How to access JSON values coming from ajax in a PHP page?

6

I passed these values via ajax:

$.ajax({
    url: '/loterias/cadastro.php',
    type: "POST",
    data: "{'numeros': '" + numeros + "', 'jogo':'" + jogo + "'}",
    dataType: 'application/json; charset=utf-8',
    success: function (data) {
        debugger;
        alert(data);
    },
    error: function(xhr,err){
        alert("readyState: "+xhr.readyState+"\nstatus: "+xhr.status);
        alert("responseText: "+xhr.responseText);
    } 
});

In PHP (cadastre.php) I received this way (I do not know if it's correct):

$data = json_decode(file_get_contents('php://input'), TRUE);

How can I echo the "numbers" and "game" values?

    
asked by anonymous 27.09.2014 / 17:32

2 answers

5

The dataType property refers to the type of data expected from the server, so use only 'application/json' if you want to return the response as json ...

To access the POST directly without going through decoder mount the date as a normal URI:

Jquery:

$.ajax({
    url: '/loterias/cadastro.php',
    type: "POST",
    data: "numeros=" + numeros + "&jogo=" + jogo,
   // dataType: 'application/json; charset=utf-8', // só utilize se o retorno do servidor for em json.
    success: function (data) {
        debugger;
        alert(data);
    },
    error: function(xhr,err){
        alert("readyState: "+xhr.readyState+"\nstatus: "+xhr.status);
        alert("responseText: "+xhr.responseText);
    } 
});

PHP:

print_r($_POST);

or

echo $_POST['numeros'];
echo $_POST['jogo'];
    
27.09.2014 / 18:36
4

The json_decode () function with the second TRUE parameter turns the json object into an associative array, I try

$numeros = $data['numeros'];
$jogo = $data['jogo']; 

Another aspect: you must invert the quotes in the json object because for the object to be valid in php, the name and value must be inside double quotation marks "name": "value" (in case of strings)

link

    
27.09.2014 / 18:23