I have this jquery that uses ajax in an attempt to return a json object, but I am no pro at ajax, though I have used it before with json, only I was loading a json file and not trying to return a string from a cshtml page that queries a database for information (as I am doing here).
Here is the jQuery:
$.ajax({
url: "/AJAX Pages/Compute_Calendar_Events.cshtml",
async: true,
type: "GET",
dataType: "json",
contentType: "application/json",
success: function (jsonObj) {
console.log("AJAX SUCCESS!");
},
error: function (jqXHR, textStatus, error) {
alert("NO AJAX!");
}
});
(Also I have tried "application/json; charset=UTF-8" as the contentType, but it changes no behavior).
Here is the cshtml page that I point AJAX to:
@{
Layout = "";
if(IsAjax || 1==1)
{
string jsonString = "{\"events\":[";
string selectQueryString = "SELECT title, summary, eventDate FROM CalendarEvents ORDER BY eventDate ASC";
var db = Database.Open("Content");
foreach (var row in db.Query(selectQueryString))
{
jsonString += "{";
jsonString += "\"title\":" + Json.Encode(row.title) + ",";
jsonString += "\"dateNumber\":" + Json.Encode(row.eventDate.ToString().Substring(0, row.eventDate.ToString().IndexOf("/"))) + ",";
jsonString += "\"dateMonth\":" + Json.Encode(row.eventDate.ToString().Substring(row.eventDate.ToString().IndexOf("/") + 1, row.eventDate.ToString().LastIndexOf("/") - (row.eventDate.ToString().IndexOf("/") + 1))) + ",";
jsonString += "\"dateYear\":" + Json.Encode(row.eventDate.ToString().Substring(row.eventDate.ToString().LastIndexOf("/") + 1, 4)) + ",";
jsonString += "\"summary\":" + Json.Encode(row.summary);
jsonString += "},";
}
jsonString = jsonString.TrimEnd(',');
jsonString += "]}";
/*System.IO.File.Delete(Server.MapPath("~/TEST.txt"));
var outputFile = System.IO.File.AppendText(Server.MapPath("~/TEST.txt"));
outputFile.Write(jsonString);
outputFile.Close();*/
@* *@@jsonString
}
else
{
Response.Redirect("~/");
}
}
It is very important to note a couple of things:
Thanks to everyone for all of your help. I believe I have found the issue (the unexpected ampersand token finally made a light bulb go on in my head). I have added the answer to this page, in the event that it may help someone else in the future.
I've had a similar issue,
I've solved it by heading a header in the top of the .cshtml
file in WebMatrix
@{
Response.AddHeader("Content-Type","application/json");
}
Another thing to check is that your JSON passes validation. Copy-Paste your JSON result in a JSON validator and make sure it passes. (You already did that, I'd like future readers of this question to see this).
Here is sample code you can grab your JSON with
$.getJSON("/AJAX Pages/Compute_Calendar_Events.cshtml").done(function(result){
alert("Success!");
console.log(result);
}).fail(function(){
alert("Error loading");
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With