简体   繁体   中英

How to display POST values which are coming from javascript XMLHttpRequest() in php

I am sending parameters using XMLHttpRequest() javascript function to another php page in Json formate, but $_POST['appoverGUID'] not getting post values.

Here is my Javascript code.

        function loadPage(href){

            var http = new XMLHttpRequest();
            var url = json.php;
            var approverGUID = "Test";
            var params = JSON.stringify({ appoverGUID: approverGUID });
            http.open("POST", url, true);
            http.setRequestHeader("Content-type", "application/json; charset=utf-8");
            http.setRequestHeader("Content-length", params.length);
            http.setRequestHeader("Connection", "close");
             http.onreadystatechange = function() {
                if(http.readyState == 4 && http.status == 200) {
                    document.getElementById('bottom').innerHTML = http.responseText;

                }
            } 
            http.send(params);

        }

And here is my json.php file code.

if(isset($_POST['appoverGUID'])){
echo $_POST['appoverGUID'];
}

You need use json_decode . Some like this:

if ("application/json" === getallheaders())
    $_JSON = json_decode(file_get_contents("php://input"), true) ?: [];

Fill params this way (did no escaping/encoding of approverGUID content, here..):

params = "appoverGUID="+approverGUID;

Also see:

http://www.openjs.com/articles/ajax_xmlhttp_using_post.php

First of all remove these headers since they will be send automatically by the browser and it's the right way to do it.

http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");

This code is a cross browser solution and it's tested.

// IE 5.5+ and every other browser
var xhr = new(window.XMLHttpRequest || ActiveXObject)('MSXML2.XMLHTTP.3.0');
var params = "appoverGUID="+approverGUID;
xhr.open("POST", url, true);

xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8");
xhr.setRequestHeader("Accept", "application/json");
xhr.onreadystatechange = function () {
    if (this.readyState === 4) {
        if (this.status >= 200 && this.status < 400) {
            console.log(JSON.parse(this.responseText));
        }
    }
}
xhr.send(params);
xhr = null;

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