How to recover query result variables via Ajax in PHP?

Asked

Viewed 4,635 times

7

I made an appointment via Ajax that returned me the variables within the 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 to specify, my system is a Ajax what makes POST in an archive PHP retrieving this information through a SELECT and stores in the variables cited. I want to send the value of these variables back to Ajax within the Success function.

1 answer

16


As I referred to in another question needs to use the echo.

To pass several variables you can make an array with them and use the echocombined 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) must use the JSON.parse() thus:

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

This way you will receive an array like this:

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

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

There is the possibility of passing an object as well, in some cases it is preferred. So in PHP you need to do so:

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

In javascript you still use JSON.parse() but you 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, use also dataType: json in AJAX to facilitate the parse of the response.

Browser other questions tagged

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