[php] 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 :)

This question is related to php javascript jquery ajax yii

The answer is


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


Use getJSON

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

Detail look here http://api.jquery.com/jQuery.getJSON/


In my case, I forgot to tell the type controller that the response is a JSON object. response.setContentType("application/json");


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"}]

Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to ajax

Getting all files in directory with ajax Cross-Origin Read Blocking (CORB) Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource Fetch API request timeout? How do I post form data with fetch api? Ajax LARAVEL 419 POST error Laravel 5.5 ajax call 419 (unknown status) How to allow CORS in react.js? Angular 2: How to access an HTTP response body? How to post a file from a form with Axios

Examples related to yii

Only on Firefox "Loading failed for the <script> with source" Stupid error: Failed to load resource: net::ERR_CACHE_MISS Yii2 data provider default sorting Jquery - Uncaught TypeError: Cannot use 'in' operator to search for '324' in CURL ERROR: Recv failure: Connection reset by peer - PHP Curl findAll() in yii Get current URL/URI without some of $_GET variables Include CSS,javascript file in Yii Framework