Laravel Ajax Example

Working with AJAX in Laravel is similar to any PHP frameworks. We need a view which allows JavaScript or jQuery to send a AJAX request and a controller which receives and parameters, then returns responded data.

For simple use of AJAX in Laravel, you need to import jQuery library in your view file. Then, you can do AJAX functions that will send and receive data from the server. On the server, you can use the response() function to respond with data to the client and if JSON is what they want instead, then chain it with json(). In my example, I use json_encode function of PHP.

Table of Contents

View

This script part should exist in the view which need to call data via AJAX frequently.

<script type="text/javascript">

$(function() {    
   
    setInterval( function(){ fetchOrders(); }, 30000 );
    function fetchOrders(){        
        $.ajax({
             type: 'GET',
             dataType: "json",
             url: '{{ url("/ajax/order/fetch") }}',
             success : function(results) {    
                
                if(results.success){
                    var orders = results.data;
                    if(orders.length > 0){
                        for(var i = 0; i < orders.length; i++){
                                                                                    
                                                
                        }
                    }
                }
                
             }
        }); 
    }    
});
</script>

Controller

In an AJAX controller, we create a method to return a list of orders in JSON format.

<?php

namespace App\Http\Controllers\Ajax;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\URL;

use App\User;


class OrderAjaxController extends Controller
{

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Contracts\Support\Renderable
     */
    public function fetchOrders()
    {
        $user = Auth::user();
        
        //allow Admin to fetch all orders
        if($user->hasRole('Administrator')){
            $orders = Order::whereNotIn('status', ['COMPLETED', 'CANCELLED'])->paginate(100);            
            
            $output = array();
            foreach($orders as $order){
                $order->custom_data = $order->id.'-'.$order->name;                
                $output[] = $order;
            }
            echo json_encode(['success' => true, 'data' => $output]);die;
        }
        echo json_encode(['success' => false]);die;
    }
 
}

Route

We need to map OrderAjaxController->fetchOrders() method to URL /ajax/order/fetch.

//ajax
Route::get('/ajax/order/fetch', ['as' => 'ajax.order.fetch', 'uses' => 'Ajax\[email protected]']);

Leave a Comment

Your email address will not be published. Required fields are marked *

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close