Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery JsTree and JSON error handling

I am using MVC to pass JSON data to JsTree and show a hierarchical view of information. Everything is working just fine, however, there are times when the user does not have access the the data or for some reason the MVC action throws an exception:

In these cases, the action passes a JSON error message and sets the HttpStatusCode to NotAccepted or InternalServerError.

However the jsTree's sinner keeps spinning and I don't seem to find a way to make it stop and show the error message.

Has anyone solved this issue before? How can one does error handling when using JsTree's JSON data plugin?

UPDATE:

I figured out how to capture the error:

 $("#jstree1").jstree({
       "json_data": {
           "ajax": {
               "url": serviceUrl,
               "data": function (n) {
                       return { pid: n.attr ? n.attr("id") : "" };
               },
               "error": function (x, s, r) { var err = $.parseJSON(x.responseText); if (err!="") { alert(err); } }
           }
    }

It seems that JsTree does get the MVC http statusCode and the error, now I need to figure out how to tell the JsTree to stop waiting and remove the spinner image!

I am also looking for a good way of showing the error in JsTree, or should I manage the error message outside of it?

like image 506
sam360 Avatar asked Dec 01 '11 02:12

sam360


1 Answers

I've solved this problem.

Just a note- the code example above for handling ajax call errors is incorrect, please see a complete example below:

        $('#YourTree').jstree({
        "json_data": {
            "ajax": {
                "url": "/Controller/Action",
                "data": function () {
                    return { Parameter1: "Value1", Parameter2: "Value2" }
                },
                "type": "POST",
                "dataType": "json",
                "error": function (jqXHR, textStatus, errorThrown) { $('#YourTree').html("<h3>There was an error while loading data for this tree</h3><p>" + jqXHR.responseText + "</p>"); }
            }
        }
    });

And in the actual action, you need to set the http response status code to 1 and write the error. e.g.

Response.StatusCode = 1
Response.Write("Error you want to go into jqXHR.responseText here");

Enjoy :)

like image 148
Tom Beech Avatar answered Nov 20 '22 21:11

Tom Beech