When I remove the content-Type it works, but jsonitem received in php side has syntax errors I found in other posts that I should definitely precise the content type when sending Json objects.
this code returns "failed func"
var json = {
test: "testv"
};
var data = {
action: 'ajax_load_article',
jsonitem: JSON.stringify(json),
};
var options = {
url: beloadmore.url,
dataType: "json",
contentType: "application/json;charset=utf-8",
type: "POST",
data: data,
success: function(res, status, xhr) {
if (res.success) {
console.log(res);
$('.site').append(res.data);
} else {
console.log("failed func");
console.log(res);
}
},
error: function(xhr, status, error) {
console.log(xhr.responseText);
console.log(error);
}
};
$.ajax(options);
EDIT:
php file:
$jsonitem= $_POST['jsonitem'];
$jsonitemdecoded = json_decode($jsonitem);
echo "jsonitem".$jsonitem;
echo "jsonitemencoded".$jsonitemdecoded;
echo json_last_error_msg();
echo screens when I remove contentType: 'application/json' :
jsonitem {\"test\":\"testv\"}
jsonitemencoded Syntax error
If you use application/json
as content type for the request, you should serialize the object to json before post it;
JSON.stringify(data);