Reputation: 12537
I have a javascript event listener on the search.html.twig
page that will trigger an ajax request. In the example below, my goal is for the ajax call to be successful so the alert()
message is executed.
I am used to the flat PHP approach:
echo json_encode($myAry);
Symfony's routing system makes returning an json response to ajax confusing. I am currently getting an internal server error 500.
I appreciate any advice on how to troubeshoot this. Thank in advance!
DefaultController
public function showCompanyAction($id)
{
$repository = $this->getDoctrine()->getRepository('TestBundle:Company');
//get company based on id
//prepare json object
//return it to search.html.twig
return new JsonResponse(array('name' => 'hello'));
}
JQuery (search.html.twig)
{% block jquery %}
<script>
$(function(){
$.ajax({
type: "POST",
url: "../company/booth/2",
dataType: 'json',
success: function(msg){
alert(msg);
}
})
});
</script>
{% endblock %}
Upvotes: 4
Views: 9628
Reputation: 5139
To process a JsonResponse with jQuery, you can do it with the "each" function:
public function showCompanyAction($id)
{
return new JsonResponse(
array(
array('name' => 'hello'),
array('name' => 'bye'),
)
);
}
{% block jquery %}
<script>
$(function() {
$.ajax({
type: "POST",
url: "../company/booth/2",
dataType: 'json',
success: function(data) {
$.each(data, function (index, element) {
alert(element.name);
});
}
})
});
</script>
{% endblock %}
Upvotes: 0
Reputation: 6256
Jivan's answer is good, here is a more maintainable alternative:
use Symfony\Component\HttpFoundation\JsonResponse;
class YourController
{
public function yourAction()
{
$response = new JsonResponse();
$response->setData(array('message' => 'hello'));
return $response;
}
}
With this solution, you don't need to encode the array and specify the response headers (Content-Type
and all). If the specificity of JSON responses change then you won't have to worry about updating your code.
Upvotes: 4
Reputation: 23038
To return a json response in Symfony2, you have to return this from the controller called by the route defined for company/booth/2
:
use Symfony\Component\HttpFoundation\Response;
class YourController
{
public function YourAction()
{
$response = json_encode(array('message' => 'hello'));
return new Response($response, 200, array(
'Content-Type' => 'application/json'
));
}
}
The 200
in the response is the Http Status Code. 200 means "the request was fulfilled".
Upvotes: 3