jquery-form/form
jQuery Form Plugin upgrades standard HTML forms to submit via AJAX with minimal setup. Use ajaxForm or ajaxSubmit to serialize and send form data, including file uploads, with extensive options and callbacks for full control over the submission process.
Installation
Add the jQuery Form Plugin via CDN in your resources/views/layouts/app.blade.php (or equivalent):
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.form/4.3.0/jquery.form.min.js"></script>
Or via npm (if using Laravel Mix/Webpack):
npm install jquery-form@4.3.0
Basic Form Submission
Include jQuery and the plugin, then use the ajaxForm method:
<form id="myForm" action="/submit" method="post">
<input type="text" name="username">
<button type="submit">Submit</button>
</form>
<script>
$(document).ready(function() {
$('#myForm').ajaxForm(function() {
alert('Success! Response: ' + $(this).find('input[name="response"]').val());
});
});
</script>
Laravel Route & Controller Define a route and controller to handle the submission:
Route::post('/submit', [FormController::class, 'submit']);
public function submit(Request $request) {
$data = $request->all();
return response()->json(['response' => 'Success']);
}
AJAX Form Submission with Validation
Use ajaxSubmit for one-time submissions with validation feedback:
$('#myForm').ajaxSubmit({
success: function(response) {
// Handle success
},
error: function(xhr) {
if (xhr.responseJSON && xhr.responseJSON.errors) {
$.each(xhr.responseJSON.errors, function(key, value) {
$('#' + key + '_error').text(value[0]);
});
}
}
});
File Uploads with Progress Bar Leverage the plugin’s built-in file upload support:
<form id="uploadForm" action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<button type="submit">Upload</button>
<div class="progress">
<div class="bar"></div>
</div>
</form>
<script>
$('#uploadForm').ajaxForm({
beforeSend: function() {
$('.bar').width('0%');
},
uploadProgress: function(event, position, total, percentComplete) {
$('.bar').width(percentComplete + '%');
},
success: function() {
alert('Upload complete!');
}
});
</script>
Integration with Laravel Blade Dynamically bind forms using Blade directives:
<form id="dynamicForm" action="{{ route('dynamic.submit') }}" method="post">
@csrf
<input type="text" name="dynamic_field">
</form>
<script>
$('#dynamicForm').ajaxForm(function() {
// Handle response
});
</script>
CSRF Protection Ensure Laravel’s CSRF token is included in AJAX requests:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
Laravel Validation Feedback Return Laravel validation errors in JSON format:
public function submit(Request $request) {
$validated = $request->validate([
'username' => 'required|min:3',
]);
return response()->json(['success' => true]);
}
Handle errors in JavaScript:
error: function(xhr) {
if (xhr.status === 422) {
let errors = xhr.responseJSON.errors;
// Display errors
}
}
Form Unbinding with beforeFormUnbind
Use the new beforeFormUnbind callback to handle cleanup before unbinding events:
$('#myForm').ajaxForm({
beforeFormUnbind: function() {
console.log('Form events are about to be unbound');
// Perform cleanup (e.g., remove temporary elements)
},
success: function() {
// Handle success
}
});
CSRF Token Mismatch
419 errors if CSRF token is missing.headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }
File Upload Size Limits
upload_max_filesize or post_max_size.php.ini settings or use chunked uploads:
$('#uploadForm').ajaxForm({
chunkSize: 1024 * 1024, // 1MB chunks
// ...
});
jQuery Version Conflicts
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
Missing enctype Attribute
enctype="multipart/form-data" is omitted.CORS Issues
IE-Specific iframeSrc Issue
about:blank for non-IE browsers, which may cause issues in some environments.iframeSrc:
$.ajaxFormDefaults.iframeSrc = 'javascript:false;';
Check Network Tab
Inspect the Request Payload and Response in browser dev tools to verify data is sent/received correctly.
Log Events
Use the plugin’s event callbacks to debug, including the new beforeFormUnbind:
$('#myForm').ajaxForm({
beforeSubmit: function() { console.log('Submitting...'); },
beforeFormUnbind: function() { console.log('Unbinding...'); },
success: function() { console.log('Success!'); },
error: function(xhr) { console.error('Error:', xhr); }
});
Validate Server-Side Ensure Laravel routes and controllers are correctly handling the request:
public function submit(Request $request) {
dd($request->all()); // Debug incoming data
}
Custom Events
Extend the plugin by binding custom events, including leveraging beforeFormUnbind:
$('#myForm').bind('formcomplete', function() {
console.log('Form completed!');
}).ajaxForm({
beforeFormUnbind: function() {
$('#myForm').unbind('formcomplete'); // Cleanup custom events
}
});
Laravel Service Providers Register global AJAX settings in a service provider:
public function boot() {
if (app()->environment('local')) {
$.ajaxSetup({
headers: { 'X-Requested-With': 'XMLHttpRequest' }
});
$.ajaxFormDefaults.iframeSrc = 'javascript:false;'; // Override iframeSrc if needed
}
}
Laravel Mix/Webpack Bundle the plugin with your assets and ensure the correct version is used:
// resources/js/app.js
import 'jquery-form';
$(document).ready(function() {
// Initialize forms
});
Laravel Livewire/Alpine Integration Use Alpine.js to dynamically initialize forms and handle unbinding:
<form x-data="{ isSubmitting: false }" @submit.prevent="submitForm">
<input type="text" name="username">
<button type="submit" :disabled="isSubmitting">Submit</button>
</form>
<script>
document.addEventListener('alpine:init', () => {
Alpine.data('formHandler', () => ({
submitForm() {
this.isSubmitting = true;
$('#myForm').ajaxSubmit({
success: () => { this.isSubmitting = false; },
error: () => { this.isSubmitting = false; },
beforeFormUnbind: () => {
console.log('Form unbinding in Alpine context');
}
});
}
}));
});
</script>
How can I help you explore Laravel packages today?