Form OnSubmit to wait jQuery Ajax Return?

前端 未结 2 684
不知归路
不知归路 2020-12-20 04:32

I want to trigger $.ajax on form onsubmit and return true only after Ajax return is something valid.

For example:



        
2条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-20 05:00

    Since AJAX is asynchronous your validation Would work better using a click handler on the submit button.

    Following is based on removing the inline onSubmit

    $(function() {
    
        var $form = $('#myForm');
    
        $form.find('input[type="submit"]').click(function() {
            $.ajax({
               /* async: false,  this is deprecated*/
                type: "POST",
                url: "ajax.php",
                data: {
                    myString: $("#myString").val()
                }
            }).success(function(response) {
                alert(response); //Got 'ok'
                if(response == "ok") {
                 /*  submit the form*/
                    $form.submit();
                } else {
                    alert("Oh, string is wrong. Form Submit is cancelled.");
                }
            }); /* prevent default when submit button clicked*/
            return false;
    
        });
    });
    

提交回复
热议问题