javascriptnode.jshttprequestvelo

Make a POST request on wixFormSubmit()


I have a Wix Form that is configured to send an email with the form data and just display a confirmation message on the page. I was asked to add a second request to send the same form data to a different server. I was able to do it sending the data to the backend using onWixFormSubmited()

export function wixForms1_wixFormSubmitted() {
    let data = {
            first_name: $w('#input5').value,
            last_name: $w('#input4').value,
            email: $w('#input3').value,
    }

    saveProspectToCRM(data)
            .then(function(response) {
            console.log('it was successfull');
            console.log(response);
    });
}

import {fetch} from 'wix-fetch';  

export async function saveProspectToCRM(params) {
    const url = 'myurl';
    let  data = {
        //encoded data
    };
    
    return fetch(url,{
        method: 'post',
            body: data,
            headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
            }).then(function(response) {
                if (response.status >= 200 && response.status < 300) {
                    return response.text();
                } else {
                        throw new Error(response.statusText);
                }
    }); 

}

This actually works and the email is being sent and the data post to my other server, but I have a second Wix Form with the only difference that this one redirects to a different page after submit instead of just displaying a message. And my code is not working with this second form. I tried to change onWixFormSubmitted for onWixFormSubmit but is still not working.

I have read in the documentation that onWixFormSubmit just handles synchronous operations and I assume the first form works because the user is not redirected to a different page. Anyone could tell me what I am doing wrong or what would be the best approach to keep the form configuration (send the emails) and POST the data to the server?


Solution

  • wixFormSubmitted() with redirect return function once is submitted. the rest of code is ignored.

    What should you do is to switch back to success message and hide it.

    for redirect you always can use wix-location after API response.

    import wixLocation from 'wix-location';
    
    // ...
    
    wixLocation.to("/about-me"); 
    

    reference