Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
-1
rated 0 times [  2] [ 3]  / answers: 1 / hits: 117467  / 11 Years ago, thu, august 29, 2013, 12:00:00

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

How can this problem be fixed?


More From » php

 Answers
7

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'
);

[#76045] Wednesday, August 28, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
eden

Total Points: 730
Total Questions: 117
Total Answers: 117

Location: Peru
Member since Fri, Oct 14, 2022
2 Years ago
eden questions
;