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
  • 34,719
  • 24
  • 185
  • 251
BobFlemming
  • 2,010
  • 11
  • 43
  • 58

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,692
  • 2
  • 13
  • 16
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,157
  • 10
  • 147
  • 130