smartius
smartius

Reputation: 653

Symfony2 JsonResponse and jQuery.parseJson()

In my controller if I return a JSON response like:

return new JsonResponse(array('numberOfRatings' => count($ratingCollection), 'oldRating' => $oldRating));

The returning object will have the following data:

protected 'data' => string '{"numberOfRatings":1,"oldRating":2}' (length=35)

But when I try to parse this with jQuery.parseJson(); it will return me an exception that jQuery is not able to parse it. But when I do:

return new JsonResponse(json_encode(array('numberOfRatings' => count($ratingCollection), 'oldRating' => $oldRating)));

What's equal to

return new Response(json_encode(array('numberOfRatings' => count($ratingCollection), 'oldRating' => $oldRating)));

The parseJson() method works great. But my mistake here cause it seems like JsonResponse is useless.

Upvotes: 0

Views: 1036

Answers (1)

xdazz
xdazz

Reputation: 160923

When you use JsonResponse, you don't need to use jQuery.parseJson(), the data you got is already a javascript object.

$.getJSON(your_url, function(data) {
   // the data is already an object, don't need to parse it.
   // var data = $.parseJSON(data); 
   // ...
});

Upvotes: 4

Related Questions