I’m trying to loop through an array that gets returned from a php file.
If I run this:
$.ajax({
type: "POST",
url: "lib/search/search.standards_one.php",
async: "false",
dataType: "json",
data: {subjects: subjects, grades: grades},
success: function(response){
$("#standards_results").html("");
$.each(response[0], function(){
console.log(this['code'], this['standard_id']);
});
}
});
everything works perfectly.
but, I need to loop through this response using an array (grades) as parameters.
like this:
$.ajax({
type: "POST",
url: "lib/search/search.standards_one.php",
async: "false",
dataType: "json",
data: {subjects: subjects, grades: grades},
success: function(response){
$("#standards_results").html("");
var len = grades.length;
var param = "";
for(var x=0; x < len; x++){
param = grades[x];
$.each(response[param], function(){
console.log(this['code'], this['standard_id']);
});
}
}
});
however, when I run this I get the “Cannot read property ‘length’ of undefined” error.
I’ve tried a number of different solutions, but I still arrive at this result.
////
this is where the JSON object gets created:
private function retrieve_standards_one(){
$dbh = $this->connect();
$stmt = $dbh->prepare("SELECT code, standard_one_id
FROM standard_one
WHERE grade_id = :grade_id
ORDER BY standard_one_id");
$stnd = array();
for($x = 0; $x < (count($this->grades)); $x++){
$stmt->bindParam(':grade_id', $this->grades[$x], PDO::PARAM_STR);
$stmt->execute();
$stnd[] = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
$json = json_encode($stnd);
return $json;
}
gradesis out of scope of your success function, that is why it is undefined. The ajax is asynchronous, so the call is fired off, and yoursuccessfunction is only executed when the response is received (and it was successful).A quick fix would be to put the vars you need in the global scope, or get them from
responseif they are in there.