Search code examples
javascriptphppostxmlhttprequest

XMLHTTPrequest sending empty post


I've done a lot of times before, so I'm honestly confused why this is failing to pass anything. I've tried printing results (script gets a response and prints the file).

function submit_form_inpage(path, data, watchForChange){
    alert(data);
    watchForChange = watchForChange || false;
    var request = new XMLHttpRequest();
    request.open('POST', path, true);
    request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
    if (watchForChange == true) {
        request.onreadystatechange = function () {
            if (request.readyState == 4) {
                document.write(request);
                if (request.status==200 && request.status < 400){
                    var xmldata=request.responseText //retrieve result as an XML object
                    alert("XML:" + xmldata);
                }
                else{
                    alert("An error has occured making the request:" + request.status );
                }
            }
        }
    }
    var temp_string = array_to_string_for_post(data);
    var temp = JSON.stringify(data);
    alert(temp);
    request.send(temp);
}

My php is

print_r($_POST);

and my result is

XML: Array ()

Despite the fact that data passed in (which is double-checked right before being sent by my alert) is

{"reason":"get_stuff","build_name":"test"}

Solution

  • You said you were sending form encoded data.

    request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
    

    Then you sent:

    temp = JSON.stringify(data);
    

    JSON is application/json not application/x-www-form-urlencoded (and isn't natively supported by PHP anyway).

    Either encode your data as application/x-www-form-urlencoded or correct your content-type and parse it manually in PHP.