mko
mko

Reputation: 22044

Why $_POST gets nothing from ajax request?

var httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = action;
httpRequest.open('POST','/fetch_product_list.php','true');
httpRequest.send("var=5");

but in the fetch_product_list.php, $_POST['var'] has nothing, How can I fix it?

Upvotes: 1

Views: 147

Answers (2)

Hanzel
Hanzel

Reputation: 453

Add line: httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); and hence the code looks like:

var httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = action;
httpRequest.open('POST','/fetch_product_list.php','true');
httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
httpRequest.send("var=5");

and in php use: $_POST['var'].

Upvotes: 2

Quentin
Quentin

Reputation: 943185

You haven't included a content-type for the request body.

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

Upvotes: 2

Related Questions