Pull php echo into a div, no refresh

Asked

Viewed 1,287 times

1

I have a div in html, it has None display, I fill in the form and the data goes to a file. php and the same gives me an echo saying that the data was entered into the database, only that I wanted when php gave this echo this div that I have taken the message and displayed.

HTML:

           <form id="form_pergunta" action="php/envia.php" Method="POST">
  <!--pergunta!-->
  <label for="input">Pergunta</label>
  <div class="input-group">
  <span class="input-group-addon"><span class="glyphicon glyphicon-question-sign" aria-hidden="true"></span></span>
  <input type="text" name="pergunta" data-placement="bottom" class="form-control" placeholder="Ex: Quem é Jeová, com base no Biblia Ensina Pg. 10, Cap: 5?" aria-describedby="basic-addon1">
  </div><br>
  <div class="alert alert-danger" id="valida_pergunta" role="alert">
  <span class="glyphicon glyphicon-info-sign"></span> Preencha o campo Pergunta
  </div>
  <!--pergunta!-->
  <!--resposta!-->
  <label for="input">Resposta:</label>
  <div class="input-group">
  <span class="input-group-addon" ><span class="glyphicon glyphicon-ok-circle" aria-hidden="true"></span></span>
  <input type="text" name="resposta" class="form-control" placeholder="Ex: É Deus." aria-describedby="basic-addon1">
  </div><br>
  <div class="alert alert-danger" id="valida_resposta" role="alert">
  <span class="glyphicon glyphicon-info-sign"></span> Preencha o campo Resposta
  </div>
  <!--resposta!-->
  <!--Desafio!-->
  <label for="input">Desafio:</label>
  <div class="input-group">
  <span class="input-group-addon" ><span class="glyphicon glyphicon-list-alt" aria-hidden="true"></span></span>
  <input type="text" name="desafio" class="form-control" placeholder="Ex: Fique 10 segundos pulando num pé só." aria-describedby="basic-addon1">
  </div><br>
  <div class="alert alert-danger" id="valida_desafio" role="alert">
  <span class="glyphicon glyphicon-info-sign"></span> Preencha o campo Desafio
  </div>
  <!--Desafio!-->



  <div class="form-group">
  <label for="select">Selecione a Dificuldade</label>
  <select class="form-control" name="dificuldade">
  <option value="1">Fácil</option>
  <option value="2">Médio</option>
  <option value="3">Difícil</option>
  </select>
  </div>
  <center><input type="button" class="btn btn-primary btn-lg" value="Enviar" id="enviar"></center><br><br>
  </form>

PHP:

  <?php
    $pergunta = $_POST ['pergunta'];
    $resposta = $_POST ['resposta'];
    $dificuldade = $_POST ['dificuldade'];
    $desafio = $_POST ['desafio'];
    $msg;

    switch ($dificuldade) {
       case '1':
        $dificuldade = "Facil";
        break;
       case '2':
        $dificuldade = "Medio";
        break;
       case '3':
        $dificuldade = "Dificil";
       break;
    }

    try{
          $conexao = new PDO ("mysql:host=localhost;dbname=teocratico;charset=utf8","root","");
     } catch (PDOException $erro){
       echo "Não foi possível conectar ao banco ". $erro->getMessage();

     }

    try {
    $insert =  $conexao-> prepare ("INSERT INTO perguntas (pergunta,  resposta, dificuldade, desafio) VALUES (

       :pergunta,
       :resposta,
       :dificuldade,
       :desafio
        )");
      $insert-> bindParam (':pergunta', $pergunta);
      $insert-> bindParam (':resposta', $resposta);
      $insert-> bindParam (':dificuldade', $dificuldade);
      $insert-> bindParam (':desafio', $desafio);
      $insert-> execute();

      $msg = "Pergunta enviada com Sucesso";
      echo $msg;
         } catch (Exception $erro) {
       echo "Não foi possivel enviar os dados" . $erro->getMessage();

     }
     ?>

JAVASCRIPT VALIDATING THE FORM:

//Executar todo nosso JS quando o DOM estiver pronto. Por isso o Onload

