Search code examples
jquery-1.5

jQuery 1.5 AJAX syntax


I'm learning the new jQuery $.ajax callback syntax.
Q: If I move req.success outside of the $('td.showcities').click function, then how should I refer to $tr?

// When the user clicks on a state, the list of cities will appear. 
$('td.showcities').click(function(){
    var $tr = $(this).closest('tr');
    var StateID = $tr.data('StateID');
    var StateName = $(this).next().text();
    var req = $.ajax({
        url: 'Remote/City.cfc?queryFormat=column'
        ,data: {
            method:'WhereStateID'
            ,returnformat:'json'
            ,StateID:StateID
        }
    });
    req.success(function(result){
        $('.highlight').removeClass('highlight');
        $('.err').removeClass('err');
        if (result.MSG == '') {
            $tr.addClass('highlight');
            var qryCity = result.qry.DATA; // Normalize
            qryCity.RecordCount = result.qry.ROWCOUNT; // Normalize
            qryCity.ColumnList = result.qry.COLUMNS; // Normalize
            var TableData = '';
            for (var i = 0; i < qryCity.RecordCount; i++) {
                TableData
                +='<tr data-CityID="' + qryCity.CITYID[i] + '">'
                + '<td>' + qryCity.CITYNAME[i] + '</td>'
                + '</tr>';
            };
            $('#cities tbody').empty().append(TableData);
            $('#cities thead th').text(StateName);
        } else {
            $tr.addClass('err');
            $('#msg').text(result.MSG).addClass('err');
        };
    });
});

Solution

  • Among the many different things you can do, probably the most convenient is passing the $tr variable as the context option to your ajax call:

    var req = $.ajax({
        url: 'Remote/City.cfc?queryFormat=column'
        ,data: {
            method:'WhereStateID'
            ,returnformat:'json'
            ,StateID:StateID
        },
        context: $tr
    });
    

    In your success callback, the value of $tr will become the this variable:

    req.success(success);
    
    ...
    
    function success(result){
        $('.highlight').removeClass('highlight');
        $('.err').removeClass('err');
        if (result.MSG == '') {
            this.addClass('highlight'); // <---
        ...