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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With