0
votes

I wrote javascript code with PHP, and wanted to send request using XMLHttpRequest. But always get $_POST null, when setRequestHeader is set. If I delete setRequestHeader, the $_POST is exist.

Here's my javascript code

var xmlhttp = new XMLHttpRequest();
var params = new FormData();
params.append('workername', name);
params.append('address', address);
params.append('email', email);
xmlhttp.open("POST", "searchworker.php", true);
//Send the proper header information along with the request
//xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

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


xmlhttp.send(params);

The code result for

print_r($_POST);`

is

Array ( [workername] => green [address] => US [email] => [email protected] )

I can receive $_POST value. But if uncomment the line

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

I will get this result

Array ( [------WebKitFormBoundaryTBeUMaDsrWBBYRFB Content-Disposition:_form-data;_name] => "workername"

green ------WebKitFormBoundaryTBeUMaDsrWBBYRFB Content-Disposition: form-data; name="address"

US ------WebKitFormBoundaryTBeUMaDsrWBBYRFB Content-Disposition: form-data; name="email"

[email protected] ------WebKitFormBoundaryTBeUMaDsrWBBYRFB--

)

And all $_POST value is null.

So should I use the setRequestHeader? Cause I read on the web, that if we use open("POST",...) we should use setRequestHeader. What's causing $_POST cannot be received if setRequestHeader is set?

2
I think when XMLHttpRequestInstance.send() takes a FormDataInstance as its argument, it's already URL encoded.StackSlave

2 Answers

1
votes

A FormData object, when posted, is formatted into a multipart/form-data body, not a urlencoded one. If you want to post the data as application/x-www-form-urlencoded, you'll need to format the post body into an urlencoded string yourself.

var params = 'workername=' + encodeURIComponent(name) + '&address=' + encodeURIComponent(address) + '&email=' + encodeURIComponent(email);
0
votes

Leave out the Content-Type header. The browser knows how to set up a FormData request.

If you look in browser dev tools network and inspect the actual headers that are sent you will see it is set as something like:

Content-Type:multipart/form-data; boundary=-----11411516529451

Also note you can pass a form element into FormData and simplify having to do all the manual appends yourself

var params = new FormData(document.forms[0]);// or other appropriate dom query