如何在表单提交后进行Jquery回调?

时间:2022-11-24 11:05:41

I have a simple form with remote=true.

我有一个简单的形式remote=true。

This form is actually on an HTML Dialog , which gets closed as soon as the Submit button is clicked.

这个表单实际上是在一个HTML对话框上,一旦单击Submit按钮,该对话框就会被关闭。

Now I need to make some changes on the main HTML page , after the form gets submitted successfully .

现在,在表单成功提交之后,我需要在主HTML页面上做一些更改。

I tried this using jQuery. But this doesnt ensure that the tasks get performed after some form of response of the form submission.

我用jQuery尝试过。但这并不能确保在表单提交的某种形式的响应之后执行任务。

$("#myform").submit(function(event) {

// do the task here ..

});

How do I attach a callback , so that my code gets executed only after the form is successfully submitted ? Is there anyway to add some .success or .complete callback to the form ?

如何附加回调,以便只有在成功提交表单之后才能执行代码?在表单中添加一些.success或.complete回调吗?

6 个解决方案

#1


97  

I just did this -

我刚刚做了-

 $("#myform").bind('ajax:complete', function() {

         // tasks to do 


   });

And things worked perfectly .

一切都很顺利。

See this api documentation for more specific details.

有关更具体的细节,请参阅此api文档。

#2


23  

I could not get the number one upvoted solution to work reliably, but have found this works. Not sure if it's required or not, but I do not have an action or method attribute on the tag, which ensures the POST is handled by the $.ajax function and gives you the callback option.

我无法使第一个向上投票的解决方案可靠地工作,但我发现这是可行的。不确定是否需要它,但是我在标记上没有操作或方法属性,这确保POST是由$处理的。ajax函数,并提供回调选项。

<form id="form">
...
<button type="submit"></button>
</form>

<script>
$(document).ready(function() {
  $("#form_selector").submit(function() {

    $.ajax({
     type: "POST",
      url: "form_handler.php",
      data: $(this).serialize(),
      success: function() {
        // callback code here
       }
    })

  })
})
</script>

#3


22  

You'll have to do things manually with an AJAX call to the server. This will require you to override the form as well.

您必须通过对服务器的AJAX调用来手动执行操作。这也要求您重写表单。

But don't worry, it's a piece of cake. Here's an overview on how you'll go about working with your form:

但别担心,这是小菜一碟。下面是关于如何处理表单的概述:

  • override the default submit action (thanks to the passed in event object, that has a preventDefault method)
  • 覆盖默认的提交操作(感谢传入的event对象,该对象具有preventDefault方法)
  • grab all necessary values from the form
  • 从窗体中获取所有必要的值
  • fire off an HTTP request
  • 启动HTTP请求
  • handle the response to the request
  • 处理对请求的响应

First, you'll have to cancel the form submit action like so:

首先,您必须取消表单提交操作,如下所示:

$("#myform").submit(function(event) {
    // Cancels the form's submit action.
    event.preventDefault();
});

And then, grab the value of the data. Let's just assume you have one text box.

然后,获取数据的值。假设你有一个文本框。

$("#myform").submit(function(event) {
    event.preventDefault();
    var val = $(this).find('input[type="text"]').val();
});

And then fire off a request. Let's just assume it's a POST request.

然后发出请求。假设这是一个POST请求。

$("#myform").submit(function(event) {
    event.preventDefault();
    var val = $(this).find('input[type="text"]').val();

    // I like to use defers :)
    deferred = $.post("http://somewhere.com", { val: val });

    deferred.success(function () {
        // Do your stuff.
    });

    deferred.error(function () {
        // Handle any errors here.
    });
});

And this should about do it.

这是应该的。

Note 2: For parsing the form's data, it's preferable that you use a plugin. It will make your life really easy, as well as provide a nice semantic that mimics an actual form submit action.

注意2:对于解析表单数据,最好使用插件。它将使您的生活变得非常简单,并且提供一个很好的语义,模仿实际的表单提交操作。

Note 2: You don't have to use defers. It's just a personal preference. You can equally do the following, and it should work, too.

注意2:您不必使用defers。这只是个人喜好。您可以同样地执行以下操作,并且它也应该工作。

$.post("http://somewhere.com", { val: val }, function () {
    // Start partying here.
}, function () {
    // Handle the bad news here.
});

#4


7  

I do not believe there is a callback-function like the one you describe.

我不相信会有像您描述的那样的回调函数。

What is normal here is to do the alterations using some server-side language, like PHP.

