Taoufiq's Blog

How to submit a form using AJAX & SSJS

2023-07-28
10 min read

AJAX & SSJS

Form handling with Ajax

Introduction

You may have dealed with a client that wanted his Form to be submitted in a more modern way, the client does not want the page to be refreshed each time the end user submits the form, end user needs to see only one dynamic page and changes within it.

This is definetly doable using GET requests, you can create a JSON resource with some AMPSCRIPT in it that retrieves the data from the URL, and you have to pass data through the URL as a query parameter, but what if the data is somehow sensitive ?

This is where you'll need to send data using POST request, it is definetly a safer choice, and this is what the article is all about.

Prerequisites

Basic Knowledge of SSJS

Demonstration

In order to make anything easier to understand, it is always to give a real life example

Let's assume that you're having a form, with three fields : Firstname, Lastname and Email field, these data is a Person's data, so it is better and safer to send it via POST request.

Go to Web Studio, then click on Add Content and select Landing Page and give it the name you want, and pick the Blank option for demo purposes

Then paste this HTML code there inside the CloudPage once you open it


    
    
    
    

Contact Form

Put it in here is case you forgot ;)

Now you have simple HTML/CSS working and well displayed in the page. Now! Time for some javascript to retrieve values from the fields once the end user fill them

The script below only retrieves data from form and do not push them to the backend, NOT YET ;)

The script is to be put at the end of the body tag.


    
                

The only missing thing from the client side is the AJAX call, for this reason it may better to know what is an AJAX call in here, because we're going to use the same script :)


    
                

The same way we created the Landing Page Content, we're going to create a JSON resource, so pick up the JSON option

And then open your JSON resource and copy and paste this code there


    
                

Let's not forget the url generated for the JSON resource and put it in the frontend script

Now feel free to submit your form and check the data you get back in the Inspector ( Network tab )

I already tested mine and here is what I got ;)

Conclusion

This was a quick demo on how to use AJAX and POST request in SFMC, as already said using POST request is way safer and harder to track, so it will be your recommanded way to send sensitive data from the CloudPage to any backend script.