Ok I can't seem to decode the JSON from my ajax call, which posts user data to my api, which is built in slim php..
This is my ajax..
var jsonData;
jsonData = [
{
username: "user",
password: "pass"
}
];
$.ajax({
type: "POST",
url: "http://localhost/api/user/auth",
data: {
user: JSON.stringify(jsonData)
},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
alert("You are good!");
},
error: function(xhr, type) {
alert("Y U NO WORK?");
}
});
This is my SLIM PHP code..
$app->post('/user/auth', function () use ($app) {
try {
$requestBody = $app->request()->getBody(); //This works
//RequestBody is: user=%5B%7B%22username%22%3A%22user%22%2C%22password%22%3A%22pass%22%7D%5D
$json_a = json_decode($requestBody); //This doesn't work
print_r($json_a); //Has no output?
$username = $json_a['user']['username']; //Therefore this doesn't work?
} catch(Exception $e) {
echo '{"error":{"text": "'. $e->getMessage() .'"}}';
}
});
As you can see in the comments, written in the code, requestBody equals:
user=%5B%7B%22username%22%3A%22user%22%2C%22password%22%3A%22pass%22%7D%5D
However, I can't seem to decode it, as print_r($json_a) has no effect.
Any help is much appreciated, thanks.
Try
$params_str = urldecode($requestBody);
parse_str($params_str, $params_arr);
$user = json_decode($params_arr['user']);
Youre doing it wrong... you are sending the data via post so you shoudl grab the json string from there instead of trying to manually read the request body... something like
$req = $app->request();
$json = json_decode($req->post('user'));
Now if you actually want to send a json request body thats a whole different thing, but it will require changes to your js. You need to set processData to false so that it does not try to encode the data value internally. This also means you have to pre-encode it:
$.ajax({
type: "POST",
url: "http://localhost/api/user/auth",
data: JSON.stringify({user: jsonData}), // gotta strinigfy the entire hash
processData: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
alert("You are good!");
},
error: function(xhr, type) {
alert("Y U NO WORK?");
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With