Connecting to the backend using AJAX. Should I?. HELP

I have a form that receives node information and then sends an email, all perfect. But what I need now is that once the user sends the form, the page is not refreshed, the form is deleted and replaced by a message that says “thank you for your message”, I also need that the form data keeps arriving to the server.

I have an idea of how to get the form deleted and put the message I want, I can do it with javascript. But I don’t know how to make the page not refresh and the form data arrive to the backend; I was thinking to do it with AJAX, using fetch or XMLHttpRequest.

I’m working with Node and Express.

I need some help, I appreciate any kind of suggestion or contribution.

The page refreshes because that is the default behaviour for submitting a form. If you want to prevent this, you will need to attach an event listener to the form and listen for the onSubmit event.

Inside this event listener, you will receive the event as the first argument passed to the listener function. By calling the preventDefault method on the event, you can stop the default behaviour (refreshing the page) from being applied.

document.getElementById("myForm").addEventListener("submit", function(event) {
  // send the data to the backend using ajax
1 Like