Huma Ali Huma Ali - 24 days ago 7
jQuery Question

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

Answer

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