Today, a new article was approved over on TalkPHP entitled "Simple AJAX with JQuery" (read article). If you're looking for a nice basic introduction to using jQuery to make AJAX calls, then head on over there. Here are some thoughts on it.

The main chunk of JavaScript code used in the article is as follows:

function register(){
		$.ajax({
			type: "POST",
			url: "submit_data.php",
			data: 	"username=" + document.getElementById("username").value + 
					"&email=" + document.getElementById("email").value,
			success: function(html){
				$("#response").html(html);
			}
		});
 
		}

Whilst that works, there are a number of things that I would do differently (that doesn't make either of the ways right, or wrong, necessarily!). My version of the AJAX call would probably move further in the direction of:

$.post("submit_data.php", $("form:first").serializeArray(), function(data){
	$("#response").html(data);
});

How's this different? Well first, we make use of the jQuery.post function rather than using the lower level jQuery.ajax with POST specified as an argument. There is an equally useful jQuery.get option if we wanted to use a GET request instead. Note the form:first selector, obviously that would only grab the data for the first form on the page but since there is only one form in the example HTML we're ok.

The next major change is rather than construct the data string manually as Gareth did in the article (why use document.getElementById rather than jQuery's dollar functon?) we make use of the jQuery.serializeArray function which serialises the form elements (if any) of an element into an object. The conversion of that object into a usable data string is done within jQuery and we needn't construct our own. I'd use serializeArray over serialize simply because I often want to include more data items in the request using jQuery.extend.

A few other points to make note of, which I think Gareth will include in a follow-up article, would be that no effort is made to make the article's sample code unobtrusive (which is all the rage right now) and without JavaScript enabled the newsletter signup simply would not work at all.

Related to this, he relies on the click event of the button to trigger the request. This is something I see time and time again with AJAX form submission, maybe everyone else in the world clicks submit buttons but I generally press the enter key (I'm much more keyboard oriented when browsing, than pointer oriented [mouse, trackpad, etc]). Binding to the form's submit event (unobtrusively, not within the HTML) would be my recommendation since we really want to hijack the normal submission process and route it through AJAX.

Hmm well, there we are. It's not a very coherent set of thoughts but they're out there now. :)