简体   繁体   中英

Pulling records from database to javascript by Symfony2 controller

Im trying to fetch categories list from my database and put it in my javascript code so i can use it later. But I've encountered problems with this task - after returning this list to javascript - they are empty.

Here is my symfony2 controller action code:

public function fetchCategoriesAction(){
     $categories = $this->getDoctrine()->getRepository('MyDataBundle:Category')->findAll();
     $return=array("responseCode"=>200,  "categories"=>$categories);
     $return=json_encode($return);//jscon encode the array
     return new Response($return,200,array('Content-Type'=>'application/json'));
}

Here is my js code:

var categories;

function categoriesLoad(){

var url=$("#categories_fetch").val(); //link to my controller

$.post(url,function(data){

     if(data.responseCode==200 ){           
         categories = data.categories;
         console.log(categories);
     }else{
       console.log("An unexpeded error occured.");
    }
});

}

I'm running $(document).ready(function() { categoriesLoad(); });

But then after using console.log(categories) I'm getting empty objects, although their number match the number of records in the database.

I'm just starting programming in symfony2 and I'd appreciate any help :)

EDIT:

SOLVED

I've just changed my controller action code. Here it is updated:

public function fetchCategoriesAction(){

    $encoders = array(new XmlEncoder(), new JsonEncoder());
    $normalizers = array(new GetSetMethodNormalizer());
    $serializer = new Serializer($normalizers, $encoders);

    $em = $this->getDoctrine()->getManager();
    $categories = $em->createQuery(
            'SELECT u
            FROM MyDataBundle:Category u'
    )->getResult();

    $categories = $serializer->serialize($categories, 'json');
    $return=array("responseCode"=>200,  "categories"=>$categories);
    $return=json_encode($return);
    return new Response($return,200,array('Content-Type'=>'application/json'));
}

Now it works fine. Thanks to @Pawel and @SAM

My example: PHP function:

public function getDistrictListAction($id) {

        $em = $this->getDoctrine()->getManager();

        $query = $em->createQuery(
           // DQL
        );

        return new JsonResponse($query->getArrayResult());
    }

JS Code:

var dropdown = $('.dropdown-selector');
dropdown.change( function() {
    $.ajax({
         url: 'url_to_function'
         beforeSend: function() {
              dropdown.attr('disabled', true);
         },
         success: function(data) {
              dropdown.find('option').not('[value=]').remove();
              $.each( JSON.parse(data), function(key, value) {
                   dropdown.append( $( "<option></option>" ).attr( "value", value.id ).text( value.name ));
              });
              dropdown.attr('disabled', false);
         }
    });
}

This you can set on change event for example as a callback. Before send you make dropdown disabled, and after load via AJAX option you are enabale it again.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM