简体   繁体   中英

Mutually exclusive submits

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++;
                    }

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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM