ahsan-alam-500/ajax-caller

Easy AJAX helper for Laravel with CSRF

Installs: 0

Dependents: 0

Suggesters: 0

Security: 0

Stars: 0

Watchers: 0

Forks: 0

Open Issues: 0

Language:JavaScript

pkg:composer/ahsan-alam-500/ajax-caller

dev-main 2025-09-10 07:15 UTC

This package is auto-updated.

Last update: 2026-01-10 08:07:00 UTC


README

A simple AJAX helper for Laravel that simplifies making fetch requests from your Blade files, with automatic CSRF token handling.

Installation

  1. Install the package via composer:

    composer require ahsan-alam-500/ajax-caller
  2. Publish the package's JavaScript file. You have two options:

    • Publish to the public/vendor directory (recommended):

      php artisan vendor:publish --provider="ahsan-alam-500\AjaxCaller\AjaxCallerServiceProvider" --tag=public
    • Publish to the public/js directory:

      php artisan vendor:publish --provider="ahsan-alam-500\AjaxCaller\AjaxCallerServiceProvider" --tag=ajax-caller-js

    This will publish the ajax-caller.js file to your public/vendor/ajax-caller directory.

Usage

  1. Include the ajax-caller.js script in your Blade template. Make sure you have a CSRF token meta tag in your layout file.

    <!DOCTYPE html>
    <html>
    <head>
        <title>My App</title>
        <meta name="csrf-token" content="{{ csrf_token() }}">
    </head>
    <body>
        <!-- Your content -->
    
        <script src="{{ asset('vendor/ajax-caller/ajax-caller.js') }}"></script>
        <script>
            // Your script here
        </script>
    </body>
    </html>
  2. Use the global call() function to make AJAX requests.

    The call() function has the following signature:

    call(method, url, data = {}, isFormData = false)
    • method: The HTTP method (e.g., 'GET', 'POST', 'PUT', 'DELETE').
    • url: The URL to send the request to.
    • data: An object or FormData to send with the request. Defaults to an empty object.
    • isFormData: A boolean indicating if the data is FormData. Defaults to false.

Example: Sending JSON data

document.getElementById('my-button').addEventListener('click', async () => {
    try {
        const data = { name: 'John Doe', email: 'john.doe@example.com' };
        const response = await call('POST', '/users', data);
        console.log(response);
    } catch (error) {
        console.error('Error:', error);
    }
});

Example: Sending FormData

const form = document.getElementById('my-form');
form.addEventListener('submit', async (event) => {
    event.preventDefault();
    const formData = new FormData(form);
    try {
        const response = await call('POST', '/users', formData, true);
        console.log(response);
    } catch (error) {
        console.error('Error:', error);
    }
});

Contributing

Contributions are welcome! Please feel free to submit a pull request.

License

This project is licensed under the MIT License.