Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Form Laravel Package

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.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup in Laravel

  1. 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
    
  2. 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>
    
  3. 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']);
    }
    

Implementation Patterns

Common Workflows

  1. 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]);
                });
            }
        }
    });
    
  2. 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>
    
  3. 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>
    
  4. CSRF Protection Ensure Laravel’s CSRF token is included in AJAX requests:

    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });
    
  5. 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
        }
    }
    
  6. 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
        }
    });
    

Gotchas and Tips

Pitfalls

  1. CSRF Token Mismatch

    • Issue: AJAX requests may fail with 419 errors if CSRF token is missing.
    • Fix: Always include the CSRF token in headers or form data:
      headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }
      
  2. File Upload Size Limits

    • Issue: Large file uploads may exceed PHP’s upload_max_filesize or post_max_size.
    • Fix: Adjust php.ini settings or use chunked uploads:
      $('#uploadForm').ajaxForm({
          chunkSize: 1024 * 1024, // 1MB chunks
          // ...
      });
      
  3. jQuery Version Conflicts

    • Issue: The plugin may not work with jQuery 3.x+ due to deprecated methods.
    • Fix: Use jQuery 1.9+ or a compatible version:
      <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
      
  4. Missing enctype Attribute

    • Issue: File uploads fail silently if enctype="multipart/form-data" is omitted.
    • Fix: Always include it for file upload forms.
  5. CORS Issues

    • Issue: Cross-origin requests may be blocked.
    • Fix: Configure CORS in Laravel middleware or use JSONP if needed.
  6. IE-Specific iframeSrc Issue

    • Issue: The plugin now defaults to about:blank for non-IE browsers, which may cause issues in some environments.
    • Fix: If needed, override the default iframeSrc:
      $.ajaxFormDefaults.iframeSrc = 'javascript:false;';
      

Debugging Tips

  1. Check Network Tab Inspect the Request Payload and Response in browser dev tools to verify data is sent/received correctly.

  2. 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); }
    });
    
  3. Validate Server-Side Ensure Laravel routes and controllers are correctly handling the request:

    public function submit(Request $request) {
        dd($request->all()); // Debug incoming data
    }
    

Extension Points

  1. 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
        }
    });
    
  2. 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
        }
    }
    
  3. 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
    });
    
  4. 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>
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui