Return PHP outputs on the same page

0

I have form which is validated via JavaScript. It's working perfectly, it validates, it sends% pro% and it gives me a .php saying that it was successful. But I wanted this echo to be given on the same page as a echo , or to change the display of an existing alert . How do I bring this PHP output to the same page? I've seen that I should use Ajax, but I do not quite understand it, I do not know what does what in the AJAX code.

PHP code:

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

switch ($dificuldade) {
  case '1':
    $dificuldade = "Facil";
    break;
  case '2':
    $dificuldade = "Medio";
    break;
  case '2':
    $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();
  echo "Pergunta enviada com Sucesso";
} catch (Exception $erro) {
 echo "Não foi possivel enviar os dados" . $erro->getMessage();

}
?>

Ajax code:

  $('#form_pergunta').submit(function(e) {
   e.preventDefault();
   const pergunta = $('input[name="pergunta"]').val();
   const resposta = $('input[name="resposta"]').val();
   const dificuldade = $('input[name="dificuldade"]')
   const desafio = $('select[name="desafio"]').val();

   $.ajax({
       url: 'envia.php', // caminho para o script que vai processar os dados
   type: 'POST',
   data: {pergunta: pergunta, resposta: resposta, dificuldade: dificuldade,    desafio: desafio},
       success: function(response) {
           $('#resp').php(response);
       },
       error: function(xhr, status, error) {
           alert(xhr.responseText);
       }
    });
   return false;
});

    
asked by anonymous 07.01.2017 / 14:47

1 answer

3

What is ajax?

Basically, ajax is when you make a call to a script (it does not matter if it's php, json, asp, javascript, html). This call causes the javascript to search for a file on the server, which will specify what it is in this case is returnData.php , example:

$("button").click(function(){
    $.get("retornaDados.php", function(data, status){
        alert("Data: " + data );
    });
});

Please notice two things.

Second, Jquery will return a date . This date is the output of your php file. Let's use a simple example of php. This is the file returnsData.php

$a = 2
$b = 3
echo $a + $b;

As you can see, it will return 5 in that date variable of Jquery.

Sending data to PHP

In your code, you used $ .ajax, but it is recommended to treat directly in $ .post (in other cases, $ .get).

Here is an example of how you would use $ .post

$("button").click(function(){
    $.post("demo_test_post.asp",
    {
        name: "Donald Duck",
        city: "Duckburg"
    },
    function(data){
        alert("Data: " + data);
    });
});

Notice the lines:

        $.post("retornaDados.php",
    {
        nome: "Felipe",
        cidade: "Verdelandia"
    },

After the comma that requests the returnsData.php , you can (optionally) put the data that will be sent to the returnsData.php . In this case, name and city will be sent to php using the values "Felipe" and "Verdelandia" respectively.

Notice how php was now. Remember that $ _ ['POST'] and $ _ ['GET'] should be used accordingly! Be it $ post or $. Get

$nome = $_POST["nome"];
$cidade = $_POST["cidade"] ;
echo $nome . " mora na cidade de " . $cidade;

Explaining again, the $ _POST ["jquery variable"] method will retrieve data by sending through POST and put in a variable, but can be used directly.

echo $_POST["nome"] . " mora na cidade de " . $_POST["cidade"]
    
07.01.2017 / 14:59