Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ajax + JSON Decode + Slim PHP problems?

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.

like image 723
Danny Avatar asked May 11 '26 08:05

Danny


2 Answers

Try

$params_str = urldecode($requestBody);
parse_str($params_str, $params_arr);
$user = json_decode($params_arr['user']);
like image 157
air4x Avatar answered May 14 '26 00:05

air4x


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?");
  }
});
like image 38
prodigitalson Avatar answered May 13 '26 23:05

prodigitalson