Just include your external file.
Edit:
For smaller pieces of code I prefer them right in the page.
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
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);
}
});
});
Please or to participate in this conversation.