$. post return 2 values

Asked

Viewed 372 times

2

I have following code:

 <script>

    $.post('http://localhost/app/user.php', {acao: acao}, function(retorna){ 

     $("#demo").html(retorna);

     if(retorna == "sucesso") {faça x}

    });

 </script>

But in the user.php he returns several echo dentros of conditions if. So if I have in PHP, for example, echo "sucesso"; and another echo "sucesso"; he returns success.

I would like to know how I do to catch each of that return separately?

1 answer

3


To redeem each information of this return, use the function json_encode and return only one echo for your Javascript.

Example:

$resposta['status'] = 'success';
$resposta['line'] = 1;

echo json_encode($resposta);

After the execution of that echo has a format JSON:

{"status":"success","line":1}

On the return of your javascript do:

jQuery.post()

 <script>

    $.post('http://localhost/app/user.php', {acao: acao}, 
    function(retorna)
    { 

        if (retorna.status == 'success')
        {
           //faça alguma coisa 
        }

        if (retorna.line == 1)
        {
            //faça mais alguma coisa
        }
    },'json');

 </script>

That is, returns a data(s) in format JSON, so that your Javascript, work with the return information. Also can be received a information list.

References:

  • João, I did what you did and it returned in JSON format: {"status":"Success","line":1} but I’m not getting the condition in javascript with the return status..

  • @rhundler tries like this > var data = jQuery.parseJSON(returns); then data.

  • @rhundler lacked a configuration in his javascript now that I saw, I’ve done the editing! look there need not convert anything saw! At the end of the function(retorna){}, 'json'); so that he understands that the return is a json

  • @rhundler The type of data expected from the server. Default: Intelligent Guess (xml, json, script, text, html). missing to specify the return! link: https://api.jquery.com/jquery.post/. I edited in my reply

  • 1

    Excellent! It worked perfectly after adding json. Thank you!

Browser other questions tagged

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