0

I am a bit stuck with my script: I am trying to live search through my pages via jQuery and AJAX. In this example I want to search in 2 sites for a keyword and I want to break the AJAX-loop when I have found something:

var urls = [
    'http://docs.db-dzine.com/woocommerce-advanced-categories/',
    'http://docs.db-dzine.com/woocommerce-catalog-mode/',
];
var found = false;
$.each(urls, function(i, url) {
    ajaxSearchPage(url, keyword, function(found) {
        console.log(found);
        if(found) {
            return true;
        }
    });
    if(found) {
        return true;
    }
});

I do not know how to break the loop here ... please help.

And my AJAX Function:

var ajaxSearchPage = function(url, keyword, callback) {
    $.ajax({
        url: url, 
        type: "GET",
        dataType: "html",
        success: function(response) {

            // Do not load images
            var page = response.replace(/<img/gi, '<noload');
            // Create parsable body for jQuery
            var body = $('<div id="body-mock">' + page.replace(/^[\s\S]*<body.*?>|<\/body>[\s\S]*$/ig, '') + '</div>');

            // Find the keyword in content
            var content = body.find('#content:containsNC("'+ keyword +'")');
            if(content.length > 0) {
                searchResultsWrapper.show();
                callback(true);
            } else {
                callback(false);
            }
        }
    });
};
  • Just use `break;` . Here is an nice article https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/break and this http://stackoverflow.com/questions/183161/best-way-to-break-from-nested-loops-in-javascript – Pugazh Aug 19 '16 at 14:18
  • 2
    To break a `$.each` loop, you have to return `false` in the loop callback. – palaѕн Aug 19 '16 at 14:19
  • I have answered today a similar [question here](http://stackoverflow.com/a/39037589/1267304). You can do like I did there, and you will be able to quit the *loop* whenever you want. – DontVoteMeDown Aug 19 '16 at 14:24
  • Just a "Break" does not answer this, because the Ajax requests will still be fired ... and I can not check if found is true and then break, because I need to wait for the Ajax request. – Daniel Barenkamp Aug 19 '16 at 14:50

2 Answers2

2

jQuery documentation states:

We can break the $.each() loop at a particular iteration by making the callback function return false. Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration.

Pugazh
  • 9,453
  • 5
  • 33
  • 54
0

AJAX calls are a deferred operation so your whole loop is likely to run. This is because you cannot know when all the network requests will complete. If you look at jQuery.ajax you will notice that it returns a jqXHR object. jqXHR has an abort method to cancel the network request.

So what we actually want to do is cancel all the requests once we have the desired result. To do that we will have to queue up the requests and then cancel.

var ajaxQueue = [];
$.each(urls, function(i, url) {
    ajaxQueue.push(ajaxSearchPage(url, keyword, function(found) {
        if(found) {
            ajaxQueue.forEach(jqXHR=>jqXHR.abort());
        }
    }));
});