$( document ).ready(function() { showForm(); }); function showForm() { $.get( "/p/contact/form", function( data ) { $( "#contact-form" ).html( data ); bindSubmit(); }); } function bindSubmit() { $("#contact-form > form > button").click(function(e) { e.preventDefault(); $("#contact-form > form").submit(); }); $("#contact-form > form").submit(function(e) { // cancel the default browser action and use ajax (below) to submit the form e.preventDefault(); // disable the submit button $("#contact-form > form > button").attr("disabled", true); var form = $(this); var url = form.attr("action"); $.ajax({ type: "POST", url: url, data: form.serialize(), // serializes the form's elements success: function(data) { $.get( "/p/contact/thanks?r=" + encodeURIComponent(data), function( d ) { $( "#contact-form" ).html( d ); }); } }); }); }