How to avoid multiple AJAX calls?

前端 未结 3 776
礼貌的吻别
礼貌的吻别 2021-01-15 06:11

I\'m submitting a form via AJAX using the code below:

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

    $.ajax({
        type: \'POST\',
        url: ajax_url,
                


        
相关标签:
3条回答
  • 2021-01-15 06:57

    Just add there some control variable:

    var isSubmitting = false;
    
    $( 'form' ).submit(function(e) {
        if(isSubmitting) {
            return;
        }
        isSubmitting = true;
        $.ajax({
            type: 'POST',
            url: ajax_url,
            dataType: 'json',
            data: {
                'action': 'my_action',
                'str': $( 'form' ).serialize()
            },
            success: function( data ) {
                isSubmitting = false;
                // Do something here.
            },
                error: function( data ) {
                isSubmitting = false;
                // Do something here.
            }
        });
        return false;
    });
    
    0 讨论(0)
  • 2021-01-15 07:00

    Disable the submit button on the first click and re-enable it, when the AJAX call comes back.

    For example:

    $( 'form' ).submit(function(e) {
        var $form = $(this);
        $form.find('submit').attr('disabled', true);
        $.ajax({
            type: 'POST',
            url: ajax_url,
            dataType: 'json',
            data: {
                'action': 'my_action',
                'str': $( 'form' ).serialize()
            },
            complete: function() {
                $form.find('submit').removeAttr('disabled');
            },
            success: function( data ) {
                // Do something here.
            },
            error: function( data ) {
                // Do something here.
            }
        });
        return false;
    });
    
    0 讨论(0)
  • 2021-01-15 07:09

    Just hide and show the submit button on submit.

    $( 'form' ).submit(function(e) {
      $('#my_button').hide();
      $.ajax({
        type: 'POST',
        url: ajax_url,
        dataType: 'json',
        data: {
            'action': 'my_action',
            'str': $( 'form' ).serialize()
        },
        success: function( data ) {
            // Do something here.
        },
        error: function( data ) {
            // Do something here.
        },
        complete: function(){
            $('#my_button').show();
        }
    });
    return false;
    

    });

    0 讨论(0)
提交回复
热议问题