Felix
Felix

Reputation: 2661

Can't access values of Laravel's JSON response object

This might be one of the strangest bugs I've encountered.

In my controller, when a user makes a reply (through AJAX), I return a JSON response in an attempt to get the ID of that reply.

$reply = Status::create([
    'body' => $replyText,
])->user()->associate(Auth::user());

$status->replies()->save($reply);

$replyID = $reply->id;

return response()->json([
    'replyID ' => $replyID
]);

This works fine. I get a JSON reponse with what I asked for. Great.

enter image description here

Now here's the problem. For WHATEVER reason, I can't access the values of the object JSON is returning.

x = response.replyID;
console.log(x);

or

x = response["replyID"];
console.log(x);

or any variation of that will ALWAYS returned undefined.

To illustrate how stupid this is, let me demonstrate with the following:

success: function(response) {
    myObj = { "age":30 };
    console.log(response);
    console.log(myObj);
    x = myObj.age;
    y = response.replyID;
    console.log(x); 
    console.log(y);             
},

This returns:

enter image description here

What could POSSIBLY be causing this?

Upvotes: 0

Views: 1301

Answers (1)

Niklesh Raut
Niklesh Raut

Reputation: 34914

You have extra blank space 'replyID ' here remove this

return response()->json([
   'replyID' => $replyID
]);

Before applying this if you tried like this it would work

x = response["replyID "];
console.log(x);

But now, I think you understand the problem came from one blank space.

Upvotes: 3

Related Questions