How to auto refresh a div every x seconds with laravel?

by darrion.kuhn , in category: PHP Frameworks , 6 months ago

How to auto refresh a div every x seconds with laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by ryleigh , 6 months ago

@darrion.kuhn 

To auto refresh a div every x seconds with Laravel, you can use JavaScript and AJAX to periodically reload the content of the div. Here is a basic example:

  1. In your Blade template, add a div with an id that you want to refresh:
1
<div id="myDiv"></div>


  1. Add a JavaScript function to make an AJAX request and update the content of the div:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
<script>
    function refreshDiv() {
        $.ajax({
           url: '/refresh',
           type: 'GET',
           success: function(response) {
               $('#myDiv').html(response);
           }
        });
    }

    $(document).ready(function() {
        refreshDiv();
        setInterval(refreshDiv, 5000); // Refresh every 5 seconds
    });
</script>


  1. Create a route in your Laravel routes file to handle the AJAX request:
1
2
3
4
Route::get('/refresh', function() {
    $data = // fetch the data you want to display in the div
    return view('partials.myDiv')->with('data', $data);
});


  1. Create a partial view file for the content you want to display in the div (e.g., resources/views/partials/myDiv.blade.php):
1
{{ $data }}


Now, every 5 seconds, the myDiv div will be refreshed with the data fetched from your Laravel application.