tags:

views:

20

answers:

2

I'm currently trying to check if the response I'm getting is empty. Now what I think will work is below:

 $.ajax({
            type: 'GET',
            url: '<%=Url.Action("FindTransaction", "Calls") %>',
            data:
            { companyID: $('#CompanyDDL').val(),
                storeID: storeNo,
                tranDate: $('#TranDate').val(),
                tranNum: $('#TranNum').val()
            },
            success: function (tData) {
                if (tData == null) {
                     $('#tranNotFound').show("blind", options, 500);
                 } else {
                     $('#products').html('');
                     $('#SKUs').html('');
                     $('#price').html('');
                    for (var i = 0; i < tData.length; i++) {
                        $('#SKUs').append(!tData ? '' : tData[i].SKUN + '<br />');
                        $('#products').append(!tData ? '' : tData[i].DESCR + '<br />');
                        $('#price').append(!tData ? '' : tData[i].EXTP + '<br />');
                    }
                    $('#till').html(!tData ? '' : tData[0].TILL);
                    $('#tran').html(!tData ? '' : tData[0].TRAN);
                    $('#cashier').html(!tData ? '' : tData[0].CashierName);
                    $('#total').html(!tData ? '' : tData[0].TOTL);
                    $('#fullTransactionDetails').show("blind", options, 500);
                }
            }
        });

I think what I'm doing will achieve what I'm aiming for however, I can't seem to find out as I'm having a second issue of tData[0] is undefined and I'm trying to fetch data for something that I know will definately return an empty response, so as far as I'm concerned, it shouldn't even hit that part of the code.

I'm at a bit of a loss with this so any help is greatly appreciated.

+1  A: 

I believe the success function will be passed a non-null string, even when no data is returned - so, you may need to check for tData == '' (in addition to checking tData==null)

Ed Schembor
A: 

If you're falling into the success handler of your $.ajax call, you're probably getting an empty object literal back (if it's a JSON dataType being returned). So you're null check is failing because it really isn't null -- it's empty.

Here's a sample of what may be going on:

$(document).ready(function() {
    var x = {};
    if (x==null) {
        alert("I am null");
    } else {
        alert(x);
    }

    if ($.isEmptyObject(x)) {
        alert("I am empty");
    } else {
        alert(x);
    }
});

In the first test, the null check will fail and you'll get an alert of 'object [Object]'. But the second test will succeed and you'll get the 'I am empty' alert.

Here's a link to it on jsFiddle: http://jsfiddle.net/pcdP2/2/

$.isEmptyObject() is in jQuery 1.4 (per the jQuery API), so it won't be available if you're not on that version.

David Hoerster