Skip to main content

How to Use Ajax in Laravel

AJAX is a client-side script that communicates to and from a server/database without the need for a page refresh. Think of when you fill out a form on a website. The data you entered is sent to the server, validated, and then processed without your having to do anything other than wait for the response. That’s AJAX in action! And it’s all done behind the scenes.

In Laravel, AJAX Requests are used to send and receive data from a server without refreshing the web page. So, using AJAX in Laravel you can develop a web application that performs all the CRUD operations without reloading the whole web page.

For simple use of AJAX in Laravel, you just 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.

View

<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

<?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

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

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