How can I send a JSON object to a PHP?

0

I want to send a JSON string from Javascript to PHP, and then in PHP do a json_decode, but one thing fails me.

function request(data)
{
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() 
    {
        if (xhttp.readyState == 4 && xhttp.status == 200) 
        {
            var response = xhttp.responseText;
            console.log(response);
        }
    };
    xhttp.open("POST", "points.php", true);
    xhttp.send(data);
}

Where xhttp.send exits I pass a JSON.stringify.

var data = {user: user, points:points};
request(JSON.stringify(data));

My problem is the following, in PHP, that I have to put in order to receive the data variable? I have the following:

$data = json_decode($_POST["data"], true);

But I get an error:

  

Undefined index data

    
asked by marc 13.07.2016 в 11:08
source

3 answers

2

What you sent via XMLHttpRequest is a Request Payload , which basically what you do is write the payload sent in the body of the HTTP request. If you look at chrome's network console or some other browser, you'll see something like this:

which indicates that the data was not sent as application/x-www-form-urlencoded but as a text/plain or text/json .

Now, to read this data in PHP, just use the following:

$payload = file_get_contents('php://input');
var_dump($payload);
json_decode($payload);
var_dump($payload);

what returns:

string(13) "{"a":1,"b":2}"

object(stdClass)#40 (2) {
  ["a"]=>
  int(1)
  ["b"]=>
  int(2)
}

greetings

    
answered by 13.07.2016 / 11:29
source
1
  

What happens is that the Request Header ( header of the request ) is how text / plain or text / json and not application / x-www-form-urlencoded which is the format that accepts the query_string and json requests.

Step 1: In JS - Add before the onreadystatechange the Request Header .

xhr.setRequestHeader("Content-type", 'application/x-www-form-urlencoded');

Step 2: In JS - I recommend you have a parent element in the JSON

var jsonAEnviar = "json=" + JSON.stringify({user: user, points:points});

Step 3: In PHP - Modify the code by the following

$jsonRecibido = json_decode($_POST['json']);

I have attached a chuletilla that I mounted long ago for the topic of the answers treatments in PHP.

  

Ways to receive data JSON , query_string , text_plain ...

// No datos y Respuesta como 'PLAIN_TEXT'

echo 'algun_texto_plano';

// No datos y Respuesta como 'JSON'

echo json_encode(["clave"=>"valor"]);

// Datos como 'QUERY_STRING' y Respuesta como 'QUERY_STRING'

echo $_REQUEST['nombre'] . ' ' . $_REQUEST['edad'];

// Datos como 'QUERY_STRING' y Respuesta como 'JSON'

$json = ["nombre" => $_REQUEST['nombre'] , "edad" => $_REQUEST['edad']];
echo json_encode($json);

// Datos como 'JSON' y Respuesta como 'QUERY_STRING'

$json = json_decode($_REQUEST['json']);
echo $json->nombre . ' ' . $json->edad;

// Datos como 'JSON' y Respuesta como 'JSON'

$datos = json_decode($_REQUEST['json']);
$respuesta = ["nombre" => $datos->nombre , "edad" => $datos->edad];
echo json_encode($respuesta);
  

Utility class for native Ajax: Link

class Ajax {

    // OBTENER INSTANCIA AJAX

    static getXHR() {
        return typeof XMLHttpRequest != 'undefined'
            ? new XMLHttpRequest() // Navegadores modernos
            : new ActiveXObject('Microsoft.XMLHTTP'); // Navegadores obsoletos
    }

    // REALIZAR PETICIÓN GET

    static doGET(url, params = null, onFinish) {
        let xhr = Ajax.getXHR();
        xhr.open('GET', url + (params === null ? '' : '?'+params), true);
        xhr.setRequestHeader("Content-type", 'application/x-www-form-urlencoded');
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4) {
                onFinish = onFinish(xhr.status, xhr.responseText, xhr);
            }
        };
        xhr.send(null);
    };

    // REALIZAR PETICIÓN POST

    static doPOST(url, params, onFinish) {
        let xhr = Ajax.getXHR();
        xhr.open('POST', url, true);
        xhr.setRequestHeader("Content-type", 'application/x-www-form-urlencoded');
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4) {
                onFinish = onFinish(xhr.status, xhr.responseText, xhr);
            }
        };
        xhr.send(params);
    };

}
    
answered by 13.07.2016 в 11:57
0

You do not need to do anything weird look with your function.


function request(data)
{
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() 
    {
        if (xhttp.readyState == 4 && xhttp.status == 200) 
        {
            var response = xhttp.responseText;
            console.log(response);
        }
    };
    xhttp.open("POST", "points.php", true);
    xhttp.send(data);
}

In PHP you only need to use the post variable as you normally use it


$user = $_POST['user'];
$points = $_POST['points'];

    
answered by 31.10.2018 в 18:38