To implement form submission with AJAX and jQuery, you can follow these steps:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<form id="myForm" action="submit.php" method="POST">
<input type="text" name="name" placeholder="Name">
<input type="email" name="email" placeholder="Email">
<input type="submit" value="Submit">
</form>
<script>
$(document).ready(function() {
$('#myForm').submit(function(event) {
// Prevent the form from submitting normally
event.preventDefault();
// Serialize form data into an object
var formData = $(this).serialize();
// Send the form data using AJAX
$.ajax({
url: $(this).attr('action'),
type: $(this).attr('method'),
data: formData,
success: function(response) {
// Handle the success response
console.log(response);
},
error: function(xhr, status, error) {
// Handle the error response
console.log(xhr.responseText);
}
});
});
});
</script>
Update the action
attribute of the <form>
tag to specify the URL where the form data should be submitted. In the example code, the form data is submitted to submit.php
.
In your server-side code (e.g., submit.php
), process the form data and send a response back to the AJAX request.