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

Asked

Viewed 1,160 times

6

I passed via ajax those values:

$.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 (registration.php) I received so (I do not know if it is correct):

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

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

2 answers

5


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

To access the POST directly without going through Coder 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'];

4

The json_decode() function with the second TRUE parameter transforms the json object into an associative array, tentative;

$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 quotes "name":"value" (in the case of strings)

http://php.net/manual/en/function.json-decode.php

  • 1

    You are right, the json_decode is failing because an invalid JSON is being posted.

Browser other questions tagged

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