su star su star - 1 year ago 83
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="" type="text/javascript"></script>

<script type="text/javascript">
var myMarkers = [];
window.onload = function () {
async: false,
type: "POST",
dataType: "json",
url: '@Url.Action("googlemapfindlatlon", "Home")',
data: '{}',
success: function (data) {
$.each(data, function (i, v) {
var mapOptions = {
center: new google.maps.LatLng(myMarkers[0].Latitude, myMarkers[0].Langitude),
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
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);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: data.title
(function (marker, data) {
google.maps.event.addListener(marker, "click", function (e) {
infoWindow.setContent(data.Address);, marker);
})(marker, data);


//init google map


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

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 Source
  /// call your ajax function here
}, 3000);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download