Receive responses from jQuery’s Ajax request

Asked

Viewed 8,678 times

3

When I send an Ajax to run my PHP script the only thing it returns is Success if the script was successfully executed or error if the script was not successfully executed. Question: How to capture PHP response and return this answer to the Ajax request for it to display or do with it? Type:

Code jQuery sending variables and doing POST

$.ajax({
      type: "POST",
      url: 'url_especifica',   
      data: {variaveis: variaveis},
      success: function (result) {
         // Como requisitar $resposta e mostrar ela aqui
      }
      error: function (result) {
         // Como requisitar $resposta e mostrar ela aqui
      }
 });

Example of PHP Insert

if($Count == 0){
    $Insert = mysql_query("INSERT INTO tbl_usuarios 
     VALUES ('', '$nome', '$email', '$tipo', '$senha', '$ativado', NOW())");
}

PHP

if(usuario_inserido_com_sucesso) { 
    $resposta: "O usuário foi inserido com sucesso"; }
else { 
    $resposta: "O usuário não foi inserido com sucesso"; }
  • 1

    If you do echo $resposta; in PHP after the if/else ajax will receive and can check with alert(result); within the function success. That’s what you’re looking for?

  • I’ll try to see if it works that way to answer you if that’s what I’m looking for. I’ll get back to you.

2 answers

3


To send data from a PHP script back to the client side you have to use echo.

echo <conteudo>;

In your case you can use it like this in your PHP:

if($Insert) $resposta = "O usuário foi inserido com sucesso";
else $resposta = "O usuário não foi inserido com sucesso";

echo $resposta;

(Note that I changed yours : for =).

And in ajax you can use it like this:

success: function (result) {
   // usar a variavel result
   alert(result);
}
  • 1

    The result can also be a Json string, so you have more control when picking up via JS. Example {error:true, msg:Error entering user, date:10/08/2014}

  • 1

    @lionbtt good comment. +1

0

I usually do like this:

jquery:

$.ajax({
    type: "POST",
    url: 'url_especifica',   
    data: {variaveis: variaveis},
    success: function (result) {
        if (result.substring(0,7) == 'sucesso') {
            $('#elemento').html(result.substring(8));
        } else {
            alert('ERRO: ' + result);
        }
    }
});

PHP:

if(usuario_inserido_com_sucesso) { 
    exit("sucessoO usuário foi inserido com sucesso");
} else { 
    exit("O usuário não foi inserido com sucesso");
}

remember that both the success and failure of the inclusion of the record, should be treated in the Success method, as it indicates the success of the ajax request, and treats the return received from PHP.

The error method, on the other hand, should be used to treat errors in the ajax request (timeout, error, abort, parsererror), and in this case it will not receive any return from the server, since it probably was not implemented...

Browser other questions tagged

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