简体   繁体   中英

How to auto refresh a div every x seconds with laravel

This maybe a broad question but here is the thing. I am using laravel and i have a database notification which displays the amount of unread badges (bootstrap badges) and a list of read and unread notifications. I want to be able to refresh only that div every 5 seconds or so.

Here is the code for database notification on my blade so far (admin-master.blade.php):

<li class="dropdown">
  <a href="#" class="dropdown-toggle" data-toggle="dropdown">
    <i class="lnr lnr-bullhorn"></i>
    <span class="badge badge-light">{{\Illuminate\Support\Facades\Auth::guard('admin')->user()->unreadNotifications()->count()}}</span>
    <i class="icon-submenu lnr lnr-chevron-down"></i>
  </a>
  <ul class="dropdown-menu">
                            @foreach(\Illuminate\Support\Facades\Auth::guard('admin')->user()->unreadNotifications as $notifications)

    <li>
      <a class="unreadNotifications" href="{{route('receptionist.markasread', $notifications->id)}}">{{$notifications->data['data']}}</a>
    </li>
                            @endforeach
                                @foreach(\Illuminate\Support\Facades\Auth::guard('admin')->user()->readNotifications()->take(4)->get() as $notifications)

    <li>
      <a class="readNotifications" href="/admin/roomstatus">{{$notifications->data['data']}}</a>
    </li>
                                @endforeach

  </ul>
</li>

So my question is, how can i use JS with this laravel to refresh the whole div. I want to be able to refresh both the badges and the actual notifications. I have seen some posts on stack overflow suggesting to use AJAX to "load" an html. I am not sure how i could achieve that with laravel.

Thanks

Ok so here is how i resolved the issue.

I used jquery ajax to fetch a route. The route goes to a controller function which passes a view. The original Questions code is in the view.

Here is my AJAX:

function loadlink(){
        $('#reload').load('/loadNotification');
        console.log('TESTING!!!!');
    }

    loadlink();
    setInterval(function(){
        loadlink()
    }, 10000);

So i refresh only that element id every 10 seconds. Of course you could listen for any database changes as well if you don't want to use a timer. a timer in my case suited my needs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM