Randy Hartmanec
Randy Hartmanec

Reputation: 129

Loading more files via AJAX

Is it somehow possible to load more files via AJAX?

Example

$.ajax({
  url: ["test1.html", "test2.html", "test3.html"],
  success: function(data1, data2, data3) {
    // Do something  
  }
});

Because I would like to avoid callbacks...

  $.ajax({
  url: "test1.html",
  success: function(data) {

    $.ajax({
      url: "test2.html",
      success: function(data) {

        $.ajax({
          url: "test3.html",
          success: function(data) {

            // Do something

          }
        });

      }
    });

  }
});

Upvotes: 1

Views: 154

Answers (6)

user166390
user166390

Reputation:

I prefer to write recursive functions and use a stack for something like this. This will only run success or error once at the end of the processing and will fetch each url sequentially. However, fetching them sequentially may make the loading take longer because it does not allow the browser to parallelize the requests! A different variation from this just be to run all the requests parallel and just process the results sequentially.

function fetch (urls, success, error) {
  if (urls.length) {
    $.ajax({
      url: urls[0],
      success: function () {
        fetch(urls.slice(1), success, error)
      },
      error: error
    })
  } else {
    success()
  }
}

fetch(["url1.html", "url2.html", ...], function () {
  // success
}, function () {
  // failure
})

As I just typed this up, there may be some small errors, but the concept is sound. There is more that can be done such as passing values/results out, but those are left as an exercise ;-) With the same warning applying, here is a version which just processes the results sequentially -- the requests may be sent in parallel:

function fetch (urls, success, error) {
  var fetched = 0
  var results = []
  var wasError = false
  function _fetch (i) {
    if (i < urls.length) {
      $.ajax({
        url: urls[i],
        success: function (result) {
          // report success when all the results are in
          results[i] = result
          if (++fetched == urls.length) {
            success(results)
          }
        },
        error: function () {
          if (!wasError) {
            wasError = true
            error()
          }
        }
      })
      // re-prime right away
      _fetch(i + 1)
    }
  }
  _fetch(0)
}

var urls = ["url1.html", "url2.html", ...]
fetch(urls, function (results) {
  $.each(results, ...)
}, function () {
  // error :(
})

Happy coding.

Upvotes: 1

AutoSponge
AutoSponge

Reputation: 1454

SEXY.js is a jQuery plugin for "sequential ajax" in jQuery.

Upvotes: 1

fcalderan
fcalderan

Reputation:

As far as I understood you need a chain af ajax calls, in which you have a request only if the previous one was successfully completed

(function ajaxchain(i) {

    var url = ["test1.html", "test2.html", ... ];

    $.ajax({
        url       : url[i],
        success: function(data) {
           console.info('%s loaded', url[i]); 
           ajaxchain(i++);
        },
        error     : function() {
            console.warn('Chain was interrupted at file %s', url[i]); 
        }
    });
})(0);

Upvotes: 0

Sarfraz
Sarfraz

Reputation: 382696

Try this:

var arr[] = ("test1.html", "test2.html", "test3.html");

for (var i in arr){
    $.ajax({
      url: arr[i],
      success: function(response) {
        // Do something  
      }
    });
}

Upvotes: 0

Alin P.
Alin P.

Reputation: 44346

AJAX requests are, by default, asynchronous. So you don't have to wait for one to end before sending the next one. Just start them at the same time.

As for the call you proposed I doubt there is something implemented that does just that, but I don't think it's too hard to do it yourself.

Upvotes: 0

Pekka
Pekka

Reputation: 449415

Yes, it is. You just can't load full HTML structures (with BODY elements and such) - you need to use HTML snippets.

You can then e.g. inject the loaded data into a div element:

success: function(data) 
 { $("#div_id").html(data); }

jQuery also has the almost decadently lazy .load() shortcut:

$('#div_id').load('ajax/test.html');

Upvotes: 0

Related Questions