How can I send JSON response in symfony2 controller

Mirage picture Mirage · Jul 30, 2012 · Viewed 162k times · Source

I am using jQuery to edit my form which is built in Symfony.

I am showing the form in jQuery dialog and then submitting it.

Data is entering correctly in database.

But I don't know whether I need to send some JSON back to jQuery. Actually I am bit confused with JSON thing.

Suppose I have added a row in my table with ``jQuery and when I submit the form then after data is submitted I want to send back those row data so that I can dynamically add the table row to show the data added.

I am confused how can get that data back.

This is my current code:

$editForm = $this->createForm(new StepsType(), $entity);

$request = $this->getRequest();

$editForm->bindRequest($request);

if ($editForm->isValid()) {
    $em->persist($entity);
    $em->flush();

    return $this->render('::success.html.twig');               
}

This is just the template with success message.

Answer

Vitalii Zurian picture Vitalii Zurian · Jul 30, 2012

Symfony 2.1

$response = new Response(json_encode(array('name' => $name)));
$response->headers->set('Content-Type', 'application/json');

return $response;

Symfony 2.2 and higher

You have special JsonResponse class, which serialises array to JSON:

return new JsonResponse(array('name' => $name));

But if your problem is How to serialize entity then you should have a look at JMSSerializerBundle

Assuming that you have it installed, you'll have simply to do

$serializedEntity = $this->container->get('serializer')->serialize($entity, 'json');

return new Response($serializedEntity);

You should also check for similar problems on StackOverflow: