$(function () { // toggle on click $('.FavoriteToggle').click ( function() { // prevent duplicate AJAX request with a "loading" flag if (!this.isLoading) { var $img = $(this).find("img"); var ListID = $(this).find('.FavoriteToggleIcon').attr("title").match(/\d+/); // flag that we are currently loading something this.isLoading = true; // determine the action from the current state of the img if ($img.attr("src").indexOf("favorite.png") > -1) var actionVerb = "unFavorite"; else var actionVerb = "mkFavorite"; $.ajax({ url: "include/AJAX.inc.php", type: "GET", data: {action: actionVerb, ItemType: 0, ItemID: ListID }, success: function($i) { return function() { // change image on success only if ($i.attr("src").indexOf("favorite.png") > -1) { $i.attr("src", "../../images/icons/favorite_not.png"; else $i.attr("src", "../../images/icons/favorite.png"; }; }($img), error: function(xhr, textStatus, errorThrown) { // make some note of the error alert(textStatus); } complete: function(p) { return function(xhr, textStatus) { // set loading flag to false when done p.isLoading = false; }; }(this) }); } }); });
Unconfirmed, but you should get this idea.
All the material if ($img.attr("src").indexOf("favorite.png") could be made much easier by adding the favorite CSS class to <img> . For example, in the main function:
var actionVerb = $img.is(".favorite") ? "unFavorite" : "mkFavorite";
and in the success callback:
if ($i.is(".favorite")) $i.attr("src", "../../images/icons/favorite_not.png"; else $i.attr("src", "../../images/icons/favorite.png"; // now toggle the CSS class $i.toggleClass("favorite")
source share