Recover json ajax data

Asked

Viewed 1,529 times

0

I have this request:

<script type="text/javascript">
    jQuery(document).ready(function(){

        jQuery('#ajax_form').submit(function(){
            var dados = jQuery( this ).serialize();

            jQuery.ajax({
                type: "POST",
                url: "teste.php",
                data: dados,
                success: function(data) {

                var nome = data["nome"];
                $("#dados_conteudo").empty();
                $("#dados_conteudo").append(data);
            }

            });

            return false;
        });
    });


    </script>

the return is something like:

{"data":{"cod":"123","nome":"Rafael"},"message":"OK","status":true}

I want to take Cod and name and move on to php variables and work with them... I’m not getting.

<form method="post" action="" id="ajax_form" align="center">
<h3 align="center"><font color=#0005E0><strong>Teste</strong></font><br><br><font color=#B22222>
<td align="right">
    <font size="4" face="Arial" color=blue>
    <b>Login</b></font>

</td><br>
<td><input name="login" type="text" id="login" /></td></tr><tr> 
<td align="right">
    <font size="4" face="Arial" color=blue>

   <b>Senha</b></font>

</td><br>
<td><input name="senha" type="password" id="senha" /></td>
<br>    <label><input type="submit" class="but but-primary" name="enviar" value="Entrar" /></label>
</form> 

If the user exists, that is, Cod is returned and name it logs into the system......

  • You can show the function/code that needs to use these values?

  • I want to run the incoming data and see if they’re registered in the system.. Helping me only to put this data on the screen separately already solves.. the rest I know how to do... Thanks!

1 answer

2

The "nome" this inside the key data and the key data is inside the variable of the same name (data), you may have imagined that the variable already represented the key, so instead of

var nome = data["nome"];

Use:

data = data.data; //Sobrescreve o valor da var com o valor de "data":...
var nome = data["nome"];
var cod = data["cod"];

Or

data = data.data;
var nome = data.nome;
var cod = data.cod;

For the record, this nay works:

$("#dados_conteudo").empty();
$("#dados_conteudo").append(data);

$(...).append is a function of jQuery to add or move HTML elements, will not convert JSON to HTML.


[editing]

If the teste.php is actually an external service so the ideal would be to authenticate via PHP itself and save the data in a session, for example in place of your teste.php (which I assume comes from another server) create a file called login.php:

<?php

if (!isset($_POST['login'], $_POST['senha'])) {
    //Se falhar
    die(json_encode(array(
        'message': 'Faltam campos',
        'status': false
    )));
}

$url = 'https://www.site-externo.com/pagina-especifica/teste.php';

//Cria o POST para CURL
$postString = http_build_query($_POST, '', '&');

$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $url); 
curl_setopt ($ch, CURLOPT_POST, true); 
curl_setopt ($ch, CURLOPT_POSTFIELDS, $postString); 

curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

//Define um User-agent
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 5.1; rv:21.0) Gecko/20100101 Firefox/21.0');

curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);

//retorna a resposta
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

//Resposta
$data = curl_exec($ch);

if($data === false) {
    //Se falhar
    die(json_encode(array(
        'message': 'erro CURL ' . curl_error($ch),
        'status': false
    )));

} else {
    $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

    if ($httpcode < 200 || $httpcode >= 300) {
        //Se falhar
        die(json_encode(array(
            'message': 'erro HTTP ' . $httpcode,
            'status': false
        )));
    }
}

//Se tudo ocorrer bem decodifica a resposta do CURL
$resposta = json_decode($data, true);

if (empty($resposta['data'])) {
    //Se falhar
    die(json_encode(array(
        'message': 'Falha em decodificar o JSON',
        'status': false
    )));
} else if (!$resposta['status']) {
    //Se falhar no servidor externo informa o erro
    die(json_encode(array(
        'message': $resposta['message'],
        'status': false
    )));
}

session_start(); //Inicia a sessão

$_SESSION['dados'] = $resposta['data']; //Salva o cod e o nome na variavel

//informa que esta OK
die(json_encode(array(
    'message': 'OK',
    'status': true
)));

Now on the php site. add this:

<?php
session_start();

...

?>

<!-- Isto é apenas um exemplo de como pegar os dados -->
<strong>Cod:</strong> <?php echo $_SESSION['dados']['nome']; ?>
<strong>Nome:</strong> <?php echo $_SESSION['dados']['cod']; ?>

So in Ajax do:

jQuery.ajax({
    type: "POST",
    url: "login.php",
    data: dados,
    success: function(data) {
       if (data.status) {
           window.location = "site.php";
       } else {
           //Informa a mensagem de erro do login.php
           alert(data.message + ', status:' + data.status);
       }
    },
    error: function (jqXHR, textStatus, errorThrown) {
        alert('erro HTTP: ' + textStatus + ': ' + jqXHR.responseText);
    }
});

Browser other questions tagged

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