Huma Ali
Huma Ali

Reputation: 1809

Ajax success: Data length Undefined

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

Upvotes: 6

Views: 8558

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337580

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

Upvotes: 7

Related Questions