Ole Haugset
Ole Haugset

Reputation: 3797

jQuery on form submit refreshing page

I know how this works, I've done it a thousands times. Still, it does not work now. WHY?

I have the following code. I've tried e.preventDefault, e.stopPropagation, return false. I've changed the html for the form to <form onsubmit="function()" and so on. Still, every time I submit the form the page refreshes.

Can anyone who can tell me how drunk I am and what I'm doing wrong?

jQuery( document ).ready(function(){
    jQuery('.register-form').submit( function(e){       
        var form = jQuery(this).serialize();        
        jQuery.ajax({
            type : "post",
            dataType : "json",
            url : myAjax.ajaxurl,
            data : form,
            success : function( d ){
                if( d.success ) {
                   alert( 'Takk for din påmelding' );
                } else {
                   alert( 'Noe gikk galt, vennligst prøv igjen senere' );
                }
            }, 
            error: function(){
                alert( 'Noe gikk galt, vennligst prøv igjen senere' );
            }
        });     
        return false;   
    }); 
});

For those who would like a url to the site it is: http://ccnmn.loke.itvault.no

NB: it's in Norwegian. You'll find the form by pressing 'Priser' in the top menu and then 'Bestill' in the packages shown

Upvotes: 2

Views: 708

Answers (1)

Tommy
Tommy

Reputation: 39807

This Fiddle shows that your code works just fine with the proper event.preventDefault(); or return false; in place at the correct locations in the code (also, I changed your variable from form to myForm just in case there was some weird name collision happening.) If you mirror this fiddle and still have issues, your problem must lie elsewhere (don't have a handler on the submit button do you?).

<form class="register-form" action="/echo" method="POST">
   <input type="Text" id="test" name="test"/>
   <input type="Submit" value="Go" id="TestSubmit"/>
</form>

jQuery(document).ready(function(){
    jQuery('.register-form').submit(function(event){ 
        event.preventDefault();
        var myForm = $(this).serialize();   
        jQuery.ajax({
            type : "post",
            dataType : "json",
            url : "www.google.com",
            data : myForm,
            success : function( d ){
                if( d.success ) {
                   alert( 'Takk for din påmelding' );
                } else {
                   alert( 'Noe gikk galt, vennligst prøv igjen senere' );
                }
            }, 
            error: function(){
                alert( 'Noe gikk galt, vennligst prøv igjen senere' );
            }
        });
        //return false; would also work here instead 
        //of the event.preventDefault(); above        
    }); 
});

Upvotes: 1

Related Questions