Problem updating multiple aysc anchors with jquery

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 that binds to the click event and I want it to send an ajax request and replace the anchor with the returned text. but if I clicked on several links so that several were executed asynchronously, then it does not update all the anchors with the returned text, but only the last anchor that I clicked on.

I assume that the binding variable is overwritten every time it starts, how would I structure my code so that every time the click event is fired, it updates the correct anchor at the end?

here is 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>
+3
source share
1 answer

, , anchor, , "" . . jsfiddle .

, var , :

function geninvoice() {

    // stop double clicks
    var anchor = $(this); //<-- put a var here

, . x , ​​ var:

var a = 1;
var b = 1;

if (a === b){
   var x = 0;
}

alert(x); //alerts '0'

, jQuery:

(function($){
    //plugin code
    //all variables local to the invoked anonymous function
})(jQuery);

JSFiddle

+4
source

All Articles