sehummel
sehummel

Reputation: 5568

jQuery event stops working after alert

I have a jQuery event that works fine until an alert is called. The function calls a script on the the server that adds an item (inserts a row in the database) to the cart. Only eight items are allowed in the cart, so when the user tries to add the ninth item, a message is returned to the jQuery script that that is not allowed. Here is the jQuery script:

jQuery(document).on('click', 'a.add.module, a.remove.module', function(e) {

    if (blnProcessing == true) {
        return false;
    } else {
        blnProcessing = true;
    }

    e.preventDefault();
    objLink = jQuery(this);
    strLink = objLink.attr('href');

    if (objLink.hasClass('add')) {
        objLink.text('Adding');
    } else {
        objLink.text('Wait');
    }

    jQuery.get(strLink, function(data) {
        if (data.success) {
            if (data.success != true) {
                alert(data.success);  // message that says this is not allowed -- this part stops the script from functioning further
            } else {
                // this part works
                jQuery('#cart').load('/study-clubs/modules/cart', function(){
                    if (objLink.hasClass('add')) {
                        strNewLink = strLink.replace('add', 'remove');
                        objLink.attr('href', strNewLink);
                        objLink.removeClass('add').addClass('remove').text('Added');
                    } else if (objLink.hasClass('remove')) {
                        strNewLink = strLink.replace('remove', 'add');
                        objLink.attr('href', strNewLink);
                            objLink.removeClass('remove').addClass('add').text('Add');
                    }

                    blnProcessing = false;

                });
            }
        } else {
            alert(data.error);
            blnProcessing = false;
        }
    }, 'json');
});

Ordinarily, with this kind of behavior, you use $(document).on('click', '#someID', function() .... But I'm already using that. So do I need to reattach the event listener or something. How do I get this to work after the alert?

Upvotes: 0

Views: 367

Answers (1)

lc.
lc.

Reputation: 116498

If data.success contains a value that evaluates to true in a boolean context but does not equal true (ergo the block containing alert(data.success) is executed), your blnProcessing flag is never reset.

FWIW, I realize it sometimes takes an extra pair of eyes, but you really should have been able to figure this out by stepping through your code in Firebug (or another set of developer tools).

Upvotes: 2

Related Questions