views:

56

answers:

3

How can I get jQuery to only do an ajax query one time?

Right now it contacts the server every time a user toggles "Comments (X)"

// Replies - Toggle display of comments
$('.info .reply').click( function() {
    $('.reply', this.parentNode.parentNode).toggle();
    return false;
});

// Load comments
$('.info .reply', this).mousedown( function() {
    var id = $('form #id', this.parentNode.parentNode).val();
    $.ajax({ url: location.href, type: 'post', data: 'id=' + id, dataType: 'json',
        success: function(data) {
            for (var i in data) {
                // Do AJAX Updates
            }
        }
    });
    return false;
});

I'm thinking I can somehow put an unbind() event in here after the ajax data is loaded, but I'm not sure where!

Thanks for your help!

+4  A: 

Maybe you are looking for one()

Dr.Molle
+5  A: 

In the success function after the for loop seems like a good place.

    success: function(data) {
        for (var i in data) {
            // Do AJAX Updates
        }
        $('.info .reply').unbind();
    }

EDIT: This is only if you really must do it this way, .one() seems like a better choice.

alpha123
+1  A: 

If I were you I'd do this with $.data:

// Load comments
$('.info .reply', this).mousedown( function() {
    var id = $('form #id', this.parentNode.parentNode).val();

    if (!$.data(this, 'commentsloaded')) {
        $.ajax({ url: location.href, type: 'post', data: 'id=' + id, dataType: 'json',
            success: function(data) {
                for (var i in data) {
                    $.data(this, 'commentsloaded', true);
                    // Do AJAX Updates
                }
            }
        });
    }
    return false;
});
lonesomeday