On window load I am trying to check if my image has already been saved and if so change the HTML so that the link to save it is disabled. This code kind of works without the .each() with but only finds the first tag and changes all other similar tags based on that. Of course I want the do each tag separately. From looking at the post transactions in firebug, each ajax call processes properly and is sent the correct href value but the html updates don’t seem to take. The if statement isn’t failing because the alert message comes on when it should. Any idea why the $(this) works for retrieving the item value but doesn’t work when setting the html changes?
window.onload = function() {
$(".img a").each(function() {
var item=$(this).attr( 'href' );
var action="check";
jqxhr = $.post("webservice.php", { action: action, color: item }, function(data) {
var result=data.result;
if (result=="saved") {
$(this).html("<div style='line-height:4em '>Saved</div>");
$(this).attr("href","saved");
alert(result);
}
}, "json")
.error(function() {
alert("error: unable to contact web service");
});
});
}
The problem is that the
thisinside the callback does not refer to the element you think.You need to create a reference to that element before the ajax and use that.
Additionally it does seem like an overkill to run so many ajax call to check a similar thing.
It might be a better idea to refactor your code to make a single ajax call, but pass it a list of files to check and then handle the response which would refer to all those images (one-by-one)