Explain Codes LogoExplain Codes Logo

Jquery AJAX submit form

javascript
ajax
form-submission
javascript-library
Nikita BarsukovbyNikita Barsukov·Feb 27, 2025
TLDR

To have a form submitted with jQuery AJAX, preventDefault() is needed to interdict the standard submission. It is followed by $(this).serialize() to bundle your data and then by $.ajax to land the request. Here's the quick and smart code:

$('form').on('submit', function(e) { e.preventDefault(); // Hold your horses, form! $.ajax({ url: this.action, // Form action? You mean AJAX URL! type: this.method, // Let's recycle the form method type. data: $(this).serialize(), // Wraps up your input nicely with a bow! success: function(data) { alert('Yabba Dabba Doo: ' + data); }, // Flintstones, meet the Flintstones! error: function(err) { alert('Panic at the Desktop: ' + err); } //Not another Panic! at the Disco reference... }); });

Ensure all form input elements have a name attribute for successful serialization. For debugging, console.log is your closest ally. Data including file uploads can be handled using new FormData(this) with AJAX setup adopting processData: false and contentType: false.

More juice, less squeeze: Enhancing AJAX Form Submission

Dynamically Configuring AJAX Requests

Let your AJAX embrace your form's method and action:

$('form').on('submit', function(e) { e.preventDefault(); // Standard form submission? Nah, too mainstream! var method = $(this).attr('method'); // Trust issues with hardcoded stuff? var action = $(this).attr('action'); $.ajax({ url: action, type: method, data: $(this).serialize(), // Dressing delivered separately. ... }); });

Handling AJAX with FormData

Forms housing file inputs can strike a friend in FormData:

$('form').on('submit', function(e) { e.preventDefault(); // Form, you're grounded! var formData = new FormData(this); // Here's a File sandwich (Diet, of course). $.ajax({ url: this.action, type: this.method, processData: false, // Don't even think about it! contentType: false, data: formData, ... }); });

Note: FormData has a rocky relationship with Internet Explorer.

Auto-Submission with Ajax Form Plugin

Achieve auto-submission utopia with the Ajax Form Plugin:

$("#orderproductForm").ajaxForm({ url: 'server.php', // Because 'server.PHP', Get it? type: 'post', success: function(data) { alert('Another order, another dollar: ' + data); } });

Or, send forms hurtling down the track immediately:

$("#orderproductForm").ajaxSubmit({ url: 'server.php', // Same server (still PHP). type: 'post', ... });

Hijax strategy: Best of both worlds

Favour Hijax for an optimal fallback strategy when JavaScript is not your browser's cup of tea.

Chasing Edge Cases and Enhancing UX

Debugging: Your New Best Friend

Unmask AJAX's response with console.log:

success: function(data) { console.log('AJAX whisperer', data); }, error: function(err) { console.error('Oops-a-daisy', err); }

Sailing Smooth with Data Attributes

Data attributes like data-autosubmit can help merge your scripts and HTML with ease:

<form id="myForm" data-autosubmit="true">...</form>
if ($('#myForm').data('autosubmit')) { // trigger submit }

Speed is Success: Caching External Scripts

Caching external scripts can speed up your page loading and keep your code neat:

<!-- Cached external script for AJAX forms --> <script src="path/to/ajax-form.js"></script>

Strategy for Accessibility and Fallback: Always Plan B

Ensure to provide a standard HTML submission when JavaScript is unavailable or turned off, in sync with the principles of Progressive Enhancement.