Skip to content Skip to sidebar Skip to footer

Php Receives Empty $_post Variables From Ajax Call

I am trying to send form data to a PHP script by using an AJAX call. I'm serializing the form data and sending it as a JSON variable, by a POST method, to a PHP script. Ajax data v

Solution 1:

By using $('#contact-form').serialize() you make jQuery convert the data from regular fields to a HTTP query string key=val&key2=val2&... - but now you set in $.ajax that the contentType is application/json, which makes jQuery set a HTTP header Content-Type: application/json to the request. jQuery will not complain that it might be the wrong Content-Type - you should know it the best.

Since the POST-Request has the Content-Type application/json, PHP will not parse the HTTP POST data into the superglobal $_POST. Instead you have to read the raw POST data from php://input.

Your problem is now, that you tell the HTTP POST data is JSON, but it's really not JSON what you send - it's a HTTP query string. Since it's a HTTP query string, you can remove contentType: "application/json", from your $.ajax call, which will make jQuery set the correct Content-Type header.

jQuery will set the Content-Type header to application/x-www-form-urlencoded - which is the correct Content-Type header for you. Since that is one of the Content-Type PHP parses, the HTTP POST data is now available in the superglobal $_POST.

$_POST will only be filled on specific Content-Types, namely multipart/form-data and application/x-www-form-urlencoded. If the HTTP Content-Type is neither of them, $_POST will not be filled and you have to read the RAW POST data from php://input.

http://php.net/manual/en/reserved.variables.post.php

Post a Comment for "Php Receives Empty $_post Variables From Ajax Call"