AJAX request before regular form is being submitted

后端 未结 2 914
时光取名叫无心
时光取名叫无心 2021-02-01 08:50

I have a jQuery form validation script that is executed while user is trying to submit. I would like another function with AJaX request to be executed (and completed) after the

2条回答
  •  悲&欢浪女
    2021-02-01 09:17

    In my case I had to remove the submit type from the button and then I had to call a method that checked the validity of the data I had to submit.

     
    

    Then I wrote a method that does the check and returns true if I have to stop and ask to continue:

     public ActionResult CheckBeforeSubbmission(datatype  var1)
     {
        if(var1>0)
             return Json(new { result1 = true });
        else
            return Json(new { result1 = false });
     }
    

    After that I added the javascript/ajax the code below:

      $("#submitbutton").click(function (e) {
    
            var self = $('#form');
            //A value from the form to post to the controller
            var var1 = $('#var1elementid').val();
    
    
            $.ajax({
                type: "POST",
                url: "/SomeController/CheckBeforeSubbmission",
                data: {
                    var1: var1
                },success: function (response) {
                    if (response.result1) {
                        bootbox.confirm({
                            message: "The check failed! Do you want to submit?",
                            buttons: {
                                confirm: {
                                    label: 'Yes',
                                    className: 'btn-success'
                                },
                                cancel: {
                                    label: 'Cancel',
                                    className: 'btn-danger'
                                }
                            },
                            callback: function (result) {
                                if (result) {
                                    self.submit();
                                } else {
                                    bootbox.hideAll();
                                    return false;
                                }
                                return false;
                            }
                        });
                    } else {
                        self.submit();
                    }
                },
                cache: false
            });
        });
    

提交回复
热议问题