Jquery - Uncaught TypeError: Cannot use 'in' operator to search for '324' in

I'm trying to send a Get request by ajax and output json data that is returned by server in html.

But, I got this error.

Uncaught TypeError: Cannot use 'in' operator to search for '324' in 
[{"id":50,"name":"SEO"},{"id":22,"name":"LPO",}]

This is my code that sends a Get request to php file by ajax. When I use $.each method, it get the error that I showed in the above.

parentCat.on('change', function(e){
    parentCatId = $(this).val();

    $.get(
        'index.php?r=admin/post/ajax',
        {"parentCatId":parentCatId},
        function(data){                     
            $.each(data, function(key, value){
                console.log(key + ":" + value)
            })
        }
    )

})

This is my PHP code that returns query result in json format.

public function actionAjax(){

    $parentCatId=$_GET['parentCatId'];

        $catData = Category::getTargetCategoryData($parentCatId);

        echo CJSON::encode($catData);
        Yii::app()->end();

}

json data outputted by this php is like this.

[{"id":50,"name":"SEO"},{"id":22,"name":"LPO",}]

Anyone knows how to fix this problem?

Please help me out. Thanks in advance :)


You have a JSON string, not an object. Tell jQuery that you expect a JSON response and it will parse it for you. Either use $.getJSON instead of $.get, or pass the dataType argument to $.get:

$.get(
    'index.php?r=admin/post/ajax',
    {"parentCatId":parentCatId},
    function(data){                     
        $.each(data, function(key, value){
            console.log(key + ":" + value)
        })
    },
    'json'
);

You can also use $.parseJSON(data) that will explicit convert a string thats come from a PHP script to a real JSON array.


If you're fetching JSON, use $.getJSON() so it automatically converts the JSON to a JS Object.


I fixed a similar error by adding the json dataType like so:

$.ajax({
    type: "POST",
    url: "someUrl",
    dataType: "json",
    data: {
        varname1 : "varvalue1",
        varname2 : "varvalue2"
    },
    success: function (data) {
        $.each(data, function (varname, varvalue){
            ...
        });  
    }
});

And in my controller I had to use double quotes around any strings like so (note: they have to be escaped in java):

@RequestMapping(value = "/someUrl", method=RequestMethod.POST)
@ResponseBody
public String getJsonData(@RequestBody String parameters) {
    // parameters = varname1=varvalue1&varname2=varvalue2
    String exampleData = "{\"somename1\":\"somevalue1\",\"somename2\":\"somevalue2\"}";
    return exampleData;
}

So, you could try using double quotes around your numbers if they are being used as strings (and remove that last comma):

[{"id":"50","name":"SEO"},{"id":"22","name":"LPO"}]