php - slim framework sending and recieving json -
im doing simple post, reason no matter do, cant read json data
$.ajax({ url: 'server/account/session', type: 'post', data: { "username": name, "password": password} , contenttype: 'application/json; charset=utf-8', datatype: "json", success: function (data) { sessionstorage.accesstoken = data["token"]; sessionstorage.userid = data["userid"]; alert ( sessionstorage.accesstoken ); }, error: function () { } });
data: {"username": "chips", "password": "potato"}
my php:
$result = json_decode($app->request->getbody(), true); var_dump($result);
would result in null. don't why return null, sent json decode in php a. array, isnt im doing?
question two: 2) related question:
if send through jquery.post
jquery.post("server/account/session", { "username": name, "password": password}, function(data){ var result = json.parse(data); sessionstorage.accesstoken = result["token"]; sessionstorage.userid = result["userid"]; alert ( sessionstorage.accesstoken ); });
and recieve in php $userid = $app->request->params('username');
it works perfectly, question is, thought when post, data sent through body instead of header. how when jquery.post, can recieve app's request->params??
edit:
ok fixed problem. turn out if specify content type json. doesnt mean convert data json. had json.stringify on data.
but can me on second question?
answer question 2; not have json.stringify() @ all, when use right method:
var data = { username: user, password: pass }; $.ajax({ datatype: 'json', method: 'post', url: 'server/account/session', data: data, success: function (data) { console.log(data); } }) .always(function () { $('body') .removeclass('loading'); });
this should generate proper json-request automatically parsed $_post, $_request php in general , can understood slim.
Comments
Post a Comment