I have done a lot of research and cannot find an answer. I want to integrate JSTREE with MVC3.0. Here is my Javascript setup:
setupTree: function (treeDivId) {
$('#' + treeDivId).jstree({
"json_data": {
"ajax": {
url: CustomTree.SectorLoadUrl,
type: "POST",
contentType: "application/json;charset=utf-8",
dataType: "json",
data: function (n) {
return { id: n.attr ? n.attr("id") : "0" };
},
success: function (data, textstatus, xhr) {
alert(data);
},
error: function (xhr, textstatus, errorThrown) {
alert(textstatus);
}
}
},
"themes": {
"theme": "default",
"dots": true,
"icons": false
},
"plugins": ["themes", "json_data"]
});
}
I also get the data correctly as can be seen in the uploaded image:
However, the following lines of code:
data: function (n) {
return { id: n.attr ? n.attr("id") : "0" };
},
Always return a -1 for n.
And I get a parser error on the OnError handler in my textstatus.
I am going to answer this question in the hopes that it helps someone.
I spent a total of 5hrs trying to understand what was going on and finally added a hack.
Using Firebug, I noticed that a callback was being appended to the URL. When the data was returned, the callback was not getting executed. I didn't specify any callbacks, so that was the first item to look into.
Per documentation, turns out that jquery1.5 onwards it will automatically append a callback if it thinks the data type is jsonp. However, I explicitly mentioned 'json' as my data type so I don't understand why it appended that callback.
Here's what the jquery documentation says:
"jsonp": Loads in a JSON block using JSONP. Will add an extra "?callback=?" to the end of your URL to specify the callback.
So this made me wonder what was going on. Also turns out, as of jquery 1.5, you can now specify multiple data types in the AJAX call and jquery will automatically try to convert.
Buried deep within the jquery documentation is this: "As of jQuery 1.5, jQuery can convert a dataType from what it received in the Content-Type header to what you require."
So I just thought it would be better to return the data type as text, then use jquery to convert it to json. The moment I changed my dataType to "text json" instead of just "json", everything magically started working.
My guess is, there's something up with auto-inference on data types with the new jquery. I am on a strict deadline so I cannot research this issue anymore, but if someone finds answers, please do post.
Here is my modified Javascript:
setupTree: function (treeDivId) {
$('#' + treeDivId).jstree({
"json_data": {
"ajax": {
"url" : CustomTree.SectorLoadUrl,
"type" : "POST",
"dataType" : "text json",
"contentType" : "application/json charset=utf-8",
}
},
"themes": {
"theme": "default",
"dots": true,
"icons": false
},
"plugins": ["themes", "json_data"]
});