Creating a hyperlink that works with or without AJAX

The current project I'm working on includes a display page where users can see a list of messages generated for them by the system. Each message consists of an <li> element containing the text of the message followed by a hyperlink labeled "Delete".

I wanted to make it such that you could delete each message without refreshing the page, but still accommodate users who had JavaScript turned off, and without a lot of extra work.

How did I do it? Like so:

<!---Include the jQuery core file--->
<script type="text/javascript" src="/views/JavaScript/jquery-1.2.2.js"></script>

<script language="javascript">
//Set the typical jQuery ready event handler to fire when the document is ready for manipulation
$(document).ready(function () {

//Assign a click event handler for all of the 'delete' hyperlinks (which all have a CSS class of 'deleteLink')
$(".deleteLink").click(function () {

var linkObj= $(this);
//Take the existing URL in the 'href' value and append an additional URL variable
var ajaxURL= linkObj.attr("href") + "&js=1";

//Remove the li list element (the parent) the link belongs to
linkObj.parent().remove();

//Make the Ajax call
$.ajax({
type: "POST",
url: ajaxURL
}); //end of .ajax function

//This statement will prevent the browser from actually navigating to the address in the link
return false;

}); //end of .deleteLink click function
}); //end of document.ready function
</script>


<h2>Your Messages</h2>

<ul>

<cfoutput query="qryMessages">

<li id="#messageId#">

#message#<br />
<a class="deleteLink" href="index.cfm?fuseaction=#xfa.deleteMsg#&msgId=#messageId#">Delete</a>

</li>

</cfoutput>

</ul>

...The only other thing you need to do is put a conditional statement in the page/event that is called by the hyperlink that looks for the presence of the additional URL variable ("js" in this case).

If JavaScript is turned off, that additional variable will not be defined and the page/event will redirect the action back to the calling page once it's done deleting the message data from the database.

If JavaScript is turned on, the page/event will simply delete the message data (no action redirect), and the user simply sees that message item disappear from the list.

Comments
One note Brian. Whenever you need to reference a jQuery object multiple times, it's best to assign it to a var so that the factory method isn't called over and over. So you'd do something like this:

var myObj = $(this);
myObj.parent().remove();
# Posted By Rey Bango | 5/23/08 10:35 AM
@Rey: Thanks for the tip. I've amended the code per your suggestion.
# Posted By Brian Swartzfager | 5/23/08 10:50 AM
Usefull tips, thank you.
# Posted By Ringtones | 7/19/08 3:39 AM
BlogCFC was created by Raymond Camden. This blog is running version 5.1.004.