1

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');
        };
    });
});
Haim Evgi
  • 123,187
  • 45
  • 217
  • 223
Phillip Senn
  • 46,771
  • 90
  • 257
  • 373

2 Answers2

1

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'); // <---
    ...
Ates Goral
  • 137,716
  • 26
  • 137
  • 190
  • This is odd: When I use context, then I lose the following events: .ajaxSend, .ajaxSuccess, .ajaxComplete. – Phillip Senn Feb 28 '11 at 19:15
  • Come to think of it, the success and error methods have to be at the same level as where the req variable is declared, so I may as well leave them all withi the click event. – Phillip Senn Feb 28 '11 at 22:28
1

You may find this post of mine useful. It explains the new deferred/promise API of AJAX in jQuery 1.5.

Community
  • 1
  • 1
rsp
  • 107,747
  • 29
  • 201
  • 177