0

I'm generating a filename via AJAX Jquery. Now I need this filename to be saved. My current process is to call a controller that will do the image saving and it will return a filename/filepath back. Using this new filepath I'm inserting this to a textfield as a value so that when the Add to Cart function is triggered it will get the generated filepath value and save it as custom option.

But the problem is that the Add to cart function is being triggered even when the Ajax Jquery hasn't finish it's processing. How can I put the Add to cart function trigger onhold until the generated filename is returned by the Ajax. I'm thinking of something like a callback function.

Is there a way to achieve this?

jQuery("#product-addtocart-button").on('click', function() {
        var canvas = jQuery('canvas.canvas');
        var canvasImage = canvas[0].toDataURL("image/jpeg", 0.7);

        jQuery.ajax({
          type: "POST",
          dataType: 'json',
          url: UPLOADER_URL,
          data: {
             imgBase64: canvasImage
          }
        }).done(function(response) {                
            last_option.val(response.filename);         
            console.log("Generated filename", response.filename);   
             // TRIGGER ADD TO CART FUNCTION HERE
             // BUT THE ADD TO CART IS BEING TRIGGERED EVEN IF THE AJAX IS NOT YET FINISH
        });

    });
0

Try below code.

jQuery("#product-addtocart-button").on('click', function(e) {
    var self = this;

    if (!jQuery(self).hasClass('processing')) {
        e.preventDefault();

        var canvas = jQuery('canvas.canvas');
        var canvasImage = canvas[0].toDataURL("image/jpeg", 0.7);

        jQuery.ajax({
            type: "POST",
            dataType: 'json',
            beforeSend: function() {
                jQuery(self).addClass('processing');
            },
            url: UPLOADER_URL,
            data: {
                imgBase64: canvasImage
            }
        }).done(function(response) {                
            last_option.val(response.filename);         
            console.log("Generated filename", response.filename);
            e.currentTarget.click();

            jQuery(self).removeClass('processing');
        });
    }
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.