Php Receives Empty $_post Variables From Ajax Call
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
.
Post a Comment for "Php Receives Empty $_post Variables From Ajax Call"