Contact Form

Name

Email *

Message *

Cari Blog Ini

Javascript Ajax Get Form Data

WEB Form Submit Function With JavaScript

How to Submit a Form via AJAX

Capture the Form Submit Button

To submit a form via AJAX, your script will need to handle four tasks:

  1. Capture the form submit button so that the default action does not take place.
  2. Create a new XMLHttpRequest object.
  3. Set the request method and URL.
  4. Send the request.

Here is an example of how to capture the form submit button:

```javascript const form = document.querySelector('form'); form.addEventListener('submit', async (event) => { event.preventDefault(); // Create a new XMLHttpRequest object const xhr = new XMLHttpRequest(); // Set the request method and URL xhr.open('POST', '/submit'); // Set the request headers xhr.setRequestHeader('Content-Type', 'application/json'); // Create a new FormData object const formData = new FormData(form); // Send the request xhr.send(formData); }); ```


Comments