This is something pretty basic, but I thought it would come in handy for people that might want to use JQuery AJAX but doesn’t want to write a lot of code to do it. The following code will allow you to transform any normal HTML ‘a’ link into an AJAX request just by adding an extra parameter to the HTML tag.
$(document).ready(function(){
$('a').click(function(e){
var strAjax = $(this).attr('ajax');
if (strAjax) {
var strDiv = $(this).attr('updatediv');
e.preventDefault();
var strPage = $(this).attr('href');
$(strDiv).html("<p><img src='images/ajax-loader.gif' alt='Loading'> Loading...</p>");
$.ajax({
type: "GET",
url: strPage,
success: function(html){
$(strDiv).html(html);
}
});
});
});
This will attach to any a link tags and see if it has the ajax parameters set. Great, now how do we use it?
<a href="path/to/file_with_code_to_get.html" ajax=true updatediv="#content"> Click Me </a> <div id="content"> </div>
Notice how I specified updatediv, this will allow us to position the content in a DIV, just enter the name of the div where you would like it and the AJAX content will be placed there; also easily style-able with CSS if you feel the need to.
Also notice the image I use in the middle, this is a small loading image to show to the user that it’s doing something – if you want your own loading image you can generate one by using this website Ajaxload
This will support an unlimited amount of links, so in theory you could add basic AJAX features to your whole site just using this one piece of code. Hope it helps someone out there.
