Return PHP outputs on the same page

Asked

Viewed 1,414 times

0

I have a form which is validated via Javascript. It is working perfectly, it validates, sends pro .php and he gives me a echo saying it was successful. However I wanted this echo be given on the same page as a alert, or change the display of a div existing. How do I bring this PHP output to the same page? I saw that I should use Ajax, but I did not understand very well, I do not know what does what in 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;
});

  • See if this link helps you http://answall.com/questions/174883/formul%C3%A1rio-de-contato-com-ajax-sem-refresh

  • If you don’t want ajax, you can simply put the script that receives the form on the same page. At the top of the page you put a check to see if there was a POST. if( (isset($_POST['name'])) and (!Empty($_POST['name'])){ // performs the function of receiving and saving data or sending email // if everything goes right echo "<div>worked</div>"; }

  • Tiago, if possible from a quick search in "jQuery Ajax via Load", man it is very simple to use in short the command is $("#div_result"). load("codigo.php", {"name_date1": date1, "name_date2": date2}); the data is sent to PHP in load itself and in the result div_echo will be returned with the result.

1 answer

3

What is ajax?

Basically, ajax is when you call a script ( it doesn’t matter if it’s php, json, Asp, javascript, html ). This call causes javascript to search a file on the server, which you will specify which is, in this case, is the returned.php, example:

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

Please understand two things.

First, the returned.php, which is the files we call on the server through javascript ( in the example I used jquery, so you understand better ).

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

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

As you can see, it will return 5 on that variable date jquery.

Sending data to PHP

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

Here’s an example of how you’d look using $.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 requesting the returned.php, you can (optionally) put the data that will be sent to the returned.php. In this case, name and city will be sent to php using the values "Felipe" and "Verdelandia" respectively.

Notice how php looks now. Remembering that $_['POST'] and $_['GET'] should be used according to the shipment! 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 it through POST and putting it into a variable, but can be used directly.

echo $_POST["nome"] . " mora na cidade de " . $_POST["cidade"]
  • I think I kind of get it, I’m gonna put the code in the question.

  • I recommend not putting the code "to be done," I personally don’t care to help, but other Stackoverflow users may be negative and I can’t help you anymore.

  • Ata, I made the Ajax Code, same as the question of the above colleague’s comment, but it did not work :/

  • I already use the onclick event for the data to be validated by another js file.

  • @I eat that you use $.get or $.post, in your case you chose POST. I will edit to show how is sending data through the POST.

  • All right, @asurakhan, I’ll wait.

  • Okay, see if that answers your question.

  • I didn’t understand, because I just want that when the data is successfully sent by php, it gives me an Alert, that’s all. I didn’t quite understand the way you did it. Another thing, I can fire 2 functions with the same event, in case the onclick.

  • you can put a javascript in php echo "<script> Alert("sent") </script>". These functions inside onClick, are the callback. They are small functions that return or do something within a function.

  • Watch the chat, please @asurakhan

Show 6 more comments

Browser other questions tagged

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