Ajax Requests in Laravel

Dikshant Rajput
4 min readJul 20, 2021

--

Ajax or Asynchronous JavaScript and XML is one of the most beautiful part of webpages to create a request to the backend server from Laravel or PHP based application as it potentially stops the loading of page unnecessarily for a small task like “Liking a post” or “Commenting on a post” and also it saves a lot of resources and a lot of HTTP requests are not being called that a webpage made on every page load.

It’s not that difficult task to make an ajax call using a library like jQuery, Axios, fetch api etc or even you can use vanilla javascript for making an Ajax or XMLHttpRequest.

In this blog I will be telling about how to make an ajax request from your laravel application using jQuery. There are other libraries available out there, you can use any one.

In my previous blogs, I have told about authentication, multi-auth, relationships and many more topics about Laravel. Don’t forget to check them out .

jQuery Ajax Request

It’s very simple to make a basic ajax request without any overhead. If you want to know about all the methods available in jQuery for making an ajax request, visit this :

Let’s start with making a basic request for fetching data of a user.

First of all, we have to add jQuery cdn or we can include the whole package, In this blog, I will be using a CDN like this:

<script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>

Add this in the layouts file that you used to include in your blade file in the end of your body section

Making the request from the blade file :

<div class="user__info p-3">    <small class="error text-danger mb-2 d-block"></small></div>    <button class="btn btn-primary" data-id="{{ auth()->id() }}" onclick="fetchData(this)">       Fetch My Data</button><script>    function fetchData(e){        let id = e.dataset.id        $.ajax({            type:'GET',            url:"{{ route('user.data') }}",            //dataType:'html', (optional)            //headers:{ (optional)               'accept':"Application/json",               'content-type':"Application/json"            //},            data:{id},            success:function(data){                $('.user__info').html(data)             },             error:function(err){                  const error = JSON.parse(err.responseText).message                   $('.error').html(error)              }        })    }</script>

In the above code, fetchData() is a function that is used to send the ajax request with the help of $.ajax() function available with jQuery library

We have to make a route before everything in the routes/web.php file like this :

Route::group(['middleware'=>'auth'],function(){Route::get('user/data',       [App\Http\Controllers\UserController::class,'getData'])-   >name('user.data');});

The UserController getData() method looks something like this:

public function getData(Request $request){    $user_id = $request->id;    $user = User::find($user_id)->first(['name','email','mobile']);    // $user = auth()->user();    return view('users.data',compact('user'));}

In the above method, we have two option to fetch the user. One is by using the auth() facade and the other way is by sending the id as a get parameter and then fetching the user from that id. I have mentioned both the method above.

We are returning the users.data view blade file that contains the appropriate html inside it and it look something like this:

<table border="1"  cellpadding="8" cellspacing="8">    <thead>        <tr>            <th>Name</th>            <th>Email</th>            <th>Mobile</th>        </tr>    </thead>    <tbody>          <tr>              <td>{{ $user->name }}</td>               <td>{{ $user->email }}</td>               <td>{{ $user->mobile }}</td>          </tr>    </tbody></table>

One more thing that I want to focus on here is while using POST method you have to send the csrf token as every request in Laravel is secured by csrf token so we can make a post request and send the csrf token like this:

//change the type to "POST" in $.ajax({}) method and in web.php file$.ajaxSetup({    headers : {       'X-CSRF-TOKEN' : $('meta[name="csrf-token"]').attr('content')    }});

Thats it… You can now send any amount of data or request and fetch data without need of reloading the page.

Thanks for reading the blog. I hope you have liked the blog and if you do…..please hit that clap icon and if you want to read more such blogs…..do follow me.

All the code of this blog is uploaded to github here:

--

--

Dikshant Rajput
Dikshant Rajput

No responses yet