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

malsup/form

jQuery Form Plugin upgrades standard HTML forms to submit via AJAX with minimal setup. Use ajaxForm or ajaxSubmit to control how data is sent, handle responses, and manage options. Requires jQuery 1.7.2+, works with jQuery 2, partial jQuery 3 support.

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Include Dependencies**:
   ```html
   <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
   <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.form/4.3.0/jquery.form.min.js"></script>
  1. Basic Form Submission:

    <form id="myForm" action="/submit" method="post">
        <input type="text" name="username">
        <input type="submit" value="Submit">
    </form>
    <div id="results"></div>
    
    $(document).ready(function() {
        $('#myForm').ajaxForm({
            target: '#results',
            success: function() {
                alert('Form submitted successfully!');
            }
        });
    });
    
  2. Manual Submission:

    $('#myForm').on('submit', function(e) {
        e.preventDefault();
        $(this).ajaxSubmit({
            url: '/submit',
            dataType: 'json',
            success: function(response) {
                console.log('Success:', response);
            }
        });
    });
    

First Use Case

AJAX-powered form submission without page reloads. Ideal for:

  • Contact forms
  • User registration
  • Dynamic content updates (e.g., search results)

Implementation Patterns

Common Workflows

1. Automatic Form Handling

// Attach to all forms on page load
$('form.ajax-form').ajaxForm({
    target: '#dynamic-content',
    beforeSubmit: validateForm,
    dataType: 'json'
});

Use Case: Global AJAX forms (e.g., admin panels, multi-step forms).

2. Conditional Submission

$('#submitBtn').on('click', function(e) {
    e.preventDefault();
    if (isValid()) {
        $('#myForm').ajaxSubmit({
            url: '/api/endpoint',
            data: { extra: 'data' },
            success: updateUI
        });
    }
});

Use Case: Forms with custom validation/logic before submission.

3. File Uploads with Progress

$('#fileForm').ajaxForm({
    target: '#upload-status',
    iframe: true, // Fallback for older browsers
    uploadProgress: function(event, position, total, percentComplete) {
        $('#progress-bar').css('width', percentComplete + '%');
    }
});

Use Case: Drag-and-drop uploaders, large file handling.

4. Dynamic Form Targeting

// Update multiple targets based on response
$('#dynamicForm').ajaxSubmit({
    target: function() {
        return $('#response-' + $(this).data('type'));
    },
    success: function() {
        $(this).find('input').val(''); // Clear form
    }
});

Use Case: Modals, tabs, or multi-panel UIs.


Integration Tips

Laravel-Specific Patterns

  1. CSRF Token Handling:

    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });
    
    • Include in resources/views/layouts/app.blade.php.
  2. Form Request Validation:

    beforeSubmit: function(arr, $form, options) {
        const errors = validateForm(arr);
        if (errors.length) {
            showErrors(errors);
            return false; // Cancel submission
        }
    }
    
  3. Laravel Routes:

    url: "{{ route('form.submit') }}",
    
    • Use Blade syntax in JavaScript (compile with Laravel Mix).
  4. Response Handling:

    success: function(response) {
        if (response.errors) {
            showFlashMessage('Error', response.errors, 'danger');
        } else {
            showFlashMessage('Success', response.message, 'success');
        }
    }
    

Advanced Patterns

  • Form Partial Updates: Use target: '#form-container > .form-section' to update specific sections.
  • Chaining Submissions:
    $('#step1').ajaxSubmit({
        success: function() {
            $('#step2').ajaxSubmit({ /* ... */ });
        }
    });
    
  • Server-Side Events:
    uploadProgress: function(event, position, total) {
        Laravel.echo.channel('form-uploads')
                .listen('Progress', (e) => {
                    console.log('Server progress:', e.percent);
                });
    }
    

Gotchas and Tips

Pitfalls

  1. jQuery Version Conflicts:

    • Issue: Plugin fails with jQuery 3.5+ due to deprecated methods.
    • Fix: Use jquery.form.min.js from v4.3.0+ or polyfill missing methods.
    • Check: $.param behavior changed in jQuery 3.0+ (see #521).
  2. File Uploads in Modern Browsers:

    • Issue: iframe fallback triggers even with XHR2 support.
    • Fix: Explicitly set iframe: false for non-file forms:
      $('#nonFileForm').ajaxForm({ iframe: false });
      
  3. CSRF Token Mismatch:

    • Issue: Laravel returns 419 (CSRF token mismatch) despite token inclusion.
    • Fix: Ensure token is sent before form submission:
      beforeSubmit: function() {
          $.post('/sanctum/csrf-cookie').then(() => {
              // Proceed with submission
          });
      }
      
  4. Form Data Serialization:

    • Issue: Special characters (e.g., +, spaces) are not URL-encoded.
    • Fix: Use encode: true (default) or manually encode:
      data: { search: encodeURIComponent($('#query').val()) }
      
  5. Event Delegation:

    • Issue: Dynamically added forms fail with delegation: true.
    • Fix: Use event delegation on a static parent:
      $(document).on('submit', 'form.dynamic-form', function(e) {
          e.preventDefault();
          $(this).ajaxSubmit({ /* ... */ });
      });
      

Debugging Tips

  1. Check the jqxhr Object:

    var jqxhr = $('#myForm').ajaxSubmit({ /* ... */ });
    jqxhr.fail(function(jqXHR, textStatus, errorThrown) {
        console.error('Error:', textStatus, errorThrown);
        console.log('Response:', jqXHR.responseText);
    });
    
  2. Inspect Form Data:

    beforeSubmit: function(arr, $form) {
        console.log('Submitting:', $.param(arr));
    }
    
  3. Test with iframe: true:

    • Forces fallback mode to debug XHR2 issues:
      $('#myForm').ajaxSubmit({ iframe: true, iframeSrc: 'javascript:false;' });
      
  4. Laravel Logs:

    • Check storage/logs/laravel.log for server-side errors (e.g., validation failures).

Configuration Quirks

  1. target vs. replaceTarget:

    • target: '#container' replaces content.
    • target: '#container', replaceTarget: true replaces the element itself.
  2. dataType Handling:

    • Laravel JSON responses require dataType: 'json':
      success: function(response) {
          console.log(response.data); // Access nested data
      }
      
  3. clearForm vs. resetForm:

    • clearForm: true clears visible fields (not hidden inputs).
    • resetForm: true resets all fields (including hidden ones).
  4. beforeSerialize vs. beforeSubmit:

    • beforeSerialize: Modify form structure (e.g., hide fields).
    • beforeSubmit: Modify data (e.g., transform values).

Extension Points

  1. Custom Serialization: Override formSerialize for non-standard forms:

    $.fn.formSerialize = function() {
        // Custom logic
        return $.param(this.serializeArray());
    };
    
  2. Progress Events: Extend upload progress with custom metrics:

    uploadProgress: function(event, position, total) {
        const speed = (position / (event.timeStamp - event.startTime)) * 1000;
        console.log('Speed:', speed.toFixed(2), 'B/s');
    }
    
  3. Laravel Service Integration:

    success: function(response) {
        if (response.redirect) {
            window.location.href = response.redirect;
        }
        // Trigger Laravel Echo events
        Laravel.echo.channel('notifications')
                .trigger('form-submitted', response);
    }
    
  4. Conditional Plugin Initialization:

    if ($.fn.jquery.match(/^\d+\.\d+\.\d+$/
    
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.
bugban/symfony
beyonder-capi/workflow-extensions-bundle
beyonder-capi/job-queue-bundle
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin