Jquery Ajax Call In For Loop Only Runs Once - Possible Issue with Timing & Exit Condition?
Posted
by
Grumps
on Stack Overflow
See other posts from Stack Overflow
or by Grumps
Published on 2013-06-29T21:44:35Z
Indexed on
2013/06/29
22:21 UTC
Read the original article
Hit count: 380
Background
I'm building a form that uses autocomplete against the EchoNest API.
First the users picks an artist, using the Artist Suggest call. Next they select a song but the Song and/Or Artist song search doesn't provide a "wild card" search. It only returns exact matches. So based on the forums they suggest building an array of the songs and using auto complete on the array. I can only get a maximum of 100 responses at a time. I do know based on the initial response the number of songs.
My Plan:
- Wrap the ajax call in a for loop ('runonceloop').
- Amend the loop exit condition after the first response with the total number of songs.
Challenge I'm having:
The 'runonceloop' only completes a singe loop because or at least that's what I believe:
- The exit condition is satisfied before the first response [1] is received.
I've tried to adjust the 'exit condition' and 'counter' such that they are set and and increased at the end of the success block. This seems to lock up my browser.
Can someone provide some guidance on this situation?[2]
I'd really appreciate it.
I also don't think turning async off is a good idea because it locks the browser.
Response[1]:
{
"response": {
"status": {
"code": "0",
"message": "Success",
"version": "4.2"
},
"start": 0,
"total": 121, //Used for
"songs": [
{
"id": "SOXZYYG127F3E1B7A2",
"title": "Karma police"
},
{
"id": "SOXZABD127F3E1B7A2",
"title" : "Creep"
}
]
}
}
}
Code[2]
var songsList = [];
function getSongs() {
var numsongs = 2; //at least 2 runs.
var startindex = 0;
runonceloop: //<~~~~Referenced in question
for (var j = 0;j >= numsongs;) {
console.log('numsongs' + numsongs);
$.ajax({
url: "http://developer.echonest.com/api/v4/artist/songs",
dataType: "jsonp",
data: {
results: 100,
api_key: "XXXXXXXXXXX",
format: "jsonp",
name: $("#artist").val(),
start: startindex
},
success: function (data) {
var songs = data.response.songs;
numsongs = data.response.total; //modify exit condition
for (var i = 0; i < songs.length; i++) {
songsList.push(songs[i].title);
}
j +=100;// increase by 100 to match number of responses.
}
});
}};
© Stack Overflow or respective owner