I have this simple JSON request
var jsonObject = {apiKey:'123123',method:'asdfsadfasdf',ip:'123.232.123.12'};
$.ajax({
url: "http://api.example.com/users/add",
type: "POST",
data: jsonObject,
dataType: "json",
success: function (result) {
switch (result) {
case true:
alert(result);
break;
default:
break;
}
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
posting to a slim API
$app->post('/add', function () use ($app) {
$user = $app->request->post() ;
$ip = $user['ip'];
$method = $user['method'];
$apiKey = $user['apiKey'];
});
however the alert in the javascript shows 123123 when I return apiKey but other 2 parameters show 'Unexpected token' even though the response in Chrome console shows the correct value.
With the dataType
setting in $.ajax
, you are expecting that the response from the server should be a json
valid string. From the documentation:
"json": Evaluates the response as JSON and returns a JavaScript object. [...] The JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown.
It seems like that you want to return back your parameters. To do that just print data in the right way (encode it in JSON):
$app->post('/users/add', function () use ($app) {
$user = $app->request->post() ;
$ip = $user['ip'];
$method = $user['method'];
$apiKey = $user['apiKey'];
echo json_encode($user);
});
Now you can access to that data using the result
parameter of success
$.ajax
callback.
If you want you could also print strings directly, using double quotes:
echo "\"$method\"";
your json parse will work correctly now.
Numbers (e.g. apiKey
) work without issues because they are numbers and they don't need double quotes.
Further reading: JSON.parse() documentation of MDN.