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.
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.
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.
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With