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.
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]']);