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

Ajax Bundle Laravel Package

appventus/ajax-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require troopers/ajax-bundle
    

    Add to config/bundles.php (Laravel 5.5+) or AppKernel.php (Symfony):

    Troopers\AjaxBundle\TroopersAjaxBundle::class,
    
  2. Load Assets: Include in your layout (e.g., resources/views/layouts/app.blade.php):

    <!-- CSS -->
    <link rel="stylesheet" href="{{ asset('bundles/troopersajax/css/ajax.css') }}">
    
    <!-- JS (after jQuery) -->
    <script src="https://code.jquery.com/jquery-3.6.min.js"></script>
    <script src="{{ asset('bundles/troopersajax/js/ajax.js') }}"></script>
    
  3. First Use Case: Add data-toggle="ajax" to a link/form and specify a target container:

    <!-- Link Example -->
    <a href="/search" data-toggle="ajax" data-update="results">Search</a>
    <div id="results"></div>
    
    <!-- Form Example -->
    <form action="/submit" method="POST" data-toggle="ajax" data-update="form-result">
        <input type="submit" value="Submit">
    </form>
    <div id="form-result"></div>
    

Implementation Patterns

1. Controller Integration

  • Route AJAX Endpoints:
    Route::get('/search', [SearchController::class, 'ajaxSearch']);
    Route::post('/submit', [FormController::class, 'ajaxSubmit']);
    
  • Return HTML Fragments:
    public function ajaxSearch(Request $request)
    {
        $results = $this->searchService->execute($request->query);
        return view('partials.search_results', compact('results'));
    }
    

2. Dynamic Updates

  • Update Strategies: Use data-update-strategy for granular control:

    <a href="/load-more" data-toggle="ajax" data-update="content" data-update-strategy="append">
        Load More
    </a>
    

    Options: replace (default), append, prepend, before, after, or a custom jQuery method.

  • Form Submission with Data:

    <form data-toggle="ajax" data-update="form-result" data-form="#search-form">
        <input type="hidden" name="action" value="filter">
    </form>
    

    Note: The form’s action attribute is overridden by the link’s href.

3. Auto-Refresh Forms

  • Trigger on Change:
    <select name="category" data-refreshonchange="true">
        <option value="all">All</option>
    </select>
    
  • Controller Handling:
    public function handleCategoryChange(Request $request)
    {
        if (!$request->query->get('novalidate')) {
            $form = $this->formFactory->create();
            $form->handleRequest($request);
            if (!$form->isValid()) {
                $form = $this->formFactory->create();
                $form->setData($request->query->get('user'));
            }
            return $this->renderForm($form);
        }
    }
    

4. Bootstrap Modal Integration

  • Trigger Modal:
    <a href="/modal-content" data-toggle="ajax-modal">Open Modal</a>
    
  • Modal Markup (returned from controller):
    <div class="modal fade">
        <div class="modal-dialog">
            <div class="modal-content">
                <!-- Your content here -->
            </div>
        </div>
    </div>
    

5. Custom Loading States

  • Override Loader:
    window.loader = '<div class="custom-loader">Loading...</div>';
    window.loaderOverlay = '<div class="overlay"></div>';
    
    Place in a <script> tag before ajax.js.

Gotchas and Tips

1. Debugging AJAX Calls

  • Check Console Errors: Ensure jQuery and ajax.js are loaded after jQuery.
    <!-- WRONG: Loads jQuery after ajax.js -->
    <script src="{{ asset('bundles/troopersajax/js/ajax.js') }}"></script>
    <script src="https://code.jquery.com/jquery-3.6.min.js"></script>
    
  • Verify Target Containers: Ensure data-update IDs match existing DOM elements. Use:
    console.log($('#updater-container').length); // Check if element exists
    

2. Common Pitfalls

  • CSRF Tokens: For forms, include a hidden CSRF token:

    <form data-toggle="ajax">
        <input type="hidden" name="_token" value="{{ csrf_token() }}">
    </form>
    
  • Form Validation: The bundle does not handle validation by default. Use Symfony’s isValid() or Laravel’s validate() in your controller.

  • Dynamic Content: If updating containers dynamically (e.g., with JavaScript), reinitialize the bundle:

    $('[data-toggle="ajax"]').ajaxBundle(); // Re-attach events
    

3. Performance Tips

  • Cache Assets: Use Laravel Mix/Vite to bundle ajax.js and ajax.css for production.
  • Lazy-Loading: Defer non-critical AJAX calls until after page load:
    <a href="/lazy-load" data-toggle="ajax" data-defer="true">Lazy Load</a>
    

4. Extension Points

  • Custom Effects: Override default animations by targeting the data-effect attribute:
    // In a separate JS file
    $(document).on('ajax:beforeLoad', function(e, settings) {
        if (settings.effect === 'custom') {
            settings.effect = function() {
                $(this).html(settings.content).slideUp(300).slideDown(500);
            };
        }
    });
    
  • Event Hooks: Listen to lifecycle events:
    $(document).on('ajax:complete', function(e, settings) {
        console.log('AJAX completed for:', settings.target);
    });
    

5. Laravel-Specific Notes

  • Asset Paths: Use Laravel’s mix() for asset paths:
    <script src="{{ mix('js/ajax.js') }}"></script>
    
  • Route Caching: Clear routes after adding AJAX endpoints:
    php artisan route:clear
    

6. Legacy Browser Support

  • Polyfills: For older browsers, include jQuery 1.x and ensure ajax.js is compatible (tested down to jQuery 1.9+).
  • Fallbacks: Provide non-AJAX links for users with JS disabled:
    <a href="/search" data-toggle="ajax">Search (AJAX)</a>
    <a href="/search?fallback=1">Search (No JS)</a>
    
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor