简体   繁体   中英

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()? I'm new at this.

jQuery doesn't have a .reset() method.

Do this instead:

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

This grabs the first DOM element, and invokes the native .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.

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.

                $.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');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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