这里通常使用一些服务器端语言(如PHP)进行更改。

In PHP you could for instance fetch a hidden field from your form and do some changes if it is present.

在PHP中,您可以从窗体中获取隐藏字段,如果存在,则进行一些更改。

PHP:

PHP:

  $someHiddenVar = $_POST["hidden_field"];
    if (!empty($someHiddenVar)) {
        // do something 
    }

One way to go about it in Jquery is to use Ajax. You could listen to submit, return false to cancel its default behaviour and use jQuery.post() instead. jQuery.post has a success-callback.

在Jquery中进行此操作的一种方法是使用Ajax。您可以侦听submit,返回false以取消其默认行为并使用jQuery.post()。jQuery。帖子success-callback。

$.post("test.php", $("#testform").serialize(), function(data) {
  $('.result').html(data);
});

http://api.jquery.com/jQuery.post/

http://api.jquery.com/jQuery.post/

#5


7  

For MVC here was an even easier approach. You need to use the Ajax form and set the AjaxOptions

对于MVC,这是一种更简单的方法。您需要使用Ajax表单并设置AjaxOptions

@using (Ajax.BeginForm("UploadTrainingMedia", "CreateTest", new AjaxOptions() { HttpMethod = "POST", OnComplete = "displayUploadMediaMsg" }, new { enctype = "multipart/form-data", id = "frmUploadTrainingMedia" }))
{ 
  ... html for form
}

here is the submission code, this is in the document ready section and ties the onclick event of the button to to submit the form

这是提交代码,在“文档准备”部分,将按钮的onclick事件绑定到提交表单

$("#btnSubmitFileUpload").click(function(e){
        e.preventDefault();
        $("#frmUploadTrainingMedia").submit();
});

here is the callback referenced in the AjaxOptions

这是AjaxOptions中引用的回调

function displayUploadMediaMsg(d){
    var rslt = $.parseJSON(d.responseText);
    if (rslt.statusCode == 200){
        $().toastmessage("showSuccessToast", rslt.status);
    }
    else{
        $().toastmessage("showErrorToast", rslt.status);
    }
}

in the controller method for MVC it looks like this

在MVC的控制器方法中是这样的

[HttpPost]
[ValidateAntiForgeryToken]
public JsonResult UploadTrainingMedia(IEnumerable<HttpPostedFileBase> files)
{
    if (files != null)
    {
        foreach (var file in files)
        {
            // there is only one file  ... do something with it
        }
        return Json(new
        {
            statusCode = 200,
            status = "File uploaded",
            file = "",
        }, "text/html");
    }
    else
    {
        return Json(new
        {
            statusCode = 400,
            status = "Unable to upload file",
            file = "",
        }, "text/html");
    }
}

#6


0  

