Search code examples
c#jqueryajaxjsonashx

JSON data unable to properly serialize in jQuery


I've been playing with the recently released jQueryGannt plugin / application from here and I'm attempting to write a drop down that is populated with the names of the different stored gantt charts on the server. To generate this drop down I use this function:

$.ajax({
    url: "GanttLoader.ashx?action=getGantts",
    context: document.body, 
    type: "GET",
    dataType: "json",
    success: function(data) {
        if(data.gantts != null) {
            for(var gantt in data.gantts) {
                alert(gantt.name + " is locked " + gantt.locked);
                var toAppend = $("<option/>").val(gantt.name).html(gantt.name);
                if(gantt.locked) { toAppend.attr("disabled", "disabled"); }
                $("#saved_gantts").append(toAppend);
            }
            $("#saved_gantts").append($("<option/>").val("add new").html("add new"));
                saved_gantts_loaded = true;
            }
            else if(data.status == "none") {
                $("#saved_gantts").append($("<option/>").val("add new").html("add new"));
            }
        },
        error: function() { alert("couldn't load gantt charts"); }
});

At the moment, this is what the server is sending to generate the drop down (no gantt data is being sent yet, just a simple list of what gantts are open and which are currently being edited):

{
  "gantts": [
    {
      "name": "other",
      "locked": true
    },
    {
      "name": "test",
      "locked": true
    }
  ]
}

For some reason in the success function's call the for loop loops over both objects stored in the array, but the alert always prints "undefined is locked undefined". Does anybody know what's wrong with my handler or my JSON being returned?

Thanks in advance.


Solution

  • You should use data.gantts[gantt].name instead of gantt.name.

    Here is updated code:

    $.ajax({
        url: "GanttLoader.ashx?action=getGantts",
        context: document.body, 
        type: "GET",
        dataType: "json",
        success: function(data) {
            if(data.gantts != null) {
                var gantts = data.gantts;
                for(var i in gantts) {
                    alert(gantts[i].name + " is locked " + gantts[i].locked);
                    var toAppend = $("<option/>").val(gantts[i].name).html(gantts[i].name);
                    if(gantts[i].locked) { toAppend.attr("disabled", "disabled"); }
                    $("#saved_gantts").append(toAppend);
                }
                $("#saved_gantts").append($("<option/>").val("add new").html("add new"));
                    saved_gantts_loaded = true;
                }
                else if(data.status == "none") {
                    $("#saved_gantts").append($("<option/>").val("add new").html("add new"));
                }
            },
            error: function() { alert("couldn't load gantt charts"); }
    });