JQuery Ajaxize Forms


Sometimes you just want a form to push through ajax without having to write so much dang code. To this end I have a universal function I include in a few of my admin area sites which have a lot of little forms which need easy access to ajax posting and here’s the jquery I have in the global.js file for those sites.

To make a form post to ajax simply put in the <form> an attribute of “ajax” and have it equal to the ID of the response area.

IE: This form would pass the three variables to the page as a post with the querystring being posting=testForm and any text returned would insert into the span “resp_testForm”.

<form id="testForm" action="?posting=testForm" method="post" ajax="resp_testForm">
  <input type="text" name="var1"></input>
  <input type="text" name="var2"></input>
  <input type="text" name="var3"></input>
  <button type="submit">Save</button>
  <span id="resp_testForm"></span>
</form>
$(document).ready(function () {
	$("form").on("submit",function(e){
		if (!$(this).attr("ajax")) {
			return true; // if there isn't an ajax attribute, simply allow default submission
		}
		var thisActual = $(this);
		if (typeof preAjaxForm === "function") { 
			preAjaxForm(thisActual);
		}
		e.preventDefault(e);
		var d = $(this).serialize(); // data
		var respSpan = $(this).attr("ajax"); // output results to 
		var t = $(this).attr("action"); // target
		$.post(t,d,function(res){
			console.log(res);
			$("#"+respSpan).fadeOut("fast",function(){
				$("#"+respSpan).html(res).fadeIn("slow");
			});
			if (typeof postAjaxForm === "function") { 
				postAjaxForm(thisActual);
			}
		});
	});
});