Ajax polling in Laravel
Tags: laravel, php, polling, javascript
Published: 2023-03-16 05:39:13

The following html will keep fetching data from the controller function `load_notification_list()` and refresh the dataTable content every setInterval() function's mentioned milliseconds.

This isn't always never a good practice however this takes no time to setup if compared to other alternatives like SSe's or WebSockets


Controller:

```php

public function get_notifications()
    {
      try
      {
        $data = [];
        $data['notifications'] = Notification::all();
        
        return view('admin.notification.view', $data);
      }
      catch(Exception $e)
      {
        abort(400);
      }
    }


public function load_notification_list(Request $request)
    {
      $inputs     = $request->all();
	    $start      = 0; $limit = $this->perpage; 
	    $column     = @$inputs['columns'][@$inputs['order'][0]['column']]['data'];
	    $dir        = @$inputs['order'][0]['dir'];

      $notif_list['data'] = [];

      $notifications = Notification::take($limit)->skip($start);
      $notifications = $notifications->get();
		
	    foreach ($notifications as $key => $notif) {
	    	switch ($notif->type) {
	    		case '0':	
	    			$status='Pending';
	    			break;
	    		case '1':
	    			$status='Active';
	    			break;
	    		case '2':
	    			$status='Upcomming';
	    			break;
	    		case '3':
	    			$status='Review';
	    			break;
	    		case '4':
	    			$status='Live';
	    			break;
	    		case '5':
	    			$status='Complete';
	    			break;
				case '6': //Added
					$status='Cancelled';
					break;
	    		default:
	    			$status='';
	    			break;
	    	}
	      	
	        // $notif_list['data'][$key]['sent_by']=$notif->sent_by->name;
	        $notif_list['data'][$key]['sent_by']=$notif->sender_id;
	        // $notif_list['data'][$key]['received_by']=$notif->received_by->name;
	        $notif_list['data'][$key]['received_by']=$notif->receiver_id;
	        // $notif_list['data'][$key]['title']=$notif->event->event_name;
	        $notif_list['data'][$key]['isRead']=($notif->isRead == '2'?'Un-Read':'Read');
	        $notif_list['data'][$key]['type']=$status;
	        $notif_list['data'][$key]['message']=$notif->msg;
	        $notif_list['data'][$key]['notify_date']=$notif->notify_date;
          // $event_list['data'][$key]['Status']=$status;
          // $event_list['data'][$key]['action']='<div class="hidden-sm hidden-xs action-buttons">
          //           <a class="blue" href="'.route('view_event',['eventid'=>$event->id]).'" title="View">
          //             <i class="ace-icon fa fa-search-plus bigger-130"></i>
          //           </a>
          //           <a class="green" href="'.route('edit_event',['eventid'=>$event->id]).'" title="Edit">
          //             <i class="ace-icon fa fa-pencil bigger-130"></i>
          //           </a>
          //         </div>';
      }

      $notif_list['recordsTotal'] =Notification::count();
      $notif_list['recordsFiltered']=$notif_list['recordsTotal'];
	
	    return response($notif_list);
    }


```



view.html
```html

@extends('layouts.admin')

@section ('title')

Notification list

@endsection

@section('content')


    <div class="page-content">
        <div class="page-header">
            <div class="row">
                <div class="left-sec col-md-6">
                <h1>
                Notifications
                </h1>
            </div>
        </div>
        
        <div class="row">
        <div class="col-xs-12">
            <div>
                <table id="event-list" class="table table-striped table-bordered table-hover dataTable no-footer" style="width: 100%">
                    <thead>
                        <tr>
                            <th class="center">
                                Sent By
                            </th>
                            <th class="center">
                                Received By
                            </th>
                            <th class="center">
                                Title
                            </th>
                            <th class="center">
                                Type
                            </th>
                            <th class="center">
                                Message
                            </th>
                            <th class="center">
                                Notify Date
                            </th>
                        </tr>
                    </thead>

                    <tbody>
                    </tbody>
                </table>
            </div>	
            </div><!-- /.col -->
    </div><!-- /.row -->
    </div>


@endsection

@section('custom_script')

<script type="text/javascript">

    function InitializeTable(event_name, start_date, end_date, status) {
		$("#event-list").dataTable().fnDestroy();
		$('#event-list').DataTable({  
        	'aoColumnDefs': [
			  {
			     bSortable: false,
			     aTargets: [ 1, 3, ]
			  }
			],
	        "lengthChange" : false,
	        "pageLength": 10,
	        "processing": true,
	        "serverSide": true,
			"order": [[ 1, 'desc' ]],
	        "ajax": {
	            url:"{{route('load_notifications')}}",
	            type: "POST",
	            data:{'_token':'{{ csrf_token() }}'}
	        },
	        "fnDrawCollback": function (oSettings) {
	            
	        },
	        "language":{"processing": "<div class='loading-parent'><div class='loading'>Loading ...</div></div>"},
	        
	        "columns": [
	            { "data": "sent_by" },
	        	{ "data": "received_by" },
	            { "data": "isRead" },
	            { "data": "type" },
	            { "data": "message" },
	            { "data": "notify_date" },
	            
	        ],
	    });
	}


    $(document).ready(function() {
        
         setInterval(() => {
            InitializeTable('', '', '', '');
        }, 2000);
		
    });

</script>

@endsection
```