Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

jhyaps's avatar

How to refactor AJAX functionality from Blade files to separate JavaScript files in Laravel project?

I currently have AJAX functions embedded within my Blade files, but I want to refactor them into separate JavaScript files in my Laravel project. Could someone guide me on the steps to achieve this seamlessly? I want to maintain the functionality while keeping my code organized and modular. Any insights or best practices would be greatly appreciated. Thank you!

currently i am using vite , where all my custom js is under the resources > js > theme.js folder

$('#submitForm').click(function(e) {
            e.preventDefault();

            $.ajaxSetup({
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                }
            });

            var form_id = "setting_form";
            var index_route = "{{ route('settings.index', app()->getLocale()) }}";
            var update_route = "{{ route('settings.update', app()->getLocale()) }}";

            var formData = new FormData(document.getElementById(form_id));

            $.ajax({
                url: update_route,
                type: 'POST',
                dataType: 'json',
                data: formData,
                contentType: false,
                processData: false,
                cache: false,
                beforeSend: function() {
                    $('span.error-text').text('');
                    $('#submitForm').html("please wait").attr("disabled", true); // corrected text
                },
                success: function(data) {
                    if (data.success) {
                        window.location.href = index_route; // corrected variable name
                    } else if (data.error_from == "exception") {
                        alert("Error while adding question.");
                    } else {
                        $('.is-invalid').removeClass('is-invalid');
                        $.each(data.error, function(key, value) {
                            $('#' + form_id).find('[name="' + key + '"]').addClass('is-invalid');
                            $('span.' + key.replace(/\./gi, "_") + '_error').append(value);
                        });
                    }
                },
                error: function(request, status, error) {
                    alert(error);
                },
                complete: function() {
                    $('#submitForm').html("save").attr("disabled", false);
                }
            });
        });
0 likes
10 replies
jlrdw's avatar

Just include your external file.

Edit:

For smaller pieces of code I prefer them right in the page.

1 like
jhyaps's avatar

@jlrdw

Actually i want to create a generic ajax function in my js file.

currently i have form for setting, address and many others , and that form will use this above js file.

how to do ?

gych's avatar

@jhyaps In your component add the desired scripts like this

@push('scripts')
    <script src="/yourscript.js"></script>
@endpush

And then add @stack to the head of your main blade file

<head>
    @stack('scripts')
</head>

It should also be possible to just use this in the blade component where you want to add the js file. Add the file to public/js

<script type="text/javascript" src="{{asset('/js/yourscript.js')}}">
1 like
jhyaps's avatar

@gych Hi thanks,

actually i want my file to be in resources/js

is that possible with your idea ?

gych's avatar

@jhyaps It needs a different approach when you want to store the file in resources/js. The files then need to be included in the build of your application.

Are you using Vite ?

1 like
jaseofspades88's avatar

I would recommend you also take this opportunity to move away from jQuery and consider something like Vue, which usually rolls with Axios for improved ajax requests. If you use something like Vite or webpack to compile your Vue files, you'll be in a much better position to import files from your resources directory and include them across your project.

2 likes
Snapey's avatar

An important thing to note is that you cannot use blade in your javascript files.

For instance, the following will fail

        var index_route = "{{ route('settings.index', app()->getLocale()) }}";
        var update_route = "{{ route('settings.update', app()->getLocale()) }}";
2 likes
Tray2's avatar

I would just do this in a js file

async function getRequest(url, parameters = {}) {
    try {
        let responsePromise = await fetch(connectionString + url, { method: 'GET', headers: parameters });
        if (!responsePromise.ok) {
            throw new Error(responsePromise.status);
        }
        return await responsePromise.json();
    } catch (error) {
        return error;
    }
}

async function postRequest(url, parameters = {}) {
    try {
        let responsePromise = await fetch(connectionString + url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: new URLSearchParams(parameters)
        });
        if (!responsePromise.ok) {
            throw new Error(responsePromise.status);
        }
        return await responsePromise.json();
    } catch (error) {
        return error;
    }
}

This would cover most of your ajax needs.

You just call it like this.

async function loadPrinter() {
    let response = await getRequest('/api/v1/loadprinter');
    setDefaultPrinter(response.printer);
}

async function printBarcodeLabel(address) {
    const parameters = {
        'printer': getDefaultPrinter(),
        'label': 'address-barcode',
        'address': address
    }

    const response = await postRequest('/printlabel', parameters);
    if (response.message != null) {
        showAlert('Could not print barcode label (' + response.message + ')');
    } else {
        showAlert('Barcode label printed.');
    }
}
2 likes

Please or to participate in this conversation.