NoBullMan
NoBullMan

Reputation: 2184

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.

Upvotes: 0

Views: 28

Answers (1)

Barmar
Barmar

Reputation: 780769

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);

Upvotes: 2

Related Questions