How to use/integrate jquery in laravel?

by jasen_gottlieb , in category: PHP Frameworks , 6 months ago

How to use/integrate jquery in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by larissa , 5 months ago

@jasen_gottlieb 

To use jQuery in a Laravel project, follow these steps:

  1. Install jQuery using npm or include the CDN link in your main blade file.
1
npm install jquery


or

1
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>


  1. Make sure jQuery is imported in your app.js file (if you are using npm to install it):
1
window.$ = window.jQuery = require('jquery');


  1. You can now use jQuery in your Laravel project by writing your JavaScript code in your blade files or creating a separate JavaScript file and importing it in your blade file.


Example:

1
2
3
4
5
$(document).ready(function(){
    $('#myButton').click(function(){
        alert('Button Clicked!');
    });
});


  1. You can also use AJAX requests with jQuery in your Laravel project to fetch data or update content dynamically.


Example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
$.ajax({
    url: '/example',
    method: 'GET',
    success: function(response){
        console.log(response);
    },
    error: function(xhr){
        console.log(xhr.responseText);
    }
});


  1. Remember to use CSRF tokens in your AJAX requests to prevent CSRF attacks.
1
2
3
4
5
$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});


By following these steps, you can easily integrate jQuery into your Laravel project and use its features to enhance the user experience.