How to work with ajax in laravel

Hello World, Today i am going to discuss that how to work with ajax in laravel. In this tutorial, We will create simple example to perform ajax working in laravel. In this example, We will click on a button then load the data with jquery ajax technology and show in the html div element. I hope you will learn and enjoy this tutorial.

I have assumed that you have basic knowledge of laravel. In this tutorial, I am using Laravel 5


I have divided this tutorial in followings steps:

View Template

In this section, we will create blade for our example. Please perform the following steps to create view template in laravel.

  • Create /resources/front.blade.php file and add the following code it
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Ajax Fetch Data</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" />
</head>
<body>
    <div class="container mt-4">
        <p>Click the button below to fetch the data</p>
        <button class="fetch-data btn btn-primary">Fetch Data</button>
        <div class="ajax-data mt-4"></div>
    </div>

{{-- Jquery --}}
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script type="text/javascript">
    var main_site="{{ url('/') }}";
</script>
<script type="text/javascript">
    $(document).ready(function(){
        $(".fetch-data").on("click",function(){
            $.ajax({
                url:main_site+'/posts',
                type:'get',
                dataType:'json',
                beforeSend:function(){
                    $(".ajax-data").html('<p>Loading...</p>');
                },
                success:function(response){
                    var _html='';
                    $.each(response,function(index,value){
                        _html+='<div class="border p-3 mb-4 shadow-sm">';
                        _html+='<h3 class="border-bottom pb-2">'+value.title+'</h3>';
                        _html+='<p>'+value.body+'</p>';
                        _html+='</div>';
                    });
                    $(".ajax-data").html(_html);
                }
            });
        });
    });
</script>
</body>
</html>

So lets understand the jquery ajax part of in the above code.

  • $.ajax helps us to retireve the data from server and show in the html element. In this code, we are clicking on the button and fetch the data from given url with get method.
  • beforeSend method helps to show preloading text while data is fetchong from the database.
  • success will work when data has been received. In this method, We have create variable and add data in this variable with each method and the insert the all data in div element.

In the above file, we have added the bootstrap 4 CSS and Jquery 3 library


Data Controller

In this section, We will create PostController, which helps to provide the data and load the view template. In this example, We are showing data as blog post which include title and body content.

  • Open up your command line and goto the laravel project folder.
  • Enter the following command to create PostController
    • php artisan make:controller PostController
  • After running the above command, you will see that controller has been created in the following path.
  • Create app/Http/Controllers/PostController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class PostController extends Controller
{
    function index(){
        return view('front');
    }
    // Posts
    function fetch_posts(){
        $data=[
            [
                'title'=>'Post 1',
                'body'=>'This is post 1 description'
            ],
            [
                'title'=>'Post 2',
                'body'=>'This is post 2 description'
            ],
            [
                'title'=>'Post 3',
                'body'=>'This is post 3 description'
            ],
        ];
        return response()->json($data);
    }
}

In this controller, I have added the two methods,

  • index – This method helps to render the view file.
  • fetch_posts – This method helps to return the json data to the script. In this method, we have added static data in $data variable.

Url Routing

In this section, we will discuss about url routing. All routing are available in the following path in laravel.

  • Open /routes/web.php and add the following code in it.
// Home
Route::get('home','PostController@index');
// Posts Routes
Route::get('posts','PostController@fetch_posts');

Run the Project

  • Open home url of project in the browser. In my case, it will be http://localhost/learning/public/home
  • You will see the screen with Fetch Data Button.
  • When you click on the button then you will see the post data.

Leave a Reply