Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop Duplicate Ajax Submisions?

Tags:

jquery

ajax

I am wondering what is the best way to stop duplciate submissions when using jquery and ajax?

I come up with 2 possible ways but not sure if these are the only 2.

  1. On Ajax start disable all buttons till request is done. 2 problems I see with this though is I use jquery model dialog so I don't know how easy it would be to disable those button as I not sure if they have id's. Second I if the the request hangs the user has really no way to try again since all the buttons are disabled.

  2. I am looking into something called AjaxQueue at this time I have no clue if it is what I need or how it works since the site where the plugin is apparently down for maintenance.

http://docs.jquery.com/AjaxQueue

Edit

I think this is a spin off of what I was looking at.

http://www.protofunc.com/scripts/jquery/ajaxManager/

The only problem I see with this ajaxManager is that I think I have to change all my $.post, $.get and $.ajax ones to their type.

But what happens if I need a special parameter from $.ajax? Or that fact I like using .post and .get.

Edit 2

I think it can take in all $.ajax options. I am still looking into it. However what I am unsure about now is can I use the same constructor for all requests that will use the same options.

First you have to construct/configure a new Ajaxmanager
//create an ajaxmanager named someAjaxProfileName
var someManagedAjax = $.manageAjax.create('someAjaxProfileName', {
    queue: true, 
    cacheResponse: true
});

Or do I have to make the above every single time?

like image 727
chobo2 Avatar asked Jun 02 '10 16:06

chobo2


1 Answers

How about setting a flag when the user clicks the button? You will only clear the flag when the AJAX request completes successfully (in complete, which is called after the success and error callbacks), and you will only send an AJAX request if the flag is not set.

Related to AJAX queuing there is a plugin called jQuery Message Queuing that is very good. I've used it myself.

var requestSent = false;

jQuery("#buttonID").click(function() {   
   if(!requestSent) {
      requestSent = true;

      jQuery.ajax({
         url: "http://example.com",
         ....,
         timeout: timeoutValue,
         complete: function() {
             ...
             requestSent = false;
         },
      });
   }
});

You can set a timeout value for long-running requests (value is in milliseconds) if you think your request has a possibility of hanging. If an timeout occurs, the error callback is called, after which the complete callback gets called.

like image 110
Vivin Paliath Avatar answered Sep 28 '22 06:09

Vivin Paliath