PHP does not receive Json POST

0

I'm trying to create a Send function via Ajax with pure JavaScript, but PHP does not receive the data.

JavaScript is sending the data correctly.

JavaScript code:

    this._data = JSON.stringify(data);
    Object.freeze(this);

    function reqListener() {
        console.log(this.responseText);
    };

    let request = new XMLHttpRequest();
    request.onload = reqListener;;
    request.open('POST', '/api');
    request.setRequestHeader('Content-Type', 'application/json;');
    request.send(this._data);

I tried to use application / x-www-form-urlencoded also without success.

PHP code:

$jSon = array(); 
$getPost = file_get_contents('php://input');
$post = json_decode($getPost);
echo json_encode($jSon);    

The purpose of these codes is to send a JSON via Ajax and PHP to return it.

    
asked by anonymous 20.05.2017 / 12:44

1 answer

0

You have an almost functional example except for two details (object freeze in javascript and use an empty variable in json_encode). Running the minimal example runs everything as expected. See:

<script>
    var data = { "name":"John", "age":30, "city":"New York"};
    this._data = JSON.stringify(data);
    //Object.freeze(this);

    function reqListener() {
    console.log(this.responseText);
    };

    let request = new XMLHttpRequest();
    request.onload = reqListener;;
    request.open('POST', '/stackoverflow.php');
    request.setRequestHeader('Content-Type', 'application/json;');
    request.send(this._data);
</script>

Already in php:

<?php
$jSon = array(); 
$getPost = file_get_contents('php://input');
$jSon = json_decode($getPost);
echo json_encode($jSon);

Looking in the browser debugger you can see that the submitted data is returned by the script in php.

    
20.05.2017 / 23:59