1

I try to call a function at different place. That why i return true or false. Problem i got is before hasCreditCard has time to do is call, that go directly to the else...

if (hasCreditCard($('#memberId').val())) {
  ...
}
else{
  ...
}

function hasCreditCard(memberId) {
    var url = getHostName() + "/members/" + memberId + "/creditcard";
    jQuery.ajax({
        type: "head",
        url: url,
        contentType: "application/json",
        headers: {
            "Authorization": "Basic " + $.cookie('authorization')
        },
        success: function (data, status, jqXHR) {
            if (jqXHR.status == 200) {
                return true;
            }
            return false;
        },
        error: function (jqXHR, status) {
            return false;
        }
    });
}
GG.
  • 21,083
  • 14
  • 84
  • 130
robert trudel
  • 5,283
  • 17
  • 72
  • 124
  • put your code in `ajax success`` function which you want to execute in `if` condition, and in `ajax error` function put your code which you want to execute in else part – Shaybi Dec 21 '16 at 05:04
  • you can try async: false attribute of ajax – Rahul Dec 21 '16 at 05:06

1 Answers1

1

Because an AJAX call is asynchronous and your if-statement doesn't wait the end of the call.

Two solutions:

#1: You can pass a callback to the function and call this callback in your success/error handler:

getCreditCard($('#memberId').val(), function (hasCreditCard) {
  if (hasCreditCard) {
    ...
  } else {
    ...
  }
})

function getCreditCard(memberId, nextStep) {
  ...
  jQuery.ajax({
    ...
    success: function (data, status, jqXHR) {
      if (jqXHR.status == 200) {
        nextStep(true)
        return
      }
      nextStep(false)
    },
    error: function (jqXHR, status) {
      nextStep(false)
    }
  })
}

#2: You can create another global function and call this function in your success/error handler:

getCreditCard($('#memberId').val())

function getCreditCard(memberId) {
  ...
  jQuery.ajax({
    ...
    success: function (data, status, jqXHR) {
      if (jqXHR.status == 200) {
        nextStep(true)
        return
      }
      nextStep(false)
    },
    error: function (jqXHR, status) {
      nextStep(false)
    }
  })
}

function nextStep(hasCreditCard) {
  if (hasCreditCard) {
    ...
  } else {
    ...
  }
}
GG.
  • 21,083
  • 14
  • 84
  • 130