'event.preventDefault(); only works some of the time with submit form

I am using the Mailchimp API to submit a form. The goal is to prevent the default callback provided by Mailchimp. The majority of the time event.preventDefault() is behaving as it should. Then randomly it will not work:

$(function () {
 var $form = $('#mc-embedded-subscribe-form');
 $('#mc-embedded-subscribe').on('click', function(event) {
     if(event) event.preventDefault();
    register($form);
   });
});

function register($form) {
    $.ajax({
        type: $form.attr('method'),
        url: $form.attr('action'),
        data: $form.serialize(),
        cache       : false,
        dataType    : 'json',
        contentType: "application/json; charset=utf-8",
        error       : function(err) { alert("Could not connect to the registration server. Please try again later."); },
        success     : function(data) {
        if (data.result != "success") {
            // Something went wrong, do something to notify the user. maybe alert(data.msg);
            var message = data.msg
            var messageSh = data.msg.substring(4);
            if (data.msg == '0 - Please enter a value' || data.msg == '0 - An email address must contain a single @') {
               $('#notification_container').html('<span class="alert">'+messageSh+'</span>'); 
            } else {
                $('#notification_container').html('<span class="alert">'+message+'</span>');
            }
        } else {
            // It worked, carry on...
        var message = data.msg;
        $('.popup-promo-container').addClass('thanks');
        $('.checkboxes, #mc_embed_signup_scroll').addClass('hidden');
        $('.complete-promo').html(message).removeClass('hidden');
        setTimeout(function() {
            document.querySelector('.popup-promo').style.display = "none";
        },20000);
        
        }
    }
});
}


Solution 1:[1]

Try

  1. take off ready function.
  2. remove if on event

Code:

var $form = $('#mc-embedded-subscribe-form');

$('#mc-embedded-subscribe').on('click', function(event) {
    event.preventDefault();
    register($form);
});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Rafael