AJAX Form Submission: Send Forms Without Reloading
Submit forms with AJAX so the page never reloads. You will use fetch and FormData to send data in the background and keep the user experience smooth.


Form Submission with AJAX
Form Submission with AJAX is the way to send the forms on a web page in the background. This way, form data can be sent to the server without the page having to reload. To do this, you can send the form data in the background using AJAX and update the page using the response that comes back from the server.
To send form data, you can use the XMLHttpRequest object. As an example, the following code snippet sends the form data in the background and prints the response from the server to the screen:
<form id="myForm">
<input type="text" name="name" placeholder="Name">
<input type="email" name="email" placeholder="Email">
<textarea name="message" placeholder="Message"></textarea>
<button type="submit">Send</button>
</form>
<script>
var form = document.getElementById("myForm");
form.addEventListener("submit", function(e) {
e.preventDefault(); // prevent the form's default behavior
var xhr = new XMLHttpRequest();
xhr.open("POST", "submit.php", true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.responseText);
}
};
var formData = new FormData(form);
xhr.send(formData);
});
</script>
In this example, the form data will be sent to the “submit.php” file with the “POST” method. The response from the server is printed to the screen with “console.log”. The “FormData” object used in this example collects the form data and sends it with the “xhr.send()” method.
With Form Submission with AJAX, users don’t need the page to reload while sending form data. In addition, the page will be updated dynamically using the response from the server. For example, if the response from the server is “success” after the form is submitted, a success message will be shown to the user. With this technology, web forms become faster and more user-friendly. Also, by showing the user the time elapsed while the form data is being sent, the wait feels shorter.
The “submit.php” file used for Form Submission processes the submitted form data and generates the response from the server. In this file, the validity of the data is checked first. Then it is saved to the database. If you want, you can also do things like sending an email when an email needs to be sent.
Finally, Form Submission with AJAX doesn’t just speed up the use of web forms, it also improves the user experience. With this technology, web forms become faster and more interactive.
- W3Schools: https://www.w3schools.com/xml/ajax_form_submit.asp
- Sitepoint: https://www.sitepoint.com/ajax-jquery-form-submit/
- CodePen: https://codepen.io/jthoms1/pen/zObzZJ
Share it if it helped


