How to retrieve via Ajax query result variables in PHP?

7

I made a query via Ajax which returned the variables within PHP :

// Variaveis
$nome      = $Fetchi['nome'];
$email     = $Fetchi['email'];
$tipo      = $Fetchi['tipo'];
$senha     = "Digite uma nova senha...";
$ativado   = $Fetchi['ativado'];

How to send these variables back to my Ajax via the success function ...

success: function(result){

Just by specifying, my system is a Ajax that does POST in a PHP file that retrieves this information through a SELECT and stores in the cited variables. I want to send the value of these variables back to Ajax within the success function.

    
asked by anonymous 03.08.2014 / 14:52

1 answer

16

As I mentioned in another question you need to use echo .

To pass multiple variables you can make an array with them and use echo combined with json_encode () .

// Variaveis
$nome      = $Fetchi['nome'];
$email     = $Fetchi['email'];
$tipo      = $Fetchi['tipo'];
$senha     = "Digite uma nova senha...";
$ativado   = $Fetchi['ativado'];

$retorno = array($nome, $email, $tipo, $senha, $ativado);
echo json_encode($retorno);

On the client side (javascript) you should use JSON.parse () like this:

success: function(result){
    var resultado = JSON.parse(result);

In this way you will receive an array like this:

[nome, email, tipo, "Digite uma nova senha...", ativado]

To access senha you can use alert(resultado[3]); if you want to see all members of the array use: alert(resultado.join('\n'));

You can also pass an object , in some cases it is preferable. So in PHP you need to do this:

$retorno = array('nome'=>$nome, 'email'=>$email, 'tipo'=>$tipo, 'senha'=>$senha, 'ativao'=>$ativado);
echo json_encode($retorno);

In javascript it uses the same JSON.parse () but will receive an object in this format:

{nome: 'valor do nome', email: 'valor do email', tipo: 'valor do tipo', senha: "Digite uma nova senha...", ativao: 'valor do ativao'}

Note: As @jader suggested, also use dataType: json in AJAX to make it easier to parse the answer.

    
03.08.2014 / 14:58