Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I send JSON response in symfony2 controller

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.

like image 375
Mirage Avatar asked Jul 30 '12 03:07

Mirage


People also ask

How does REST API send JSON data?

To post JSON to a REST API endpoint, you must send an HTTP POST request to the REST API server and provide JSON data in the body of the POST message. You also need to specify the data type in the body of the POST message using the Content-Type: application/json request header.

How do I get response JSON?

To return JSON from the server, you must include the JSON data in the body of the HTTP response message and provide a "Content-Type: application/json" response header. The Content-Type response header allows the client to interpret the data in the response body correctly.


2 Answers

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:

  • How to encode Doctrine entities to JSON in Symfony 2.0 AJAX application?
  • Symfony 2 Doctrine export to JSON
like image 167
Vitalii Zurian Avatar answered Oct 07 '22 05:10

Vitalii Zurian


Symfony 2.1 has a JsonResponse class.

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

The passed in array will be JSON encoded the status code will default to 200 and the content type will be set to application/json.

There is also a handy setCallback function for JSONP.

like image 44
jmaloney Avatar answered Oct 07 '22 06:10

jmaloney