mercredi 3 juillet 2019

What is the best way or how do you recommend working JS files in conjunction with Laravel 5.5?

I expose my doubt/problem. I am currently working on a project with Laravel 5.5. The project has many AJAX requests using JQuery to server urls.

Currently, in some of my views I have the JS code at the end of the blade file.

Illustrative example: users.blade.php

<h1>Usuarios</h1>
@foreach ($users as $user)
    <p> <span class="delete-user" data-user="">Eliminar Usuario</span></p>
@endforeach

<script>
    $(document).on('click', '.delete-user', function () {
        $.ajax({
            url: "",
            type: "POST",
            data: { id: $(this).data('user') }, 
            dataType: "JSON",
            success: function (response) {
                // Hacer algo
            },
            error: function (jqXHR, timeout, message) {
                // Hacer otra cosa
            }
        });
    });
</script>

As you can see in the previous example, I have my user view, and clicking on the element with delete-user class makes an AJAX call to the server.

This is how most of the views of the project have been worked. I don't know how correct it is to handle it that way, but that's the way I've done it, no way.

The project is doing mostly using ES6 features, but it is necessary that the project works in older versions of some browsers that do not support these features, so I decided to use BabelJS for the JS code.

The complicated thing now is that every view or blade.php file has JS code, to use BabelJS would be too laborious to take the code from each view, transform it with BabelJS and then paste it into the view. I know it's not the right or the best or the recommended way.

I thought that the ideas would be to move all the JS of the project to their respective JS files in the folder public/js and use BabelJS on that path, but it happens that from JS files I can not make use of PHP variables or functions, for example:

route('users.delete')

for AJAX request paths.

I have thought about the footer of my project, defining JS constants with the urls and other values that are necessary for AJAX requests, etc. But I don't know if this is the best option.

In cases as well as recommending to work JS code that needs variables or values passed from PHP or in a general way, how do you recommend to manage the JS code to keep it separated from my blade views but that I can make my AJAX requests to my project paths?



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2J9R8pw
via IFTTT

Aucun commentaire:

Enregistrer un commentaire