1

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

  • Few tips, 1. Are you getting the $categories array in php side, 2. if you are getting the value for $categories, then try to console.log(data); 3. define the categories : var categories = data.categories; Let me know the result – RONE Aug 01 '13 at 13:16
  • @SAM 1. I've made test function before at php side and it contains variables it looks like this : public function testAction(){ $categories = $this->getDoctrine()->getRepository('VelrezDataBundle:Category')->findAll(); return new Response(var_dump( $categories )); } – Tomasz Buczeń Aug 01 '13 at 13:22
  • can you tell me the status of 2. if you are getting the value for $categories, then try to console.log(data); So that i can get some clue by any chance – RONE Aug 01 '13 at 13:24
  • the output is like this:`array(5) { [0]=> object(Proj\DataBundle\Entity\Category)#333 (2) { ["name":"Proj\DataBundle\Entity\Category":private]=> string(8) "Test2" ["id":"Proj\DataBundle\Entity\Category":private]=> int(17) } [1]=> object(Proj\DataBundle\Entity\Category)#334 (2) { ["name":"Proj\DataBundle\Entity\Category":private]=> string(10) "Multimedia" ["id":"Proj\DataBundle\Entity\Category":private]=> int(15) }... } ` – Tomasz Buczeń Aug 01 '13 at 13:25
  • 2. After console.log(data) - the output is `[15:20:47.122] ({responseCode:200, categories:[{}, {}, {}, {}, {}]})` – Tomasz Buczeń Aug 01 '13 at 13:26
  • You have ready solution with json object in response in comment below. – Pawel Aug 01 '13 at 13:26
  • There you are, dear, you are returning the object array, that will not be converted into normal array, try itterating the array in php itself and create a normal array, then the flow will work – RONE Aug 01 '13 at 13:29
  • 1
    Refer this: http://stackoverflow.com/questions/4697656/using-json-encode-on-objects-in-php-regardless-of-scope – RONE Aug 01 '13 at 13:36
  • Ok, I've solved the problem using serializer. I'll paste solution right now – Tomasz Buczeń Aug 01 '13 at 14:25

1 Answers1

2

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.

Pawel
  • 1,672
  • 2
  • 18
  • 24
  • 2
    Little tip; you don't have json_encode the result, you can just supply it to the constructor of JsonResponse directly. Also be sure you use a simple object or array persister before putting it into a json response or use getArrayResult(). – Kees Schepers Feb 19 '14 at 21:31