Reputation: 907
I am making an ajax request that looks like
var object = JSON.stringify(object);
// var url = "http://"+baseURL +"/"+endpoint;
$.ajax({
contentType: "application/json",
dataType: 'json',
type:type,
data:object,
url:endpoint,
success:function(data){
if (typeof callback == "function"){
alert(data);
}
},
error: function (xhr, textStatus, errorThrown) {
console.log(xhr.statusText);
console.log(xhr.responseText);
console.log(xhr.status);
console.log(errorThrown);
}
});
where var=object
is a stringified json objectby the time it makes it into the ajax request. On the php side, I am trying to catch the variables by doing
<?php
echo ($_POST['object']);
exit;
?>
and my success call back function alerts the data as "null". What am I doing wrong?
Thanks, alex
Upvotes: 0
Views: 2090
Reputation: 24645
Skip the json.stringify you don't want the data as json text in the post body. To populate the post array it needs to be sent as application/x-www-form-urlencoded
. To do this in jquery just set the data attribute to an object instead of a string.
// remove this.... var object = JSON.stringify(object);
// var url = "http://"+baseURL +"/"+endpoint;
$.ajax({
dataType: 'json',
type:"POST", // <--- Should be post
data:object,
url:endpoint,
success:function(data){
if (typeof callback == "function"){
alert(data);
}
},
error: function (xhr, textStatus, errorThrown) {
console.log(xhr.statusText);
console.log(xhr.responseText);
console.log(xhr.status);
console.log(errorThrown);
}
});
It is possible to get the data as you are sending it currently but you have to go through a little more work on the PHP side.
$_POST = json_decode(file_get_contents("php://input"),true);
Upvotes: 1