SharpCoder
SharpCoder

Reputation: 19183

Error handling with JQuery When

I am using JQuery when. The syntax looks like this:

$.when(
  // Get the HTML
  $.get("/feature/", function(html) {
    globalStore.html = html;
  }),

  // Get the CSS
  $.get("/assets/feature.css", function(css) {
    globalStore.css = css;
  }),

  // Get the JS
  $.getScript("/assets/feature.js")

).then(function() {

  // Add CSS to page
  $("<style />").html(globalStore.css).appendTo("head");

  // Add HTML to page
  $("body").append(globalStore.html);

});

My question

  1. How can I do error handling when one of the call to the server results in exception (failure scenario) or error handling for any other scenario?
  2. Since I am making Ajax request here, how can I define timeout period for the Ajax request?

Upvotes: 2

Views: 3041

Answers (2)

JelleP
JelleP

Reputation: 1004

I think it is because the calls are async. When using:

    $.ajax({
          url: "file.php",
          type: "POST",
          async: false,
          success: function(data) {

          }
    });

The call is synchronous.

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388446

deferred.then( doneCallbacks, failCallbacks ) can take a failure filter like

$.when(
  // Get the HTML
  $.get("/feature/", function(html) {
    globalStore.html = html;
  }),

  // Get the CSS
  $.get("/assets/feature.css", function(css) {
    globalStore.css = css;
  }),

  // Get the JS
  $.getScript("/assets/feature.js")

).then(function() {

  // Add CSS to page
  $("<style />").html(globalStore.css).appendTo("head");

  // Add HTML to page
  $("body").append(globalStore.html);

}, function(){
    //there is an exception in the request
});

To setup the timeout, you can use the timeout option.

You can use it either globally like

jQuery.ajaxSetup({
    timeout: 5000
})

or use $.ajax() instead of the short version $.get() with the timeout option

Upvotes: 3

Related Questions