phpjsonsymfonyjsonresponsesymfony-http-foundation

Error parsing JSON returned via Symfony Component's JsonResponse


My Ajax call:

$.ajax({
    url : path,
    type: 'POST',
    dataType : 'json',
    data: data,
    success: function(memberExtra) {
        console.log (memberExtra);
    }
});

My response:

HTTP/1.0 201 Created
Cache-Control: no-cache
Content-Type:  application/json
Date:          Tue, 10 Feb 2015 23:49:09 GMT

{"memberExtras":{"label":"seller","dropdown":"abc"}}

My PHP:

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;

/**
 * Update the pulldown menus.
 *
 * @Route("/classification", name="classification")
 * @Template()
 */
public function classificationAction(Request $request)
{
    $memberType = $request->request->get('classification');

    $label = $memberType["user"]["memberType"];
    $dropdown = "abc";
    $response = new Response(json_encode(array('memberExtras' => array(
        'label' => $label,
        'dropdown' => $dropdown,
    ))), Response::HTTP_CREATED);
    $response->headers->set('Content-Type', 'application/json');

    return new Response($response);
}

The console.log doesn't output anything. Even if a regular text expression like ("test").

If I remove the dataType : 'json' declaration and attempt to manually parse the data via $.parseJSON(memberExtra), I get this error:

SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

Not too surprised. Basically, it seems that the parser gets tripped on the header returned by the Symfony class. How can I avoid this header and just get to the JSON?

Thanks!


Solution

  • try simply:

    return $response;

    instead of return

    new Response($response);

    BTW I suggest you to simply use

    return new JsonResponse($myarray) 
    

    and remove the annotation @Template from your method.

    Hope this help