How To Submit AJAX Forms with JQuery

Submitting a form using AJAX in jQuery enables you to send form data to a server and receive a response without having to reload the entire page. Here's a step-by-step explanation with examples:

HTML Form

Create an HTML form you want to submit.

<form id="myForm"> <input type="text" name="username" placeholder="Username"> <input type="password" name="password" placeholder="Password"> <button type="submit">Submit</button> </form> <div id="result"></div>

jQuery AJAX Submission

Use jQuery to handle the form submission using AJAX. Prevent the default form submission behavior, gather form data, and send it to the server.

$(document).ready(function() { $("#myForm").submit(function(event) { event.preventDefault(); // Prevent default form submission var formData = $(this).serialize(); // Serialize form data $.ajax({ type: "POST", // Use POST method url: "your_server_endpoint.php", // Replace with your server endpoint data: formData, success: function(response) { $("#result").html(response); // Display server response } }); }); });

In this example, when the form is submitted, the submit event is caught by jQuery. The event.preventDefault() prevents the form from being submitted in the usual way. The serialize() method is used to gather form data.

run this source code Browser View

The $.ajax() function is then employed to send an asynchronous request to the server. You need to replace "your_server_endpoint.php" with the actual server endpoint URL. Upon success, the server response is displayed in the <div> element with the ID "result".

Full Source | jQuery

<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script> <script> $(document).ready(function() { $("#myForm").submit(function(event) { event.preventDefault(); // Prevent default form submission var formData = $(this).serialize(); // Serialize form data $.ajax({ type: "POST", // Use POST method url: "your_server_endpoint.php", // Replace with your server endpoint data: formData, success: function(response) { $("#result").html(response); // Display server response } }); }); }); </script> </head> <body> <form id="myForm"> <input type="text" name="username" placeholder="Username"> <input type="password" name="password" placeholder="Password"> <button type="submit">Submit</button> </form> <div id="result"></div> </body> </html>

This way, when the user submits the form, the data is sent to the server using AJAX, and the response is displayed without a full page refresh.


Submit a Form Without Page Refresh Using jQuery

Remember to replace "your_server_endpoint.php" with your actual server endpoint URL and adjust the handling on the server side accordingly.

Conclusion

Submitting a form using AJAX in jQuery provides a smoother and more dynamic user experience by allowing data exchange with the server without reloading the entire page.