简体   繁体   English

AJAX成功回调仅执行第一个功能

[英]AJAX success callback only carrying out first function

I've got a simple form submission that upon success I've got an alert and a call to clear the form. 我有一个简单的表单提交,成功后我有一个警报和一个电话要求清除表单。 I do get the alert, the info gets successfully added to the database, but the second call--for the form to clear, is not being carried out. 我确实收到了警报,信息已成功添加到数据库中,但是第二次调用(要清除表单)没有执行。 I'm sure it's something simple I'm doing wrong, but I can't figure it out. 我敢肯定,这是我做错的简单事情,但我无法弄清楚。

$('#contact_submit').click(function(e){
                if ($("#submit_form_contact").valid()) {


                    var post_data = {
                        "name" : $('#name').val(),
                        "email" : $('#email').val(),
                        "inquiry" : $('#inquiry_dropdown option:selected').text(),
                        "message" : $('#message').val()
                    };


                    $.ajax({  
                      type: "POST",  
                      url: "process-contact.php",  
                      data: post_data,  
                      success: function(data) {  
                        alert("Thank you for contacting us.");
                        $('#submit_form_contact').reset();
                      }  
                    });

                    e.preventDefault();

                }

Also, the submit button is just a button, not a submit input. 同样,提交按钮只是一个按钮,而不是提交输入。 Is it necessary to preventDefault()? 是否有必要阻止Default()? I'm new at this. 我是新来的。

jQuery doesn't have a .reset() method. jQuery没有.reset()方法。

Do this instead: 改为这样做:

$('#submit_form_contact')[0].reset();

This grabs the first DOM element, and invokes the native .reset() . 这将获取第一个DOM元素,并调用本机.reset() If there's any chance the form won't be found, then test for the element. 如果有可能找不到表格,请测试该元素。

var f = $('#submit_form_contact')[0];

if (f)
    f.reset();

And of course you don't really need jQuery to get an element by ID, especially if you're not going to use any jQuery methods. 当然,您实际上并不需要jQuery通过ID来获取元素,特别是如果您不打算使用任何jQuery方法时。

var f = document.getElementbyId('submit_form_contact');

if (f)
    f.reset();

Another alternative would be to set the submit button as the context: of the ajax call, then use its form property. 另一种选择是将提交按钮设置为context: ajax调用,然后使用其form属性。

                $.ajax({  
                  context: this,
                  type: "POST",  
                  url: "process-contact.php",  
                  data: post_data,  
                  success: function(data) {  
                    alert("Thank you for contacting us.");
                    this.form.reset();
                  }  
                });

这条线也可以使用

$("#submit_form_contact").trigger('reset');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM