AJAX Form Submission and Feedback
Master submitting form data asynchronously via AJAX, providing real-time user feedback, and handling server responses without full page reloads for a smoother UX.
AJAX Form Submission and Feedback is a free jQuery Academy lesson on CoddyKit — lesson 3 of 3. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the jQuery Academy learning path, one of 3 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Smooth Forms with AJAX
Imagine submitting a form without the entire page reloading! That's the magic of AJAX form submission.
Instead of a full page refresh, AJAX lets you send form data to a server in the background. This provides a much smoother, faster user experience, perfect for comments, sign-ups, or quick updates.
Stopping Default Submission
The first step in an AJAX form submission is to prevent the browser's default behavior. If you don't, the page will reload as usual, defeating the purpose of AJAX!
We achieve this by calling event.preventDefault() inside our form's submit handler.
<form id="myForm">
<label for="username">Name:</label>
<input type="text" id="username" name="username" placeholder="Your name">
<button type="submit">Submit</button>
</form>
<div id="status"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('#myForm').submit(function(event) {
event.preventDefault(); // Stop default form submission
$('#status').text("Form submission prevented!");
console.log("Form submission prevented!");
});
});
</script>Preparing Form Data
Before sending form data via AJAX, we need to package it correctly. jQuery's .serialize() method is perfect for this!
- It automatically collects values from all input, select, and textarea elements within the form.
- It encodes them into a URL-encoded string (e.g.,
name=Alice&email=alice%40example.com). - This string is the standard format for sending form data to a server.
<form id="dataForm">
<label for="name">Name:</label>
<input type="text" id="name" name="name" value="Bob">
<label for="email">Email:</label>
<input type="email" id="email" name="email" value="bob@example.com">
<button type="submit">Get Data</button>
</form>
<div id="output"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('#dataForm').submit(function(event) {
event.preventDefault();
let formData = $(this).serialize();
$('#output').text("Serialized: " + formData);
console.log(formData); // name=Bob&email=bob%40example.com
});
});
</script>Sending the AJAX Request
With the form data serialized, we can now send it to the server. jQuery offers several AJAX methods, but $.post() is a convenient shortcut for sending data using the HTTP POST method.
It takes the server URL, the serialized data, and an optional callback function to run on success.
<form id="submitForm">
<label for="msg">Message:</label>
<input type="text" id="msg" name="message" value="Hello AJAX!">
<button type="submit">Send</button>
</form>
<div id="response"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('#submitForm').submit(function(event) {
event.preventDefault();
let formData = $(this).serialize();
// Using a dummy API endpoint for demonstration
$.post("https://jsonplaceholder.typicode.com/posts", formData, function(data) {
$('#response').text("Success! Server ID: " + data.id);
console.log("Server response:", data);
});
});
});
</script>Displaying Loading Feedback
When a user clicks submit, they expect an immediate response. Since AJAX requests are asynchronous, there's a delay. Providing visual feedback is crucial!
You can show a 'Loading...' message or a spinner while the request is in progress, and hide it once the response arrives.
<style>
#loading { display: none; color: gray; }
</style>
<form id="feedbackForm">
<label for="item">Item:</label>
<input type="text" id="item" name="item" value="New Widget">
<button type="submit">Add</button>
</form>
<div id="loading">Loading...</div>
<div id="status"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('#feedbackForm').submit(function(event) {
event.preventDefault();
$('#loading').show(); // Show loading indicator
$('#status').text(''); // Clear previous status
let formData = $(this).serialize();
$.post("https://jsonplaceholder.typicode.com/posts", formData, function(data) {
$('#loading').hide(); // Hide loading
$('#status').text("Item added with ID: " + data.id);
});
});
});
</script>Handling Success Responses
Once the server successfully processes the form data, it usually sends back a response. This might be a confirmation message, the ID of a newly created record, or updated data.
The success callback function (the third argument in $.post()) receives this data, allowing you to update your UI accordingly.
<form id="addTodoForm">
<label for="todoTitle">Todo:</label>
<input type="text" id="todoTitle" name="title" placeholder="New todo item">
<button type="submit">Add Todo</button>
</form>
<ul id="todoList"></ul>
<div id="message"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('#addTodoForm').submit(function(event) {
event.preventDefault();
$('#message').text('Adding...');
let formData = $(this).serialize();
$.post("https://jsonplaceholder.typicode.com/todos", formData, function(todo) {
$('#message').text('Todo added!');
$('#todoList').append('<li>' + todo.title + ' (ID: ' + todo.id + ')</li>');
$('#addTodoForm')[0].reset(); // Clear form fields
});
});
});
</script>Graceful Error Handling
Not all requests succeed. Network issues, server errors, or invalid data can cause an AJAX request to fail. It's vital to handle these errors gracefully and inform the user.
For $.post(), you can chain a .fail() method. For $.ajax(), you can use the error callback or the .fail() method on the returned Deferred object.
<form id="errorForm">
<label for="badData">Data:</label>
<input type="text" id="badData" name="data" value="bad value">
<button type="submit">Submit</button>
</form>
<div id="errorMessage" style="color: red;"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('#errorForm').submit(function(event) {
event.preventDefault();
$('#errorMessage').text('');
let formData = $(this).serialize();
// Simulating an error by posting to a non-existent endpoint
$.ajax({
url: "https://jsonplaceholder.typicode.com/nonexistent-endpoint", // Will cause a 404 error
type: "POST",
data: formData
})
.done(function(data) {
$('#errorMessage').text("Unexpected success!");
})
.fail(function(jqXHR, textStatus, errorThrown) {
$('#errorMessage').text("Error: " + textStatus + " - " + errorThrown);
console.error("AJAX Error:", textStatus, errorThrown);
});
});
});
</script>Clearing Forms After Submission
After a successful form submission, it's a good user experience to clear the input fields. This prevents accidental resubmissions and provides a clean slate for the next action.
You can use the native DOM .reset() method on the form element, or manually clear individual input values.
<form id="clearForm">
<label for="item">Item:</label>
<input type="text" id="item" name="item" value="Item A">
<label for="quantity">Quantity:</label>
<input type="number" id="quantity" name="quantity" value="1">
<button type="submit">Add</button>
</form>
<div id="feedbackMsg" style="color: green;"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('#clearForm').submit(function(event) {
event.preventDefault();
$('#feedbackMsg').text('Submitting...');
let formData = $(this).serialize();
$.post("https://jsonplaceholder.typicode.com/posts", formData, function(data) {
$('#feedbackMsg').text('Successfully added! ID: ' + data.id);
$('#clearForm')[0].reset(); // Clears all form fields
});
});
});
</script>Full AJAX Form Example
Let's combine all the techniques we've learned: preventing default submission, serializing data, sending the AJAX request, showing loading feedback, handling both success and failure responses, and finally, clearing the form.
This comprehensive approach ensures a robust and user-friendly AJAX form experience.
<style>
#loader { display: none; color: blue; }
#result { margin-top: 10px; font-weight: bold; }
</style>
<form id="fullAjaxForm">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<button type="submit">Register</button>
</form>
<div id="loader">Processing...</div>
<div id="result"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('#fullAjaxForm').submit(function(event) {
event.preventDefault(); // Stop default form submission
$('#loader').show(); // Show loading indicator
$('#result').text(''); // Clear previous results
let formData = $(this).serialize(); // Serialize form data
$.ajax({
url: "https://jsonplaceholder.typicode.com/users", // Dummy API endpoint
type: "POST",
data: formData,
dataType: "json" // Expect JSON response
})
.done(function(response) {
$('#result').css('color', 'green').text('Registration successful! ID: ' + response.id);
$('#fullAjaxForm')[0].reset(); // Clear form fields
})
.fail(function(jqXHR, textStatus, errorThrown) {
$('#result').css('color', 'red').text('Registration failed: ' + textStatus);
console.error("AJAX Error:", textStatus, errorThrown);
})
.always(function() {
$('#loader').hide(); // Always hide loading indicator
});
});
});
</script>Check Your Understanding
You've learned how to submit forms with AJAX, providing real-time feedback. Let's test your knowledge!
Recap: Smooth Form Submissions
Congratulations! You've mastered AJAX form submission, enhancing your web applications with smooth, non-disruptive user experiences.
- You learned to prevent default form behavior with
event.preventDefault(). - You used
.serialize()to easily prepare form data for transmission. - You implemented
$.post()or$.ajax()to send data asynchronously. - You added crucial real-time user feedback for loading, success, and error states.
- Finally, you learned to clear forms after submission for a clean user interface.
These skills are essential for building modern, responsive web forms!
Frequently asked questions
Is the “AJAX Form Submission and Feedback” lesson free?
Yes — the full text of “AJAX Form Submission and Feedback” is free to read here on the web, and the jQuery Academy course includes 3 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the jQuery Academy course, upgrade to CoddyKit PRO.
What will I learn in “AJAX Form Submission and Feedback”?
Master submitting form data asynchronously via AJAX, providing real-time user feedback, and handling server responses without full page reloads for a smoother UX. You practise jQuery Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start jQuery Academy?
No prior experience is required. jQuery Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 3, so you can start here or from the beginning and move at your own pace.
How long does the “AJAX Form Submission and Feedback” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this jQuery Academy lesson?
Yes. Every jQuery Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Dynamic Form Field Manipulation
- Client-Side Form Validation Logic
- AJAX Form Submission and Feedback