简体   繁体   中英

AJAX JSON Post to PHP

I'm trying to post JSON String via AJAX to PHP, but all examples not work.
First of all I learn https://www.w3schools.com/js/js_json_php.asp
https://www.w3schools.com/js/tryit.asp?filename=tryjson_php_db_post
Then i write own code. But no one of my example code below not working. And return one result:

index.php:6:string '[object Object]' (length=15)
index.php:7:null
index.php:8:null

First variant:

<?php

    $JsonPost   = file_get_contents('php://input');
    if ($JsonPost != null) {
        var_dump($JsonPost);
        var_dump(json_decode($JsonPost, true));
        var_dump(json_decode($JsonPost));
    } else {
    ?>
    <html> 
        <script type="text/javascript">
            var RequestObject = new XMLHttpRequest();
            RequestObject.open("POST", window.location.href, true)
            RequestObject.setRequestHeader('Content-type', 'application/json');

            var SomeObject      = {};
            SomeObject.Field1   = 'lalala';
            SomeObject.Array1   = [
                'lala1', 'lala2'
            ];

            RequestObject.onreadystatechange = function() {
                if (RequestObject.readyState == 4 && RequestObject.status == 200) {
                    document.getElementById("body").innerHTML = RequestObject.responseText;
                }
            };

            var JsonStr = {JsonPost: JSON.stringify(SomeObject)};
            RequestObject.send(JsonStr);
        </script>
    <body id="body"></body> 
    </html>
    <?php 
    }
    ?>

Second variant:

<?php

if (isset($_POST['JsonPost'])) {
    var_dump($_POST['JsonPost']);
    var_dump(json_decode($_POST['JsonPost'], true));
    var_dump(json_decode($_POST['JsonPost']));
} else {
?>
<html> 
    <script type="text/javascript">
        var RequestObject = new XMLHttpRequest();
        RequestObject.open("POST", window.location.href, true)
        RequestObject.setRequestHeader('Content-type', 'application/x-www-form-urlencoded; charset=utf-8');

        var SomeObject      = {};
        SomeObject.Field1   = 'lalala';
        SomeObject.Array1   = [
            'lala1', 'lala2'
        ];

        RequestObject.onreadystatechange = function() {
            if (RequestObject.readyState == 4 && RequestObject.status == 200) {
                document.getElementById("body").innerHTML = RequestObject.responseText;
            }
        };

        var JsonStr = {JsonPost: JSON.stringify(SomeObject)};
        RequestObject.send("JsonPost=" + JsonStr);
    </script>
<body id="body"></body> 
</html>
<?php 
}

?>

Please help.
PHP Version 5.6.28
XAMPP v3.2.2 on Windows 10 (64-bit)
Browser Chrome 56.0.2924.87 (64-bit)

UPDATED

Working Example.

<?php

$JsonPost   = file_get_contents('php://input');
if ($JsonPost != null) {
    var_dump($JsonPost);
    var_dump(json_decode($JsonPost, true));
    var_dump(json_decode($JsonPost));
} else {
    ?>
<html> 
    <script type="text/javascript">
        var RequestObject = new XMLHttpRequest();
        RequestObject.open("POST", window.location.href, true)
        RequestObject.setRequestHeader('Content-type', 'application/json');

        var SomeObject      = {};
        SomeObject.Field1   = 'lalala';
        SomeObject.Array1   = [
            'lala1', 'lala2'
        ];

        RequestObject.onreadystatechange = function() {
            if (RequestObject.readyState == 4 && RequestObject.status == 200) {
                document.getElementById("body").innerHTML = RequestObject.responseText;
            }
        };

        //var JsonStr = {JsonPost: JSON.stringify(SomeObject)};
        var JsonStr = JSON.stringify(SomeObject);
        RequestObject.send(JsonStr);
    </script>
<body id="body"></body> 
</html>
<?php 
}
?>

Many thanks to all who answered.

Change in you Second variant this:

    var JsonStr = {JsonPost: JSON.stringify(SomeObject)};
    RequestObject.send("JsonPost=" + JsonStr);

to

    RequestObject.send("JsonPost=" + JSON.stringify(SomeObject));

Why:

  • var JsonStr = { creates an new real javascript object
  • but this object can not used with + to concate it
 var JsonStr = {JsonPost: JSON.stringify(SomeObject)}; RequestObject.send(JsonStr); 

Here you are:

  1. Creating some JSON
  2. Setting the JSON as the value of an object property
  3. Implicitly converting the object to a string (which will be "[object Object]" )
  4. Sending that string as the request body

But since you are trying to post JSON you should skip steps 2 and 3 … just pass the JSON:

RequestObject.send(JSON.stringify(SomeObject));

Your problem is this:

var JsonStr = {JsonPost: JSON.stringify(SomeObject)};

that is still a javasript object, you have to stringifly the whole thing

so this should wok:

var JsonStr = JSON.stringify({JsonPost: SomeObject});
RequestObject.send(JsonStr);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM