Bart
Bart

Reputation: 269

Get Data from DB every 5 sec and send it through AJAX to Views

I need some help. I want to update Google Maps marker every 5 sec with data from db(mssql).

I have JsonResult witch returning tabel list :

    [System.Web.Mvc.HttpGet]
    JsonResult LoadDB()
    {
        EagleDBEntities db = new EagleDBEntities();

        return Json(db.Coordinates.ToList(), JsonRequestBehavior.AllowGet);
    }

And my Ajax code in Views

        function getData() {

            $.ajax({
                type: "GET",
                url: "Home/LoadDB",
                contentType: "application/json;charset=utf-8",
                dataType: "json",
                success: function (result) {

                    $.each(data.items, function(item) {
                        alert('long:'+item.longitude +' lat:'+item.latitude);
                    });
                },
                error: function (response) {

                    alert('error');
                }
            });

In the and i get error alert , I am not receiving data from the database:(

Failed to load resource: the server responded with a status of 404 (Not Found) http://localhost:7279/Home/LoadDB

Upvotes: 2

Views: 1261

Answers (2)

Bart
Bart

Reputation: 269

I fixed it.

HomeController.cs:

    [HttpGet]
   public JsonResult LoadDB()
    {
        EagleDBEntities db = new EagleDBEntities();
        var cor = db.Lokalizacja          
           .Select(a => new
           {
               szerokosc = a.szerokosc,
               dlugosc = a.dlugosc
           });

        return Json(cor, JsonRequestBehavior.AllowGet);
    }

Maps.cshtml:

        function getData() {

        var counter = 0;
        interval = window.setInterval(function () {
            counter++;

            $.ajax({
                type: "GET",
                url: "LoadDB",
                contentType: "application/json;charset=utf-8",
                dataType: "json",
                success: function (data) {
                    $.each(data, function (i, item) {

                        moveMarker(item.szerokosc, item.dlugosc);

                    });
                },
                error: function (response) {

                    alert('eror');
                }
            });



            marker.setPosition(pos);
            if (counter >= 1000) {
                window.clearInterval(interval);
            }
        }, 10);




    };

Upvotes: 2

Marc Canet
Marc Canet

Reputation: 11

You just have to setup a javascript timer like this one:

setInterval(function(){ getData(); }, 3000);

Upvotes: 1

Related Questions