Skip to content Skip to sidebar Skip to footer

Ajax Form Cannot Prevent Page Reload With Event.preventdefault();

I have the following code which is supposed submit a form via Ajax without having to reload the page: $( document ).on('submit', '.login_form', function( event ){ event.prevent

Solution 1:

don't attach a listener on document instead use a on click handler on the submit button and change the type to button.

<button id="form1SubmitBtn">Submit</button>
$('#form1SubmitBtn').click(function(){

  //do ajax here
});

Happy Coding !!!

Solution 2:

for instance you can write like this

 $(".login_form").on('submit', function( event ){
    var $this = $(this);
    $.ajax({         
       data: "action=login_submit&" + $this.serialize(),
       type: "POST",
       url: _ajax_login_settings.ajaxurl,
       success: function( msg ){

        ajax_login_register_show_message( $this, msg );

      }
    });
    event.preventDefault();
 });

Solution 3:

You can use jquery and ajax to do that. Here is a nice piece code below that doesn't refresh the page but instead on submit the form gets hidden and gets replaced by a thank you message. The form data is sent to an email address using sendmail.php script.

Assuming your form has 3 input fields - name, email and message.

<scriptsrc="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script><scripttype="text/javascript">jQuery(function() {
jQuery("#button").click(function() {

var name=jQuery('#name').val(); 
var email=jQuery('#email').val();   
var message=jQuery('#message').val();

var dataString = 'name='+ name + '&email=' + email + '&message=' + message;

jQuery.ajax({
type: "POST",
url: "sendmail.php",
data: dataString,
success: function() {
jQuery('#contact_form').html("<div id='message'></div>");
jQuery('#contactForm').hide();
jQuery('#message').html("<h2>Contact Form Submitted!</h2>")
.append("<p>Thank you for your submission. We will be in touch shortly.</p>").hide()
.fadeIn(1500, function() {
});
}
});
returnfalse;
});
});

</script>

On top of your form tag just add this to display the thank you message.

<div id='message'></div>

Enjoy coding!!!!!!!

Post a Comment for "Ajax Form Cannot Prevent Page Reload With Event.preventdefault();"