Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why won't my $.ajax call return a json object from a cshtml file?

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:

  1. I get no server-side error or error code.
  2. I have written the output to a simple .txt file to test the contents, and by pasting it into jsonLint (found here: http://jsonlint.com/) I was easily able to determine that this is, indeed, valid json syntax.
  3. I am still always getting the alert message that runs only under the "error: function()" option of the $.ajax call.
  4. I am getting no white space either before or after the entire jsonString (not that that probably matters).
  5. I am in a WebMatrix, C#, asp.net-webpages environment.
  6. My only two suspicions are 1) The dataType and/or contentType is not set correctly, or 2) The last time I had to use ajax for json (targeting an actual .json file) I had to change a setting in "IIS Express" to allow it to receive data from json files, however, I thought that this was only needed if actually using ajax to parse a json "file" and not just json data. Also, no matter where I look, I can't seem to find this resource anymore.
  7. The textStatus and error parameter values are: textStatus: parsererror error: SyntaxError: Unexpected token & but this doesn't seem to throw any red flags in my mind, because I know that the json syntax by itself checks out okay.

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.

like image 278
VoidKing Avatar asked Oct 22 '22 09:10

VoidKing


1 Answers

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");
});
like image 143
Benjamin Gruenbaum Avatar answered Oct 27 '22 09:10

Benjamin Gruenbaum