user2219493
user2219493

Reputation: 13

jquery ajax get success

Can somebody tell me how to ensure the below code only returns success when msg is not null.

Occasionally it fires the success function even when msg.Text is undefined.

$.ajax({
    async: true,
    url: url,
    type: "GET",
    data: params,
    success: function (msg) {
        if (msg.Text != undefined) {
            $('#mediumText').val(msg.Text).blur();
        } else {
            console.log("failed to load");
            return false;
        }
    }
});

Upvotes: 1

Views: 5405

Answers (4)

Vimal Stan
Vimal Stan

Reputation: 2005

You could just check for a falsey value:

  if (msg.Text) {
     ...
  } else {
     ...
  }

Upvotes: 1

Zoltan.Tamasi
Zoltan.Tamasi

Reputation: 1391

If msg.Text is undefined that does not mean the call was unsuccessful, so it is completely OK to call success function. You must check msg.Text inside success callback.

Upvotes: 1

tamilmani
tamilmani

Reputation: 591

you can check the length and its empty ot not.

$.ajax({
async: true,
url: url,
type: "GET",
data: params,
success: function (msg) 
{
      if (msg.Text != null && msg.Text.Length > 0) 
      {
           $('#mediumText').val(msg.Text).blur();
      }
      else
      {
          console.log("failed to load");
          return false;
      }
}
});

Upvotes: 1

enb081
enb081

Reputation: 4051

You can check the length of the response:

$.ajax({
    async: true,
    url: url,
    type: "GET",
    data: params,
    success: function (msg) {
        if (msg.Text != undefined) {
            if (msg.Text.Length > 0) {
                $('#mediumText').val(msg.Text).blur();
            } else {
                console.log("failed to load");
                return false;
            }
        } else {
            console.log("failed to load");
            return false;
        }
    }
});

Upvotes: 1

Related Questions