i have an ajax call and it works good , when i call a new ajax call inside the old one , i got error in the first call
just one ajax call
$.getJSON("http://localhost/Mar7ba/Ontology/getRelatedConceptsAndRelations/"+conceptName+"/TRUE",function(data){
var concepts = data[0];
var relations = data[1];
for(var i = 0 ; i < concepts.length ; i++){
var IOS = '';
$("#ioAddRelatedConcepts").append('<p>\n\
connect to\n\
<span class="ioAddConcept">'+concepts[i]+'</span>\n\
with\n\
<span class="ioAddRelation">'+relations[i]+'</span>\n\
<select name ="concetedIOs[]" class="TypeSelector">\n\
'+IOS+'</select>\n\
<span class="errorMessage"></span>\n\
<a href="#" class="removeA" id="aioRemoveIO">remove</a>\n\
</p>\n\
<p>');
}
});
after adding this ajax call
$.getJSON("http://localhost/Mar7ba/Ontology/getRelatedConceptsAndRelations/"+conceptName+"/TRUE",function(data){
var concepts = data[0];
var relations = data[1];
for(var i = 0 ; i < concepts.length ; i++){
$.getJSON("http://localhost/Mar7ba/InformationObject/getIOsForConcept/"+concepts[i]+"/TRUE",function(data1){
var IOS = '';
$("#ioAddRelatedConcepts").append('<p>\n\
connect to\n\
<span class="ioAddConcept">'+concepts[i]+'</span>\n\
with\n\
<span class="ioAddRelation">'+relations[i]+'</span>\n\
<select name ="concetedIOs[]" class="TypeSelector">\n\
'+IOS+'</select>\n\
<span class="errorMessage"></span>\n\
<a href="#" class="removeA" id="aioRemoveIO">remove</a>\n\
</p>\n\
<p>');
});
}
});
after that , the concepts[i] and the relations[i] will be as undifined
and the data1.length always null
and the this is the second php code for ajax
public function getIOsForConcept($conceptName, $AJAX) {
if ($AJAX) {
$results = $this->model->getIOsForConcept($conceptName);
$IOs = array();
$i = 0;
while ($row = $results->fetch()) {
$IOs[$i] = $row['name'];
$i++;
}
return json_encode($IOs);
}
}
and i tried it and it works good
The reason that
concepts[i]and therelations[i]are undefined within the callback function of the inner$.getJSON()function is that$.getJSON()is aysnchronous which means that the entire for loop will have finished running before any of the callbacks occur on the inner$.getJSON()calls – so by the time these inner callbacks occuriis one higher than the maximum index of theconceptsandrelationsarrays.To get around this you can introduce an extra closure to keep the values from each iteration:
The anonymous function I’ve added inside the for loop will run once per iteration creating separate closures each with their own
currentConceptandcurrentRelation.EDIT: To make it really obvious what I’ve changed compared to your original code–
Add the following line as the first thing inside your existing
forloop:And then the following line as the last thing before your existing
forloop’s closing}:And then everywhere inside the
forloop where you did haveconcepts[i]andrelations[i]change them tocurrentConceptandcurrentRelation.