Submitting a form using Jquery ajax

This code will work for any scenario where you want to post back a form to the server asynchronously, and then render a response. The use of the “on” keyword here (JQ1.7 and above only) allows the event to stay attached to the element even if it’s posted back later. The scenario I used this was in an “add comment” type form, where the form would fade out on submit, and then fade back in with either a message stating that the comment was received successfully, or alternatively would re-display the form with error messages if it wasn’t.


    $(document).ready(function() {       
    
        $(document).on("click", "#formSelector" , function() {
            var $form = $(this).parents('form');

            $.ajax({
                type: "POST",
                url: $form.attr('action'),
                data: $form.serialize(),
                error: function(xhr, status, error) {
                    //Actions to take on error
                },
                success: function(response) {
                    //Actions to take on success
                }
            });

            return false; //This stops actual postback (some browsers will still try)
        });
    });

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s