Explain Codes LogoExplain Codes Logo

How to do a Jquery Callback after form submit?

javascript
ajax
callbacks
promises
Anton ShumikhinbyAnton ShumikhinΒ·Feb 17, 2025
⚑TLDR

For a jQuery callback after form submission, capture the submit event using .on(), halt the default submission activity through e.preventDefault(), then run $.ajax() to relay form data and manage the resulting response.

$('form').on('submit', function(e) { e.preventDefault(); // Hang on! Let's deal with this ourselves. $.ajax({ url: this.action, type: this.method, data: $(this).serialize(), // All aboard the payload train! Choo choo! success: function() { alert('Submitted and duly processed! High five πŸ™'); } }); });

Using serialize() helps package the form data and ajax()'s success enables post-submission actions, ensuring the form submits asynchronously and runs your code following success.

Detailed Breakdown

Managing Different Scenarios

Think beyond the successful form submission. Leverage $ajax()'s complete and statusCode callbacks to cater to variety of server responses. Always expect the unexpected, because, well... Murphy's law, right?

$('form').on('submit', function(e) { e.preventDefault(); $.ajax({ url: this.action, type: this.method, data: $(this).serialize(), complete: function(jqXHR, textStatus) { // You can do something on completion of the request, regardless of success or failure. // Or have a cup of coffee β˜•, your choice! }, statusCode: { 404: function() { alert('Page not found! Did you check in your basement?'); }, 500: function() { alert('Internal server error! We all have those days, don't we?'); } }, success: function(data) { // handle a successful response // Party time! πŸŽ‰ }, error: function(jqXHR, textStatus, errorThrown) { // handle errors // Sad times 😞 } }); });

Data Serialization and Server Side Actions

When using $(this).serialize(), ensure form elements all have name attributes which jQuery uses to key the serialized data.

Handling data server-side, you would structure your logic to respond appropriately whether in PHP or MVC:

if ($_SERVER["REQUEST_METHOD"] == "POST") { // Use $_POST superglobal to access form data // Perform your server-side logic here echo json_encode($response); // send back a JSON response... because you're a good person! }

For MVC, return a JsonResult and use AjaxOptions:

[HttpPost] [ValidateAntiForgeryToken] public JsonResult ActionName(FormModel model) { // Validate and process model return Json(new { success = true, message = "Processed! Pat yourself on the back!" }); }

UX Feedback and Validation

For happy users, consider displaying post-submit messages using plugins like $.toastmessage or display fancy loading spinners. Everyone loves a spinner!

$('form').validate({ rules: { // Define rules for form inputs. Naughty or nice, everyone gets through! }, messages: { // Define custom messages or let jQuery insult your users. } });

Deep Dive: Advanced Scenarios

Asynchronous Form Handling with Promises

Manage your AJAX flow with deferred objects or promises to keep your code clean and readable.

Form Complexities & MVC AjaxOptions

Working with complex forms? Use .serializeArray() or Ajax.BeginForm() with AjaxOptions in MVC.

JSON Handling and Server Response Techniques

Utilize $.parseJSON() for efficient parsing of JSON strings. Remember, nobody likes a stringy soup!