Amine Achalhi Amine Achalhi - 1 year ago 176
Ajax Question

symfony Response with json ajax

I'm new in Symfony i wanted to do some manipulation such I can get a list of all elemets in the entity Theme via Ajax but the answer is still "undefined" Here the code text strong


$(document).ready(function () {
var $theme = $('#theme');
$theme.append('<option value="">Choisir un thème</option>');
type: 'post',
url: '{{ path('web_site_liste_theme_cmb') }}',
dataType: 'json',
beforeSend: function () {
$('#themediv').append('<div id="loading" style=" float: left; display: block;"><img src="{{ asset('bundles/BackBundle/img/loadingicon.gif') }}"/></div>');
success: function (json) {
{#$('#theme').append({{ dump(json)}});#}
$.each(json, function (index, value) {

$('#theme').append('<option value="' + + '">' + + '</option>');


public function ListeThemeAction(Request $request)

$em = $this->getDoctrine()->getEntityManager();
if ($request->isXmlHttpRequest()) {
$themes = $em->getRepository('WebSiteBackBundle:theme');
$themes = $themes->findAll();

return new JsonResponse($json);
return new JsonResponse('no results found', Response::HTTP_NOT_FOUND); // constant for 404


the server response is 200 OK, everything seems to work, I have the same number of data in the database but I can't read the objects values

and here is the :

Answer Source

There is many ways to do that, I show you one of them.

First, prepare you data to send from controller and returns a JsonResponse instance with you data:

public function fooAction()
    $data = ['foo1' => 'bar1', 'foo2' => 'bar2'];

    return new JsonResponse($data); //or $this->json($data) since Symfony3 

Second, use the same data structure to access from Javascript callback function:

$.post('{{ path('web_site_liste_theme_cmb') }}', function (data) {
    console.log(data['foo1']); //output bar1
    console.log(data.foo2);    //output bar2 

The JsonResponse tells the browser that data sent must be interpreted as JSON, otherwise these data are interpreted as plain/text by default.

In your question your data sent was the array of objects, so you needs loop for this variable "json" (array) and access to each property of object.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download