# How to execute a velo code \*after\* submit button is \*successful\*

**URL:** <https://forum.wixstudio.com/t/how-to-execute-a-velo-code-after-submit-button-is-successful/62634>\
**Category:** Ask the community\
**Tags:** code, question, cms, wix-studio\
**Created:** [September 10, 2024, 1:01am UTC](https://forum.wixstudio.com/t/how-to-execute-a-velo-code-after-submit-button-is-successful/62634 "2024-09-10T01:01:25Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Adrian.E](https://avatars.discourse-cdn.com/v4/letter/a/f14d63/32.png) [@Adrian.E](https://forum.wixstudio.com/u/Adrian.E)\
**Post date:** [September 10, 2024, 1:01am UTC](https://forum.wixstudio.com/t/how-to-execute-a-velo-code-after-submit-button-is-successful/62634/1 "2024-09-10T01:01:25Z")

</div>

**Question:**  
How to ensure that a velo code is only executed in the event when a submit button is **successful** (ie all mandatory fields are filled by the site visitor) - this is for input fields connected to a CMS.

**Product:**  
Wix Studio

**What are you trying to achieve:**  
I have “built” a “form”, that is actually a set of input fields connecting to a CMS (so, not a classic “form”, but enabled through CMS). It includes a submit button that puts all the input data into a CMS. There are some fields that are set to **required** inputs, such as obvious ones like ‘name’ and ‘email address’ etc.  
(the submit button is defined through "click actions connects to ‘submit’, and a success message is being displayed)  
**All this is working well and as intended.**

Then, I have added a velo code that is executed once the submit button is clicked (see below how it is implemented ). The aim of the code is to send an email to the site visitor [‘triggeredEmails’] and some additional features such as opening a lightbox [wixWindowFrontend.openLightbox(…)] etc  
**Basically, the code itself is running well, too!**

However, the velo code is being executed at all circumstances when the submit button in clicked, even if some mandatory inputs are have not been done by the visitor.

The code starts with:  
$w.onReady(function () {  
$w(“#_submit-button_”).onClick(() =\> {  
…  
…  
});

I do understand that the code is executed, as there is no “check” if the all the required fields are filled by the site visitor.

**Finally, what I want to achieve:**  
So, I’d like to ensure that the code is only executed once the submit button is successful (or in other words: when the success message is being showed up, not for the “failure” message).

I am wonderig how to implement this - is it something that can be realized through/in the code or even straight in the editor?  
Perhaps I can somehow implment an another query to check the visibilty of the success message (that is another text element with an ID)  
Any ideas are more than welcome!

**What have you already tried:**

- Fields are implemented and well connected to CMS, submit button in place
- Code is executed when clicked

---

<div class="post-metadata">

**Author:** ![Dan\_Suhr](https://sea1.discourse-cdn.com/wix/user_avatar/forum.wixstudio.com/dan_suhr/32/94074_2.png) [@Dan\_Suhr](https://forum.wixstudio.com/u/Dan_Suhr)\
**Post date:** [September 10, 2024, 3:37am UTC](https://forum.wixstudio.com/t/how-to-execute-a-velo-code-after-submit-button-is-successful/62634/2 "2024-09-10T03:37:35Z")

</div>

i’d remove the onclick and instead check for succesful submission

maybe something like this

```javascript
$w.onReady(function () {
    // Select your dataset, assuming it is named "myDataset"
    const dataset = $w("#myDataset");

    // Triggered when the dataset's data is successfully saved
    dataset.onAfterSave(() => {
        // Your custom code that should run only on successful submit
        sendEmailAndOpenLightbox();
    });

    // Triggered when there is an error during save
    dataset.onError((error) => {
        console.error("Failed to save data:", error.message);
        // You can also display an error message to the user here if needed
    });
});

// Define your custom function for sending an email and opening a lightbox
function sendEmailAndOpenLightbox() {
    // Example: Sending triggered email
    wixCrm.emailContact('TRIGGERED_EMAIL_ID', {
        variables: {
            // Add variables as needed
            firstName: $w('#inputFirstName').value,
            email: $w('#inputEmail').value
        }
    }).then(() => {
        console.log('Email sent successfully');
    }).catch((error) => {
        console.error('Error sending email:', error);
    });

    // Example: Opening a lightbox
    wixWindow.openLightbox('LightboxName');
}

```

---

<div class="post-metadata">

**Author:** ![Adrian.E](https://avatars.discourse-cdn.com/v4/letter/a/f14d63/32.png) [@Adrian.E](https://forum.wixstudio.com/u/Adrian.E)\
**Post date:** [September 10, 2024, 11:53am UTC](https://forum.wixstudio.com/t/how-to-execute-a-velo-code-after-submit-button-is-successful/62634/3 "2024-09-10T11:53:20Z")

</div>

Dear Dan,

thank you very much for your prompt reply and support on this.  
Indeed, this looks as a very promising way to do it.

In fact, I was not aware that I have straight access to the dataset in velo (“#myDatset”) - as I have wrongly assumed that any $w(“#…”) function is meant for elements that are “actively” positioned in the editor. I have found the dataset ID in the inspector CMS connections → dataset settings → Dataset ID.

Now, I have just tried out your suggestion.

Yeah, it is working well:  
On the published site, the triggered email and open.lightbox functions are only executed when the submit button is pushed **and** all required fields are filled (as intented).

**However, just one remark & question:**  
it seems that your error message code line is not working:  
dataset.onError((error) =\> {  
console.error(“Failed to save data:”, **error.message** );  
});  
 → as error is a string type.

I have checked the content (value) of “error” when the req’ fields are not filled. In this case, the value is “save”.

Now, when I run the code in the “preview mode” (not published site), in the case of “not allreq’ fields are filled”, there are red error warnings popping-up in the developer console:  
_"UserError: datasetApi ‘save’ operation failed_  
_Caused by DatasetError: Some of the elements validation failed_  
_Failed to save data: save"_  
[last line is coming from code " console.error(“Failed to save data:”, **error** );"]

So, I am wondering if this is a **normal and expected procedure/behaviour** (as this is something the site visitor does not see anyway), or is it beacuse of a not-optimal “error handling” **?**

Sorry, this might be a stupid question - as you recoginze, I am not a velo/coding expert at all…

Thank you for your feedback and any recommendations!  
Adrian
