I have result page where result is loaded with ajax and I have jq ui slider for price and checkboxes which change result live. On every change the result is loaded but when I start clicking fast on checkboxes and sliders it call's result every time and at some point it stops working. Placing some timer after every change is not the solution I am looking 开发者_C百科for.
You need to use a timer, but not one for each change, just 1 global timer. Each time a checkbox is checked, slider is moved, etc, set a timeout of, say, 500ms to submit your ajax request. But each time a change is made, also clear the existing timer, and set a new one.
This way, the submission only occurs after 500ms of inactivity. If the user goes click happy, the timer is cleared every time and only after they stop clicking around does the ajax get submitted.
myForm.find( 'input, textarea, select' ).bind( 'change', function( )
{
var self = $(this);
self.attr( 'changed', 'changed' ); // -- mark as modified
clearTimeout( $(document).data( 'ajaxTimer' )); // -- prevent previous changes from being submitted
$(document).data( 'ajaxTimer', setTimeout( submitData, 500 )); // -- start new timer for submission
} );
function submitData( )
{
var allInputs = myForm.find( 'input, textarea, select' );
var changedInputs.filter( '[changed]' );
allInputs.removeAttr( 'changed' ); // -- mark all as submitted
changedInputs.each( function( )
{
// gather values here
} );
// build your AJAX request here
}
As stated in this answer: Stop AJAX Request using jQuery, you can assign request to some variable and then, if this variable is set, you can stop the already pending request before making another call.
This way, the result that will take effect will be the latest one and there should be no confusion.
I paste here the answer I referenced:
var request = $.ajax({
type: 'POST',
url: 'someurl',
success: function(result){}
});
Then you can abort the request:
request.abort();
精彩评论