3

I'm trying to return JSONP from Symfony2. I can return a regular JSON response fine, but it seems as if the JSON response class is ignoring my callback.

$.ajax({
        type: 'GET',
        url: url,
        async: true,
        jsonpCallback: 'callback',
        contentType: "application/json",
        dataType: 'jsonp',                      
        success: function(data) 
        {                                   
              console.log(data);
        },
        error: function() 
        {
            console.log('failed');
        }
        });   

Then in my controller:

$callback = $request->get('callback');    
$response = new JsonResponse($result, 200, array(), $callback);
return $response;

The response I get from this is always regular JSON. No callback wrapping.

The Json Response class is here:

https://github.com/symfony/symfony/blob/master/src/Symfony/Component/HttpFoundation/JsonResponse.php

Cœur
  • 37,241
  • 25
  • 195
  • 267
BobFlemming
  • 2,040
  • 11
  • 43
  • 59

2 Answers2

13

As the docs says:

$response = new JsonResponse($result, 200, array(), $callback);

You're setting the callback method as the $headers parameter.

So you need to:

$response = new JsonResponse($result, 200, array());
$response->setCallback($callback);
return $response;
Max Małecki
  • 1,700
  • 2
  • 13
  • 18
1

The JsonResponse's constructor doesn't take the callback argument. You need to set it via a method call:

$response = new JsonResponse($result);
$response->setCallback($callback);

return $response;
Elnur Abdurrakhimov
  • 44,533
  • 10
  • 148
  • 133