Custom JS after successful form submission

Hi,

I’m trying to execute a custom Javascript code inside a popup after a form is successfully submitted. Here’s the code:

document.addEventListener('bricks/popup/open', function(event) {
    var popupId = event.detail.popupId;

    if (popupId == 359) {
        document.addEventListener('bricks/form/success', function() {
    	    console.log('Success!');
	    });
    }
});

The problem I’m having is the code is being executed twice, so the console is showing two ‘Success!’ messages instead of one. I do have have some custom actions and interactions for Form Success, but when I remove them all the problem still exists.

Also, I’d like to know how I can target a specific form. Using var form = document.getElementById(‘brxe-tuqkso’); form.addEventListener… doesn’t seem to work.

Thank you.

Hi,

You can access the form ID via event.detail.elementId

document.addEventListener( 'bricks/form/success', function ( event ) {
  // Access the element ID
  const elementId = event.detail.elementId;

  // Access the form data
  const formData = event.detail.formData;

  // Access the raw response from AJAX
  const res = event.detail.res;

  // Do your magic here

});
1 Like

Magic happened after running this code:

document.addEventListener('bricks/popup/open', function(event) {
    var popupId = event.detail.popupId;
    if (popupId == 359) {
        // Remove any existing event listeners to avoid duplication
        document.removeEventListener('bricks/form/success', formSuccessHandler);
        // Add the event listener
        document.addEventListener('bricks/form/success', formSuccessHandler);
    }
});

function formSuccessHandler() {
    console.log('Success!');
    // Optionally, remove the event listener if it's no longer needed
    document.removeEventListener('bricks/form/success', formSuccessHandler);
}

I’m thanking Dylan Wages for helping me out in Bricks Facebook group.

1 Like