Search code examples
jqueryajaxdeferred

Make ajax promise into function


I have two ajax functions that I need to complete before a 3rd one can run. I made those into two variables and used $.when to start the 3rd one.

var ilf =
    $.ajax({
        type: "POST",
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        url: '<%= ResolveUrl("../WebService/abc.asmx/GetFirst") %>',
        cache: false,
        data: null,
    }).done(function (result) {
        if (result != '') {
        }
    }).fail(function (jqXHR, textStatus, errorThrown) {
});

var rlf =
    $.ajax({
        type: "POST",
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        url: '<%= ResolveUrl("../WebService/abc.asmx/GetSecond") %>',
        cache: false,
        data: null,
    }).done(function (result) {
    }).fail(function (jqXHR, textStatus, errorThrown) {
    });

$.when(ilf, rlf) 
    .done(function (r1, r2) {
    // do whatever
});

If I want to be able to recall the $.when, how do I modify this setup? Say, in response to a button click.


Solution

  • Just put the code in a function definition.

    function ilf_rlf() {
      var ilf =
        $.ajax({
          type: "POST",
          dataType: "json",
          contentType: "application/json; charset=utf-8",
          url: '<%= ResolveUrl("../WebService/abc.asmx/GetFirst") %>',
          cache: false,
          data: null,
        }).done(function(result) {
          if (result != '') {}
        }).fail(function(jqXHR, textStatus, errorThrown) {});
    
      var rlf =
        $.ajax({
          type: "POST",
          dataType: "json",
          contentType: "application/json; charset=utf-8",
          url: '<%= ResolveUrl("../WebService/abc.asmx/GetSecond") %>',
          cache: false,
          data: null,
        }).done(function(result) {}).fail(function(jqXHR, textStatus, errorThrown) {});
    
      $.when(ilf, rlf)
        .done(function(r1, r2) {
          // do whatever
        });
    }
    
    $("#buttonid").click(ilf_rlf);