Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ajax success: Data length Undefined

Tags:

jquery

ajax

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

like image 316
Huma Ali Avatar asked Nov 16 '16 08:11

Huma Ali


1 Answers

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);
    }
});
like image 177
Rory McCrossan Avatar answered Oct 29 '22 14:10

Rory McCrossan