window.onload = Function(){

var button = Document.getElementById("send"); // takes the button value var form = Document.getElementById("form_question"); //take the form of the whole question button.addeventlistener("click", Function(e){ if(validate(form)) form.(); });/With access to this, we can perform a function every time the button is clicked, for this let’s use addeventlistener() on the button and put the following logic: IF THE VALIDATE FUNCTION RETURNS TRUE, PLEASE SUBMIT TO THE FORM/

//Now the function validate. This will receive a parameter which is the form itself that we have recovered above. Function validar (form_question){ var question = form_question.question.value; var answer = form_question.resposta.value; var challenge = form_question.desafio.value; var passed = true; if(question ==""){ Document.getElementById("valida_question").style.display = "flex"; passed = false; } Else { Document.getElementById("valida_question").style.display = "None"; } if (answer == "") { Document.getElementById("valida_response").style.display ="flex"; passed = false; } Else { Document.getElementById('valida_resposta').style.display = "None"; } if (challenge ==""){ Document.getElementById("valida_challenge").style.display = "flex"; passed = false; } Else { Document.getElementById("valida_challenge").style.display = "None"; } Return passed;

}

}

  • 1

    You need to use AJAX, see if this answer helps you...http://answall.com/questions/163498/%C3%89-poss%C3%Advel-fazer-Submit-sem-dar-refresh-e-sem-jquery/163505#163505

  • A..........j..... .a.......x

  • No need for ajax needed. Just replicate the div code in the reply.

  • I’m pulling from an external action, the scipts are not in the same doc

1 answer

4


Send the data from form without refresh and with "validation"; Captures the response of php in resp and fills the div; Shows refresh button to renew the form

<script>
$(function () {
    $('#refresh').click(function () {
        window.location = window.location;
    });
    // Comportamento do botao de envio do FORM
    $('#enviar').click(function () {
        if(validar() === true){
            // Se a validacao passar, carrega os dados do FORM e envia
            $.post(
                $("#form_pergunta").attr("action"),// Captura o ACTION do FORM
                $("#form_pergunta").serialize() // Captura os campos do FORM 
            )
            // Se enviar com sucesso, retorna a resposta do PHP
            .done(function (resp) {
                $("#success").attr('class','alert alert-success');
                $("#success").html(resp); //Preenche a DIV com a resp
                $('#success').show(); //Mostra a DIV
                $("#form_pergunta input").prop("disabled", true);
                $("#form_pergunta select").prop("disabled", true);
                $('#enviar').hide(); //oculta o botao de envio
                $('#refresh').show(); //Mostra o botao de refresh
            })
            // Se o envio falhar, retorna uma msg de erro
            .fail(function (resp) {
                $("#success").attr('class','alert alert-danger'); //Muda o CSS da DIV
                $("#success").html('Falha no envio!'); //Preenche a DIV com a msg
                $('#success').show(); //Mostra a DIV
            });
        } else {

        }
    });
});
// Validacao do FORM ao enviar
function validar() {
    var passou = true;
    if ($('#pergunta').val() === "") {
        $('#valida_pergunta').show();
        passou = false;
    } else {
        $('#valida_pergunta').hide();
    }
    if ($('#resposta').val() === "") {
        $('#valida_resposta').show();
        passou = false;
    } else {
        $('#valida_resposta').hide();
    }
    if ($('#desafio').val() === "") {
        $('#valida_desafio').show();
        passou = false;
    } else {
        $('#valida_desafio').hide();
    }
    return passou;
}
</script>
  • The sending part of the form and avoiding sending with Enter I n understood very well, I saw some codes like this ó: http://answall.com/questions/174883/formul%C3%A1rio-de-contact-with-ajax-without-refresh

  • I tried to use and could not, my problem is not being validate or send, I just want that when successfully send the data to the bank, it gives me a return on successful div. or at least take php echo and throw me in this div.

  • But it’s exactly what that code does. What’s your question?

  • Okay, I think the mistake was mine, I’ll test again, hold on.

  • I made the code by putting the data of my HTML, but now it generates a new form when I click to send.

  • and does not send anything else. , nor validates

  • Just so we’re clear, you want this to work refresheless, Isn’t it? Edit the question and show your FORM for me to adapt the JavaScript.

  • Yes, I have a div for each field and one for when it is successful they are all with display None, if at the time of validating, the fields are empty, it changes the display of div, and it becomes visible, I wanted that when he could send the form and php could put things in the database, he showed the div that says "Data sent successfully"

  • :D But that’s exactly what my answer does. You’re just not being able to adapt in your code. Show the FORM and I make the adaptations and explain what was done, ok?

Show 5 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.