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:
- Capture the form submit button so that the default action does not take place.
- Create a new XMLHttpRequest object.
- Set the request method and URL.
- 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