$("#formid").ajaxForm({ success: function(){ //to do after submit } });

#1


97  

I just did this -

我刚刚做了-

 $("#myform").bind('ajax:complete', function() {

         // tasks to do 


   });

And things worked perfectly .

一切都很顺利。

See this api documentation for more specific details.

有关更具体的细节,请参阅此api文档。

#2


23  

I could not get the number one upvoted solution to work reliably, but have found this works. Not sure if it's required or not, but I do not have an action or method attribute on the tag, which ensures the POST is handled by the $.ajax function and gives you the callback option.

我无法使第一个向上投票的解决方案可靠地工作,但我发现这是可行的。不确定是否需要它,但是我在标记上没有操作或方法属性,这确保POST是由$处理的。ajax函数,并提供回调选项。

<form id="form">
...
<button type="submit"></button>
</form>

<script>
$(document).ready(function() {
  $("#form_selector").submit(function() {

    $.ajax({
     type: "POST",
      url: "form_handler.php",
      data: $(this).serialize(),
      success: function() {
        // callback code here
       }
    })

  })
})
</script>

#3


22  

You'll have to do things manually with an AJAX call to the server. This will require you to override the form as well.

您必须通过对服务器的AJAX调用来手动执行操作。这也要求您重写表单。

But don't worry, it's a piece of cake. Here's an overview on how you'll go about working with your form:

但别担心,这是小菜一碟。下面是关于如何处理表单的概述:

  • override the default submit action (thanks to the passed in event object, that has a preventDefault method)
  • 覆盖默认的提交操作(感谢传入的event对象,该对象具有preventDefault方法)
  • grab all necessary values from the form
  • 从窗体中获取所有必要的值
  • fire off an HTTP request
  • 启动HTTP请求
  • handle the response to the request
  • 处理对请求的响应

First, you'll have to cancel the form submit action like so:

首先,您必须取消表单提交操作,如下所示:

$("#myform").submit(function(event) {
    // Cancels the form's submit action.
    event.preventDefault();
});

And then, grab the value of the data. Let's just assume you have one text box.

然后,获取数据的值。假设你有一个文本框。

$("#myform").submit(function(event) {
    event.preventDefault();
    var val = $(this).find('input[type="text"]').val();
});

And then fire off a request. Let's just assume it's a POST request.

然后发出请求。假设这是一个POST请求。

$("#myform").submit(function(event) {
    event.preventDefault();
    var val = $(this).find('input[type="text"]').val();

    // I like to use defers :)
    deferred = $.post("http://somewhere.com", { val: val });

    deferred.success(function () {
        // Do your stuff.
    });

    deferred.error(function () {
        // Handle any errors here.
    });
});

And this should about do it.

这是应该的。

Note 2: For parsing the form's data, it's preferable that you use a plugin. It will make your life really easy, as well as provide a nice semantic that mimics an actual form submit action.

注意2:对于解析表单数据,最好使用插件。它将使您的生活变得非常简单,并且提供一个很好的语义,模仿实际的表单提交操作。

Note 2: You don't have to use defers. It's just a personal preference. You can equally do the following, and it should work, too.

注意2:您不必使用defers。这只是个人喜好。您可以同样地执行以下操作,并且它也应该工作。

$.post("http://somewhere.com", { val: val }, function () {
    // Start partying here.
}, function () {
    // Handle the bad news here.
});

#4


7  

I do not believe there is a callback-function like the one you describe.

我不相信会有像您描述的那样的回调函数。

What is normal here is to do the alterations using some server-side language, like PHP.

这里通常使用一些服务器端语言(如PHP)进行更改。

In PHP you could for instance fetch a hidden field from your form and do some changes if it is present.

在PHP中,您可以从窗体中获取隐藏字段,如果存在,则进行一些更改。

PHP:

PHP:

  $someHiddenVar = $_POST["hidden_field"];
    if (!empty($someHiddenVar)) {
        // do something 
    }

One way to go about it in Jquery is to use Ajax. You could listen to submit, return false to cancel its default behaviour and use jQuery.post() instead. jQuery.post has a success-callback.

在Jquery中进行此操作的一种方法是使用Ajax。您可以侦听submit,返回false以取消其默认行为并使用jQuery.post()。jQuery。帖子success-callback。

$.post("test.php", $("#testform").serialize(), function(data) {
  $('.result').html(data);
});

http://api.jquery.com/jQuery.post/

http://api.jquery.com/jQuery.post/

#5


7  

For MVC here was an even easier approach. You need to use the Ajax form and set the AjaxOptions

对于MVC,这是一种更简单的方法。您需要使用Ajax表单并设置AjaxOptions

@using (Ajax.BeginForm("UploadTrainingMedia", "CreateTest", new AjaxOptions() { HttpMethod = "POST", OnComplete = "displayUploadMediaMsg" }, new { enctype = "multipart/form-data", id = "frmUploadTrainingMedia" }))
{ 
  ... html for form
}

here is the submission code, this is in the document ready section and ties the onclick event of the button to to submit the form

这是提交代码,在“文档准备”部分,将按钮的onclick事件绑定到提交表单

$("#btnSubmitFileUpload").click(function(e){
        e.preventDefault();
        $("#frmUploadTrainingMedia").submit();
});

here is the callback referenced in the AjaxOptions

这是AjaxOptions中引用的回调

function displayUploadMediaMsg(d){
    var rslt = $.parseJSON(d.responseText);
    if (rslt.statusCode == 200){
        $().toastmessage("showSuccessToast", rslt.status);
    }
    else{
        $().toastmessage("showErrorToast", rslt.status);
    }
}

in the controller method for MVC it looks like this

在MVC的控制器方法中是这样的

[HttpPost]
[ValidateAntiForgeryToken]
public JsonResult UploadTrainingMedia(IEnumerable<HttpPostedFileBase> files)
{
    if (files != null)
    {
        foreach (var file in files)
        {
            // there is only one file  ... do something with it
        }
        return Json(new
        {
            statusCode = 200,
            status = "File uploaded",
            file = "",
        }, "text/html");
    }
    else
    {
        return Json(new
        {
            statusCode = 400,
            status = "Unable to upload file",
            file = "",
        }, "text/html");
    }
}

#6


0  

$("#formid").ajaxForm({ success: function(){ //to do after submit } });