So i have all these links in html like this
<a href="#ajax" class="invlink" competition_id="532">Gen Invoice</a>
<a href="#ajax" class="invlink" competition_id="534">Gen Invoice</a>
<a href="#ajax" class="invlink" competition_id="535">Gen Invoice</a>
then i wrote some javascript which binds to the click event
and i want it to submit an ajax request, and replace the anchor with the returned text.
but if i have clicked on multiple links so that several are running asychronously, then it doesn’t update all the anchors with the returned text, only the last anchor i clicked on.
i am guessing that the anchor variable is being overwritten each time it is run, how would i structure my code so that each time the click event is triggered, it updates the correct anchor on completion?
here is the javascript
<script type="text/javascript">
$(document).ready(function() {
// bind geninvoice function to all invlink's
$('.invlink').bind('click', geninvoice);
});
function geninvoice() {
// stop double clicks
anchor = $(this);
anchor.unbind('click');
competition_id = $(this).attr('competition_id');
$.ajax({
type: "POST",
url: "<?php echo url::site('manage/ajax/geninvoice'); ?>/"+competition_id,
dataType: "json",
beforeSend: function() {
anchor.addClass("loading");
},
success: function(response, textStatus) {
anchor.replaceWith(response.invoice_number);
},
error: function(response) {
alert("Unknown Error Occurred");
anchor.bind('click', geninvoice); // rebind if error occurs
},
complete: function() {
anchor.removeClass("loading");
}
});
}
</script>
Yeah, the problem is that your
anchorvariable as it is written being ‘hoisted’ to a global scope. See this jsfiddle for a simplified example.You can fix this, by putting a
varin front of the variable, so its scope will be limited to the function:You can see the fix at this updated version of the above fiddle
Note, this will only help you for scoping within functions. The
xvariable in the following example will be hoisted to the top of the global scope even though it has been declared with avar:the advantages of scoping within functions is on of the reasons we often see the following convention around jQuery plugins:
See at this JSFiddle