Retrieve data json ajax [closed]

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>

return is something like:

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

I want to get the cod and name and move to php variables and work with them ... I'm not getting it.

<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, return cod and name it on the system ......

    
asked by anonymous 25.09.2017 / 14:55

1 answer

1

The "nome" is inside the key data and the key data is inside the variable of the same name ( data ), you must have imagined that the variable already represented the key, then 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;

Just to note, this does not works:

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

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

[editing]

If teste.php is actually an external service then 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 suppose 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 at site.php 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']; ?>

Then 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);
    }
});
    
25.09.2017 / 14:58