Submitting JSON data via JQuery ajax.post to PHP -
im submitting data php file via ajax using post. worked fine submitting strings, wanted submit js object json , decode on php side.
in console can see, data submitted correctly on php side json_decode returns null.
i've tried 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 check alright...
and yea usual string echoed correctly :-)
where went wrong in code in first code must have used this:
var_dump(json_decode(file_get_contents("php://input"))); //and not $_post['data'] quoting php manual
php://input read-only stream allows read raw data request body.
since in case, submitting json in body, have read stream. usual method of $_post['field_name'] wont work, because post body not in urlencoded format.
in second part, must have used this:
contenttype: "application/json; charset=utf-8", url: "ajax/selectsingle.php?m=getabsence", data: json.stringify({'absence' : json.stringify(this)}), update:
when request has content type application/json, php wont parse request , give json object in $_post, must parse raw http body. json string retrieved using file_get_contents("php://input");.
if must using $_postyou make it:
data: {"data":json.stringify({'absence' : json.stringify(this)})}, and in php do:
$json = json_decode($_post['data']);
Comments
Post a Comment