Only execute jQuery ajax request once

How can I get jQuery only once for ajax request?

Right now, he contacts the server every time the user switches "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 think I can somehow put the unbind () event here after loading ajax data, but I'm not sure where!

Thank you for your help!

+4
source share
3 answers

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

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

EDIT: This is only if you really have to do it this way .one () seems to be the best choice.

+5
source

Perhaps you are looking for one ()

+4
source

If I were you, I would do it 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; }); 
+1
source

All Articles