I have an Ajax request:
$.ajax({ url: "MyPage.aspx",
data: params,
success: function(data) {
// Check results
$('#testp').append(data.message);
enableForm();
},
error: function() {
alert('Unable to load the permissions for this user level.\n\nYour login may have expired.');
enableForm();
},
dataType: "json"
});
On the request page there is C# code that does this at the end of Page_Load:
Response.AppendHeader("X-JSON", result);
‘result’ is formatted like this:
{ "success": true, "message": "SUCCESS", "user_level": 25, "switches": [ { "number": 30, "is_enabled": false, "is_default": false }, { "number": 30, "is_enabled": false, "is_default": false } ]}
The request returns successfully, but ‘data’ is null. What am I missing?
Thanks.
Your main problem seems to be that you’re returning the JSON data in an HTTP header instead of as the content of the response. You probably want to do something like this:
That might fix your immediate problem, but I would strongly recommend that you avoid the approach of using an ASPX page’s direct ouput. There’s a lot of unnecessary overhead involved in getting to the point of Page_Load, when all you really want is a simple JSON endpoint. Not to mention, manually handling the JSON serialization isn’t necessary.
If you’re building that JSON string from an object on the server-side, you can use an ASP.NET AJAX “Page Method” to return that directly and let the framework handle serialization. Like this:
You’ll have to fit that to your own server-side data structures, but hopefully you get the idea. If you already have existing classes that you can populate with the data you need, you can use those instead of creating new ones for the transfer.
To call an ASP.NET AJAX Page Method with jQuery, you need to specify a couple extra parameters on the $.ajax() call:
Regarding the data parameter, here is info on it needing to be a string: http://encosia.com/2010/05/31/asmx-scriptservice-mistake-invalid-json-primitive/
Also, here is more on using the JSON.stringify() approach: http://encosia.com/2009/04/07/using-complex-types-to-make-calling-services-less-complex/
The .d issue is one that can be confusing at first. Basically, the JSON will come back like this instead of how you might expect:
It’s easy to account for once you expect it. It makes your endpoint more secure by mitigating against a fairly treacherous client-side exploit when the top level container is an array. Not applicable in this specific case, but nice to have as a rule. You read more about that here: http://encosia.com/2009/02/10/a-breaking-change-between-versions-of-aspnet-ajax/