How to make JQuery-AJAX request synchronous

前端 未结 7 1984
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-30 09:55

How do i make an ajax request synchronous?

I have a form which needs to be submitted. But it needs to be submitted only when the user enters the correct password.

相关标签:
7条回答
  • 2020-11-30 10:16

    It's as simple as the one below, and works like a charm.

    My solution perfectly answers your question: How to make JQuery-AJAX request synchronous

    Set ajax to synchronous before the ajax call, and then reset it after your ajax call:

    $.ajaxSetup({async: false});
    
    $ajax({ajax call....});
    
    $.ajaxSetup({async: true});
    

    In your case it would look like this:

    $.ajaxSetup({async: false});
    
    $.ajax({
            type: "POST",
            async: "false",
            url: "checkpass.php",
            data: "password="+password,
            success: function(html) {
                var arr=$.parseJSON(html);
                if(arr == "Successful") {
                    return true;
                } else {
                    return false;
                }
            }
        });
    
    
    $.ajaxSetup({async: true});
    

    I hope it helps :)

    0 讨论(0)
  • 2020-11-30 10:31

    Can you try this,

    var ajaxSubmit = function(formE1) {
    
                var password = $.trim($('#employee_password').val());
    
                 $.ajax({
                    type: "POST",
                    async: "false",
                    url: "checkpass.php",
                    data: "password="+password,
                    success: function(html) {
                        var arr=$.parseJSON(html);
                        if(arr == "Successful")
                        { 
                             **$("form[name='form']").submit();**
                            return true;
                        }
                        else
                        {    return false;
                        }
                    }
                });
                  **return false;**
            }
    
    0 讨论(0)
  • 2020-11-30 10:32

    try this

    the solution is, work with callbacks like this

    $(function() {
    
        var jForm = $('form[name=form]');
        var jPWField = $('#employee_password');
    
        function getCheckedState() {
            return jForm.data('checked_state');
        };
    
        function setChecked(s) {
            jForm.data('checked_state', s);
        };
    
    
        jPWField.change(function() {
            //reset checked thing
            setChecked(null);
        }).trigger('change');
    
        jForm.submit(function(){
            switch(getCheckedState()) {
                case 'valid':
                    return true;
                case 'invalid':
                    //invalid, don submit
                    return false;
                default:
                    //make your check
                    var password = $.trim(jPWField.val());
    
                    $.ajax({
                        type: "POST",
                        async: "false",
                        url: "checkpass.php",
                        data: {
                            "password": $.trim(jPWField.val);
                        }
                        success: function(html) {
                            var arr=$.parseJSON(html);
                            setChecked(arr == "Successful" ? 'valid': 'invalid');
                            //submit again
                            jForm.submit();
                        }
                        });
                    return false;
            }
    
        });
     });
    
    0 讨论(0)
  • 2020-11-30 10:34

    Instead of adding onSubmit event, you can prevent the default action for submit button.

    So, in the following html:

    <form name="form" action="insert.php" method="post">
        <input type='submit' />
    </form>​
    

    first, prevent submit button action. Then make the ajax call asynchronously, and submit the form when the password is correct.

    $('input[type=submit]').click(function(e) {
        e.preventDefault(); //prevent form submit when button is clicked
    
        var password = $.trim($('#employee_password').val());
    
         $.ajax({
            type: "POST",
            url: "checkpass.php",
            data: "password="+password,
            success: function(html) {
                var arr=$.parseJSON(html);
                var $form = $('form');
                if(arr == "Successful")
                {    
                    $form.submit(); //submit the form if the password is correct
                }
            }
        });
    });​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
    
    0 讨论(0)
  • 2020-11-30 10:35

    From jQuery.ajax()

    async Boolean
    Default: true
    By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous requests, set this option to false.

    So in your request, you must do async: false instead of async: "false".

    Update:

    The return value of ajaxSubmit is not the return value of the success: function(){...}. ajaxSubmit returns no value at all, which is equivalent to undefined, which in turn evaluates to true.

    And that is the reason, why the form is always submitted and is independent of sending the request synchronous or not.

    If you want to submit the form only, when the response is "Successful", you must return false from ajaxSubmit and then submit the form in the success function, as @halilb already suggested.

    Something along these lines should work

    function ajaxSubmit() {
        var password = $.trim($('#employee_password').val());
        $.ajax({
            type: "POST",
            url: "checkpass.php",
            data: "password="+password,
            success: function(response) {
                if(response == "Successful")
                {
                    $('form').removeAttr('onsubmit'); // prevent endless loop
                    $('form').submit();
                }
            }
        });
    
        return false;
    }
    
    0 讨论(0)
  • 2020-11-30 10:37

    The below is a working example. Add async:false.

    const response = $.ajax({
                        type:"POST",
                        dataType:"json",
                        async:false, 
                        url:"your-url",
                        data:{"data":"data"}                        
                    });                   
     console.log("response: ", response);
    
    0 讨论(0)
提交回复
热议问题