Search code examples
jquerylaravelyajra-datatable

Yajra datatable is interupting jQuery auto refresh function


I have made alert system for new order. For that I am refreshing div (in header) in every three seconds using jQuery function like this

setInterval(function() {  
    $("#notification-rf1").load(location.href + " #notification-rf1");
    $("#notification-rf2").load(location.href + " #notification-rf2");
    $("#notification-rf3").load(location.href + " #notification-rf3");
}, 3000);

This is working fine on other pages but giving issue on those pages where I am using yajra datatable.

When it refresh after three seconds, then those divs which refreshes (using jQuery in 3 sec) become empty. Means all html inside those divs disappears.

I did some testing and found, if I remove yajra datable's code from controller file then issue get resolves.

Here is the controller code:

 if ($request->ajax()) {
    $data = blog_category::get();
    return Datatables::of($data)
    ->addIndexColumn()
    ->addColumn('action', function($row){
    $category = "'".$row->category."'";
    $data = '<button type="button" class="btn btn-info btn-sm" onclick="return editblogcategory('.$row->id.','.$category.');" data-bs-toggle="modal" data-bs-target="#editcategory"><i class="fa fa-pencil" aria-hidden="true"></i></button>
    <button class="btn btn-danger btn-sm" data-toggle="tooltip" data-original-title="Delete" onclick="return deleteblogcategory('.$row->id.')"><i class="fa fa-trash font-14"></i></button>';

    return $data;
    })
    ->rawColumns(['action'])
    ->make(true);
}

Any solution?


Solution

  • use seperate method/route for your datatables results.

    $request->ajax() will be triggered by $("#notification-rf1").load(location.href + " #notification-rf1"); since it's an ajax call too

    If you want the janky solution and add another condition to differentiate between yajra calls and other ajax calls, you can use the input draw for example which is sent in every request by yajra.

    if ($request->ajax() && $request->draw) {
        $data = blog_category::get();
        ...
    }