Ariel Nitzan Ariel Nitzan - 4 months ago 6
JSON Question

Why is AJAX JSON response failing despite 200 OK status?

I am working on a basic ASP.NET & AJAX/JSON assignment and I am frustrated with making it work. One of the requirements was to create an AJAX/JSON method to do some manipulations on SQL DB data.

In order to complete that, I used the following code:

In the aspx:

type: "GET",
dataType: "json",
url: "Retrieve",
success: function (data) {
var col;
for (col in data) {
addRow(data[col].id, data[col].Name, data[col].catagory, data[col].difficulty, data[col].company, data[col].price, '#products');
error: function () {


In the "retrieve.aspx" page (the part of code that creates the data for JSON):

Response.ContentType = "application/json; charset=utf-8";
bool val1 = (System.Web.HttpContext.Current.User != null) && System.Web.HttpContext.Current.User.Identity.IsAuthenticated;
string category = Request.QueryString["category"];
//string a = JsonConvert.SerializeObject(getProducts(category));
var a = getProducts(category);
// instantiate a serializer
JavaScriptSerializer TheSerializer = new JavaScriptSerializer();

var TheJson = TheSerializer.Serialize(a);

And last but not least, if i try to change the dataType to text, it will show that the content is the JSON-structured text together with an HTML page code.

What am I missing here?


You need to make sure ASP.NET does not render anything else outside of the json content you put into the response. To do so, clear the response beforehand:

Response.ContentType = "application/json; charset=utf-8";

and in the end complete the response right away:


See this excellent answer as to why CompleteRequest should be used here instead of more widespread Request.End().

However using pages to output JSON seems like an overhead. You may want to checkout simpler ways of doing the same, which is Http Handlers. Plenty examples over the internet, here is one