Reputation: 641
I have an index page which displays data about different systems. I need to update this page every 2 seconds. So I call an jQuery ajax to call a method of the controller which sends a partial view of the page with the requested data.
While loading the information, I have a loading gif to user feedback.
The problem I am having is that the ajax call is working(the page is loaded with info) but before entering the controller method the ajax error is first triggered.
Index page
<div align="center" class="loader">
<img src="@Url.Content("~/Images/loader.gif")"/>
</div>
<div id="reportsContent">
</div>
jQuery ajax call
var refreshInterval = @ViewBag.RefreshTime;
setInterval(function () { GetData() }, refreshInterval);
function GetData() {
$.ajax({
type: "POST",
url: '@Url.Content("~/SystemReports/SystemReports")',
//url: '@Url.Action("SystemReports")',
dataType: "text",
data : {},
success: function (data) {
$(".loader").hide();
$('#reportsContent').html(data);
},
error : function() {
alert('error');
}
});
};
As it shows I have tried both @Url.Action and @Url.Content.. I do not know why the alert('error') is first displayed and only after the page is loaded correctly with the needed data.
Controller
[HttpPost]
public PartialViewResult SystemReports()
{
DataService.GetStatusData();
SystemModel model = new SystemModel();
Map(data, model);
return PartialView("_ReportsContent", model);
}
I do not know why the error is triggered and the $.ajax still works. Maybe someone can help me?
Upvotes: 1
Views: 1081
Reputation: 15860
The error is that you cannot use ASP.NET codes in your jQuery ajax API. Replace the URL:
url: '/SystemReports/SystemReports'
This would work now! You need to be using the JavaScript API while sending Ajax request through jQuery, instead of using Server Side Classes such as: Url etc. They won't work in jQuery as their is no reference to them in jQuery Library.
To be more precise about the error, you can use this to know about the actual error:
error: function(xhr, status, error) {
alert(xhr.responseText);
}
This will alert the error that is being thrown, maybe it would be an 404 (Not Found).
Upvotes: 2