6

Why am I getting undefined in data.length in the ajax.sucess?

Here is the code,some parts have removed for sake of brevity:

$.ajax({
    data: JSON.stringify(data),
    url: urlGetProviderQualificationTimeData,
    type: 'POST',
    contentType: "application/json; charset=utf-8",
    success: function (data) {
        if (data.length > 0) {
            $("#loading").hide();
            $("#providerqualification-main").show();
            $("#tblProviders").show();
            SetHeaderFields(data);
        } else {
            $("#NoRecordFound").show();
            $("#providerqualification-main").hide();
        }
    },
    complete: function (e) {
        $("#loading").hide();
    }
});

enter image description here

Sumurai8
  • 20,333
  • 11
  • 66
  • 100
Huma Ali
  • 1,759
  • 7
  • 40
  • 66

1 Answers1

7

Your data object doesn't have a length property (and Object's don't have one as Arrays do), so it's undefined.

Given the context of your code you simply want to check if the returned object has some data within it. If so, you can use this:

success: function (data) {
    if (!data || !Object.keys(data).length) {
        $("#NoRecordFound").show();
        $("#providerqualification-main").hide();
    } else {
        $("#loading").hide();
        $("#providerqualification-main").show();
        $("#tblProviders").show();
        SetHeaderFields(data);
    }
});
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • Does this mean that if any of the property would be null, it will be true? – Huma Ali Nov 16 '16 at 09:30
  • No, it checks if the object exists and that it has at least one property. The value of that property can be null and it would still pass as valid – Rory McCrossan Nov 16 '16 at 09:30
  • OK. So my data has Object and in it I have properties. Still it doesn't pass the if condition and goes into the else. – Huma Ali Nov 16 '16 at 09:34
  • That's correct behaviour, as I said, if the object has properties (no matter what their value is) it will hit the `else` statement above – Rory McCrossan Nov 16 '16 at 09:35
  • So there is no way I can check if those properties have null or not? – Huma Ali Nov 16 '16 at 09:36
  • 1
    Yes there is, you need to loop through the object: http://stackoverflow.com/questions/27709636/determning-if-all-attributes-on-a-javascript-object-are-null-or-the-empty-string – Rory McCrossan Nov 16 '16 at 09:40