“get_ing_id” gets a string, looks to the database and retrieve relevant id data according to the string. At this example, it needs to retrieve ’65’ and ’66’ which it does successfully when the code is executed.
var ings = [];
var ingsSearch = [];
var i = 2;
var k = 0;
ings[0] = 'apple';
ings[1] = 'banana';
function next(){
for(j=0;j<i;j++){
if(ings[j] != 0){
$.ajax({
url: burl+'index.php/ajax/get_ing_id',
type: 'POST',
data: 'name='+ings[j],
success: function(data){
ingsSearch[k] = data;
alert(ingsSearch[k]);
k++;
alert(k);
}
});
}
}
alert(ingsSearch[0]);
alert(ingsSearch[1]);
}
When the code is executed, I get alert boxes in order:
- 66
- 1
- 65
- 2
- undefined
- undefined
It supposed to be like this
- 66
- 1
- 65
- 2
- 66
- 65
So where am I doing wrong? I’m not very experienced with javascript, I’ll be grateful if I get any help. Thanks for your time!
Try setting the
asyncproperty of theajaxobject tofalse. Default istrueso there is no guarantee the calls will finish sequentially:asyncpropertyDo note ShankarSangoli’s comment; the ideal way to code this is not loop-based, but to progress to the next element from the AJAX callback function.