Im submitting Data to a php file via AJAX using POST.
It worked fine with just submitting strings, but now I wanted to submit my JS Object with JSON and decode it on PHP side.
In the console I can see, that my data is submitted correctly but on PHP side json_decode returns NULL.
I’ve tried the following:
this.getAbsence = function()
{
alert(JSON.stringify(this));
jQuery.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "ajax/selectSingle.php?m=getAbsence",
data: JSON.stringify(this),
success : function(data){
alert(data);
}
});
}
PHP:
echo $_POST['data'];
echo json_decode($_POST['data']);
echo var_dump(json_decode($_POST['data']));
And:
this.getAbsence = function()
{
alert(JSON.stringify(this));
jQuery.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "ajax/selectSingle.php?m=getAbsence",
data: {'Absence' : JSON.stringify(this)},
success : function(data){
alert(data);
}
});
}
PHP:
echo $_POST['Absence'];
echo json_decode($_POST['Absence']);
echo var_dump(json_decode($_POST['Absence']));
The alert was just to check everything is alright…
And yea usual string were echoed correctly 🙂
Where you went wrong in your code in the first code is that you must have used this:
Quoting from PHP Manual
Since in your case, you are submitting a JSON in the body, you have to read it from this stream. Usual method of
$_POST['field_name']wont work, because the post body is not in an URLencoded format.In the second part, you must have used this:
UPDATE:
When request has a content type
application/json, PHP wont parse the request and give you the JSON object in$_POST, you must parse it yourself from the raw HTTP body. The JSON string is retrieved usingfile_get_contents("php://input");.If you must get that using
$_POSTyou would make it:And then in PHP do: