views:

61

answers:

6

Hi,

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

          }
        });

      }
    });

  }
});
A: 

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');
Pekka
You're not being extremely clear. You should specify that the AJAX request should be to a single server script that merges the HTML parts together into one response. I presume that is what you had in mind.
Alin Purcaru
@Alin I misunderstood the question.
Pekka
A: 

Hello Randy,

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.

Alin Purcaru
A: 

Try this:

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

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

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);
Fabrizio Calderan
You are right! Thank you.
Randy Hartmanec
you may also improve this code collecting all data responses in an array (e.g. in an external closure) so at <n-th> request you may look at data of all previous request (if you need to)
Fabrizio Calderan
A: 

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.

pst
A: 

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

AutoSponge
Thanks for tip!
Randy Hartmanec