symfony Response with json ajax

15,565

Solution 1

well, i found the answer i had to change the controller to make it happen. thank you Yonel ! here is a link that helped me Json in controller

Controller

public function ListeThemeAction(Request $request)
{
$output=array();
    $em = $this->getDoctrine()->getEntityManager();
    if ($request->isXmlHttpRequest()) {
        $themes = $em->getRepository('WebSiteBackBundle:theme');
        $themes = $themes->findAll();
        foreach ($themes as $theme){

            $output[]=array($theme->getId(),$theme->getName());
        }
     /*   var_dump($themes);
        $json = json_encode($themes);

        $response = new Response();*/
        //            return $response->setContent($json);
        return new JsonResponse($output);

    }
    return new JsonResponse('no results found', Response::HTTP_NOT_FOUND);
}

Vue

        $(document).ready(function () {
        var $theme = $('#theme');
        $theme.append('<option value="">Choisir un thème</option>');
        $.ajax({
            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) {

                console.log(json);
                $.each(json, function (index, value) {

                    //console.log(value);
                    $('#theme').append('<option value="' + value[0]+ '">' + value[1] + '</option>');
                    $('#loading').remove();
                });
            }
        });
    });

Hoping it will help someone. thank you all for your answer it helped me a lot

Solution 2

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 Symfony 3.1
}

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

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 
});

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.

Share:
15,565
Amine Achalhi
Author by

Amine Achalhi

Updated on June 05, 2022

Comments

  • Amine Achalhi
    Amine Achalhi almost 2 years

    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

    vue

        $(document).ready(function () {
            var $theme = $('#theme');
            $theme.append('<option value="">Choisir un thème</option>');
            $.ajax({
                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)}});#}
                    console.log(json.value);
                    $.each(json, function (index, value) {
    
                        //console.log(value);
                        $('#theme').append('<option value="' + value.id + '">' + value.name + '</option>');
                        $('#loading').remove();
                    });
                }
            });
        });
    

    Controller

      public function ListeThemeAction(Request $request)
    {
    
        $em = $this->getDoctrine()->getEntityManager();
        if ($request->isXmlHttpRequest()) {
            $themes = $em->getRepository('WebSiteBackBundle:theme');
            $themes = $themes->findAll();
            //var_dump($themes);
    
            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 : console.log(json)

    • carmel
      carmel over 7 years
      can you provide some move info? what is the response from the server? what is 'undefined'? the "json.value"?
    • Amine Achalhi
      Amine Achalhi over 7 years
      the server response is 200 OK, everything seems to work, I have the same number of data in the database but I do not read the objects values
  • Amine Achalhi
    Amine Achalhi over 7 years
    how can i loop to each property of object. i guess that i already did it in the " $.each(json, function (index, value) { ..." is that right ?
  • yceruto
    yceruto over 7 years
    Yes, but it depends of your WebSiteBackBundle:Theme entity, if it contains the "id" and "value" properties. Otherwise, you should prepare these data before send the json response in your controller.