2

I have a javascript which on a "submit" event does the following ajax call(which in turn triggers a python script),my problem now is that "when one submit event is going on if anyone else clicks on the submit button this ajax call should notify that a submission is in progress" ,has anyone ran into this problem?(is there a name?) ,how do fix this problem? Please suggest..

$("#main_form").submit(function(event) {
       .....................

            $.ajax({
                dataType: "json",
                type: "POST",
                contentType: "application/json",//note the contentType definition
                url: "scripts/cherrypick.py",
                data: JSON.stringify(data_cp),
                //data: data_cp,
                error : function (xhr, ajaxOptions, thrownError){
                    console.log("cherypick fail");
                    console.log(response);      
                    console.log(response['returnArray']);
                    alert(xhr.status);
                    alert(thrownError); 
                },
                success: function(response){
                    console.log("cherypick sucess");
                    console.log(response);
                    console.log(response['returnArray']);
                    var return_array = response['returnArray'];
                    console.log(return_array['faillist'].length);
                    console.log(return_array['picklist'].length);       
                    for (var i = 0; i < ip_gerrits.length; ) {
                        for (var j = 0; j < return_array['faillist'].length; ) {
                            if (ip_gerrits[i] != return_array['faillist'][j] )
                                ipgerrits_pickuplist.push(ip_gerrits[i]);
                            j++;
                        }
                        i++;
                    }
Anonymous
  • 1,823
  • 2
  • 35
  • 74
  • 1. Just a suggestion - send request 1, server starts processing and create new state variable in session, when request 2 comes in - server checks this state, if it is active - return some error code to JS, when request 1 is done, session state is removed and server is open for processing again 2. there are some technics like Comet and Long Polling, in short - JS sends requests to server that is in infinite loop and thus can freeze request or send something back to client - http://stackoverflow.com/questions/1991427/server-push-comet-vs-ape – Anonymous Jun 04 '15 at 01:30
  • @Andy - Are there sample examples on how these techniques are implemented?how to start state variable ,how to check server state ,how to remove the session state etc..,? –  Jun 04 '15 at 01:43

2 Answers2

1

Ok, as far as you want to synchronize requests processing for all users, it should be done on the server side. I assume that your server side is Python, even though you did not add relevant tag to your question. My preferences are C# and PHP, but in your case I would do the following ...

Options # 1 - Session

1) add or install preferable session module for Python, crowd recommends to use Beaker

Python Module for Session Management

2) send AJAX request to the server side script

$(form).submit(function(e) {

    var options = {
         url: "scripts/cherrypick.py"
    };

    $.ajax(options);

});

3) this server side script will have something like this code

session_opts = {
    'session.type': 'file',
    'session.data_dir': './session/',
    'session.auto': True,
}

app = beaker.middleware.SessionMiddleware(bottle.app(), session_opts)

@hook('before_request')
def setup_request():
    request.session = request.environ['beaker.session']

@route('/cherrypick')
def index():
    if 'processing' in request.session:
        data = { 'procesing': request.session['processing'] }
        return data

    processor()

def processor():

    request.session['processing'] = 1

    # Do some processing here for the first request
    # When processing is done you can clear "state" variable in session

    del request.session['processing']
    request.session.modified = True

4) Now in your JS script if you get JSON that contains key "processing" you may show alert to the user that he needs to wait until first request is processed

Option # 2 - Long Polling and Comet

Description of this option may take much more space to describe, thus it is better to look at this article, it has quite nice and clean example and implementation of long polling in Python

http://blog.oddbit.com/2013/11/23/long-polling-with-ja/

The main idea here is not to keep static session but use infinite loop instead that can send back different HTTP responses depending on some state variable :

@route('/cherrypick')
def index():

    while True :

        response = { 'processing': processing }
        print response

        if processing != 1 :
            processing = 1
            # Do some processing
            processing = 0

        sleep(5)
Community
  • 1
  • 1
Anonymous
  • 1,823
  • 2
  • 35
  • 74
  • what does `@hook('before_request')` and `@route('/cherrypick')` signify ? – carte blanche Jun 05 '15 at 23:39
  • @hook('before_request') - supposed to execute some action before each request, in this case - start session, otherwise you will need to start session in each method, @route('/cherrypick') - means that all requests that comes to this URL will be handled by method index() – Anonymous Jun 06 '15 at 00:26
  • you can change @route('cherrypick') to something like @route('scripts/cherrypick.py') or @route('/ajax-handler') or @route('/server-script') it is a URL that you will send data to within AJAX – Anonymous Jun 06 '15 at 00:34
-1

The simplest way is to close around a flag that indicates some processing is underway:

var processing = false;   
$("#main_form").submit(function(event) {
    if (processing) {
        $("#some_notification_pane").text("hold on there, turbo!");
        return;
    }
    processing = true;
    ...
    $.ajax({
        ...
        error: function(xhr, ajaxOptions, thrownError) {
            ...
            processing = false;
        },
        success: function(response) {
            ...
            processing = false;
        }
    });
    ...
});

You might also want to disable the submit button at the beginning of the submit handler (where I have processing = true) and re-enable it after receiving a response.

Erin Call
  • 1,764
  • 11
  • 15
  • does the above really work when two users are trying to click the "submit" button on two different browsers?does a different instance of the ajax call have the information of `processing` variable? –  Jun 04 '15 at 00:57
  • OH, I didn't catch that it needed to be locked for all users. That's trickier. Hm. – Erin Call Jun 04 '15 at 01:04
  • @@all - Any other inputs for the folks who are watching? –  Jun 04 '15 at 01:11