asobey
asobey

Reputation: 21

How can refresh the page every minute with ajax?

I want to update a div with the minute of the match on my page every 15 seconds. How can i do that ? I just want to refresh the area where that div is.

  <script>
                        setInterval(function () {
                            $.ajax({
                                @*url: '@Url.Action("_List", "Home",new { match_id=Model.match.match_id})',*@
                                cache: false,
                                success: function (result) {
                                    $("#test").html(result);
                                    console.log(result)
                                    //alert(result);
                                }
                            });
                        }, 20000);
    </script>

Upvotes: 0

Views: 650

Answers (1)

Amit Kotha
Amit Kotha

Reputation: 2019

Use partial views for this. They will allow you to update only a part of the DOM without having to perform a full page refresh or a postback and they are strongly typed.

For example I created below partial view

    function loadPartialView() {
   $.ajax({
    url: "@Url.Action("ActionName", "ControllerName")",
    type: 'GET', // <-- make a async request by GET
    dataType: 'html', // <-- to expect an html response
    success: function(result) {
                $('#YourDiv').html(result);
             }
   });
}

$(function() {

   loadPartialView(); // first time

   // re-call the function each 5 seconds
   window.setInterval("loadPartialView()", 5000);

});

After every 5 seconds it goes to controller and executes the action

public class ControllerName: Controller
{
    public ActionResult ActionName()
    {
        .
        .   // code for update object
        .
        return PartialView("PartialViewName", updatedObject);
    }
}

For more information https://cmatskas.com/update-an-mvc-partial-view-with-ajax/

Upvotes: 1

Related Questions