su star su star - 2 months ago 16
jQuery Question

Refresh JavaScript and Ajax call to controller after 3 seconds without any click in Razor View in MVC 4

Controller Action :

public ActionResult googlemap()
{
return View();
}


It will call the googlemap.cshtml View.
So Ajax Call and JavaScript code in googlemap.cshtml View :



@{
ViewBag.Title = "Google Map";
}
<script src="~/Scripts/jquery-1.8.2.js"></script>
<script src="~/Scripts/jquery-1.8.2.min.js"></script>
<script src="http://maps.googleapis.com/maps/api/js?key=AIzaSyCM7G5ruvunb0K7qxm6jb1TssJUwROqs-g" type="text/javascript"></script>

<script type="text/javascript">
var myMarkers = [];
window.onload = function () {
$.ajax({
async: false,
type: "POST",
dataType: "json",
url: '@Url.Action("googlemapfindlatlon", "Home")',
data: '{}',
success: function (data) {
$.each(data, function (i, v) {
myMarkers.push(v);
});
var mapOptions = {
center: new google.maps.LatLng(myMarkers[0].Latitude, myMarkers[0].Langitude),
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
//alert(myMarkers[0].Latitude)
//alert(myMarkers[0].Langitude)
var infoWindow = new google.maps.InfoWindow();
var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
var lat_lng = new Array();
var latlngbounds = new google.maps.LatLngBounds();
for (i = 0; i < myMarkers.length; i++) {
var data = myMarkers[i]
var myLatlng = new google.maps.LatLng(data.Latitude, data.Langitude);
lat_lng.push(myLatlng);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: data.title
});
latlngbounds.extend(marker.position);
(function (marker, data) {
google.maps.event.addListener(marker, "click", function (e) {
infoWindow.setContent(data.Address);
infoWindow.open(map, marker);
});
})(marker, data);
}
//map.setCenter(latlngbounds.getCenter());
//map.fitBounds(latlngbounds);
}

});

//init google map

}
</script>

<div id="map_canvas" style="border-top: none; width: 100%; margin-top: -1px;
height: 250px; background-color: #FAFAFA; margin-top: 0px;">
</div>





JsonResult action in Controller :

public JsonResult googlemapfindlatlon()
{

Models.Vehicle_Tracking_SystemEntities entities = new Vehicle_Tracking_SystemEntities();
var latlon = entities.LatLangs.ToList();
//var latlon = entities.LatLangs.OrderByDescending(x => x.Id).Take(1).ToList();
return Json(latlon, JsonRequestBehavior.AllowGet);
}


So here I wants that my Ajax call is done repeatedly after each 3 seconds automatically to the JsonResult action in controller , and controller get the latest values and send back to the Ajax.

Answer
window.setInterval(function(){
  /// call your ajax function here
}, 3000);
Comments