How can I send JSON response in symfony2 controller
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
Return a Json Response from a Controller in Symfony
You should use $message
instead of $entityManager
as mentioned in the comments but passing the entity to new JsonResponse()
will only include public
properties from the message entity and they are usually all private
.
There are many ways to do this, but the easiest is just to insert exactly what you want with the entity's getters:
return new JsonResponse([
'result' => 'ok',
'ret' => [
'txtName' => $message->getTxtName(),
'txtMes ' => $message->getTxtMes(),
],
]);
Posting JSON objects to Symfony 2
If you want to retrieve data in your controller that's been sent as standard JSON in the request body, you can do something similar to the following:
public function yourAction()
{
$params = array();
$content = $this->get("request")->getContent();
if (!empty($content))
{
$params = json_decode($content, true); // 2nd param to get as array
}
}
Now $params
will be an array full of your JSON data. Remove the true
parameter value in the json_decode()
call to get a stdClass
object.
Return JSON based on Accept: application/json from a Symfony2 controller
This will verify if the current request is XHR and then send back properly formatted JSON data:
public function someAction(Request $request)
{
if ($request->isXmlHttpRequest()) {
$serializer = new Serializer(array(
new GetSetMethodNormalizer()
), array(
'json' => new JsonEncoder()
));
$response = $serializer->serialize(array(
'success' => true,
'data' => array(
'entity' => $entities,
)
), 'json');
return new Response($response, 200, array('Content-Type' => 'application/json'));
} else {
// Run "normal" request code, render a view
}
}
By the way, JMSSerializerBundle makes the serializing syntax more straightforward (because, let's face it, the native Symfony way for this is ugly) and also provides some additionnal features such as excluding entity fields to serialize (through annotations).
With JMS, my code looks like this:
if ($request->isXmlHttpRequest()) {
$response = array('success' => true, 'data' => array(
'entity' => $this->container->get('serializer')->serialize($entity, 'json'),
'lastPage' => $lastPage,
));
return new Response(json_encode($response), 200, array('Content-Type' => 'application/json'));
}
And finally, 'success' and 'data' are in no way required, it's just the structure I use to split status and data to be readable in JavaScript.
Return a JSON array from a Controller in Symfony
You need to do this (based on previous answer):
public function getAllCategoryAction() {
$em = $this->getDoctrine()->getManager();
$query = $em->createQuery(
'SELECT c
FROM AppBundle:Categoria c'
);
$categorias = $query->getArrayResult();
return new JsonResponse($categorias);
}
It works perfect with any Query that Doctrine returns as array.
Post json data to symfony2 controller
Had to change
data: { "data" : 'test' },
to
data: '{ "data" : 'test' }',
and use in the controller
$data = $this->get("request")->getContent();
if(!empty($data)) {
$params = json_decode($data, true);
}
Send POST Data with Ajax, withtout form, to a Symfony2 Controller, in JSON format
I found the solution.
It's not really difficult.
It is not necessary to JSonify data. The controller has the capability to understand the original datatype.
So here is my simplified AJAX call:
function validerSession()
{
obj = new Object();
obj["title"] = "Title for example";
$.ajax({
type: "POST",
url: Routing.generate('cloud_money_drop_validerSession', { id: {{ partie.id }}, idSession: sessionId }),
data: obj,
success: function (donnees) {
data = Parse.JSON(donnees);
alert(data.title); //Show "Title for example"
}
});
}
And here is my Controller. It can recover data as an array of values.
public function validerSessionAction(Partie $partie, Session $session)
{
$request = $this->get('request');
$data = $request->request->all();
$serializer = $this->container->get('jms_serializer');
$response = $serializer->serialize($data["title"], 'json');
return new Response($response);
}
Thanks for the help!
Related Topics
How to Detect and Handle MySQL Warnings with PHP
Php: Type Hinting - Difference Between 'Closure' and 'Callable'
Send Post Data via Raw JSON with Postman
Importing Multiple CSV Files to MySQL Tables
Header("Location") Causes [500] Internal Server Error
Check to See If an Email Is Already in the Database Using Prepared Statements
Is There a Function to Make a Copy of a PHP Array to Another
Check If a "Run-Time" Multidimensional Array Key Exists
How to Post Multiple <Input Type="Checkbox" /> as Array in PHP
Fully Understanding Pdo Attr_Persistent
Whats the Best Way to Do User Authentication in PHP
PHP Merge Array(S) and Delete Double Values
Setting Environment Variables in Mamp