I have a app.blade.php
laravel file where I wrote javascript code, precisely an ajax request that is directed to the controller in laravel, but I don't know how to pass it to a separate .js file since I use blade syntax in the script of the file in the route to send it to the laravel controller and redirecting it to another page app.blade.php
, how can I write that blade syntax in a javascript file? since I understand that in javascript you can't write blade syntax.
Script code at the end ofapp.blade.php
I want to pass this code to a separate javascript file, but make it dynamic since it will be uploaded to a hosting.
<script>
$(document).on('click', '#login', function (e) {
/* EVITAR EVENTO DEFAULT DEL BOTON */
e.preventDefault();
let email = $('#email').val();
// alert(email);
let password = $('#password').val();
// alert(password);
$.ajax({
url : '{{url('admin/auth')}}',
method : 'post',
data : {
_token : '{{csrf_token()}}',
email : email,
password: password
},
success: (data) => {
console.log(data);
if (data !== 'Éxito') {
toastr.options = {
'closeButton' : false,
'debug' : false,
'newestOnTop' : false,
'progressBar' : false,
'positionClass' : 'toast-top-right',
'preventDuplicates': false,
'onclick' : null,
'showDuration' : '300',
'hideDuration' : '1000',
'timeOut' : '5000',
'extendedTimeOut' : '1000',
'showEasing' : 'swing',
'hideEasing' : 'linear',
'showMethod' : 'fadeIn',
'hideMethod' : 'fadeOut'
};
toastr.error(data);
} else if (data === 'Éxito') {
toastr.options = {
'closeButton' : false,
'debug' : false,
'newestOnTop' : false,
'progressBar' : false,
'positionClass' : 'toast-top-right',
'preventDuplicates': false,
'onclick' : null,
'showDuration' : '300',
'hideDuration' : '1000',
'timeOut' : '5000',
'extendedTimeOut' : '1000',
'showEasing' : 'swing',
'hideEasing' : 'linear',
'showMethod' : 'fadeIn',
'hideMethod' : 'fadeOut'
};
toastr.success(data);
setTimeout(() => {
window.location = '{{url('admin/dashboard')}}';
}, 1500);
{{--window.location = '{{url('admin/dashboard')}}';--}}
}
}
});
});
</script>
I don't know if I understood your question correctly, but I see that what you use from the blade syntax there is the
csrf_token
right? so simple.It is recommended that you serve that Ajax request in a Laravel api route , create a new route of this type, that uses the middleware and points to your method of that controller; by doing this you don't need the with jQuery . it only sends the request with the necessary data and the rest.
api
csrf token
It is also ideal for this type of request, the web in your
web.php
and the ajax in yourapi.php
I say this because I use Axios and Laravel, I have not used jQuery but I understand that in this case it works the same