Note that the return
is pointless since it is the last line of the function already. It will only exit this function, but the $.each
will keep executing since it is contained in another function.
This is what happens if you break down your code:
$.each(JSEFileNames, ajaxFunction);
function ajaxFunction(key, value){
$.ajax({ url: "/"+key, success: successFunction });
}
function successFunction(r) {
$(JSEPlaceholder).html(r);
JSEFileNames[key] = $(JSEPlaceholder).text().toString().replace(/(\r\n|\n|\r)/gm,"") + $(JSEPlaceholder).children().text().toString().replace(/(\r\n|\n|\r)/gm,"");
$(JSEPlaceholder).empty();
return;
}
Here you can see that the return
is not doing what you want it to do. You will need to do a return false
inside the ajaxFunction
call for it to stop. This is an example of how you can do it:
$.each(JSEFileNames, function(key, value){
cont = true;
$.ajax({ url: "/"+key, async: false,
success: function(r){
$(JSEPlaceholder).html(r);
JSEFileNames[key] = $(JSEPlaceholder).text().toString().replace(/(\r\n|\n|\r)/gm,"") + $(JSEPlaceholder).children().text().toString().replace(/(\r\n|\n|\r)/gm,"");
$(JSEPlaceholder).empty();
cont = false;
}
});
return cont;
});
Here what happens is that a return value
with value
evaluating to false
will stop the jQuery loop; if value
is true
, the loop will keep running. See here for the official documentation.
Notice that I added async: false
; indeed, $.ajax
is an asynchronous function, and it will return before cont
can be modified. The underlying call will only be treated later, once the request succeeds or fails. One way around that is to make the request synchronous, but it will prevent the rest of your code from executing in the meantime. This is probably what you're looking for here, since you're visibly performing a search over a number of pages, and you don't want all pages to be searched at once, but rather check them one after the other.