I want to create a dynamic select input (dropdown menu) from JSON.
I have tried two approaches to getting a JSON object for a dropdown menu Select input (which I have labeled Attempt 1 and Attempt 2 in the commented out JS).
I have the string returning to the client, however, the front end is not seeing it as a JSON object, but rather just a string. I have tried to parse and serialize it using both the .Net serializer and the Json2 Parse.
AJAX Call
function getcategories(categoryId) {
$.ajax({
type: 'POST',
url: '/Services/Category.aspx/GetCategory',
data: '{"categoryId":"' + categoryId + '"}',
contentType: 'application/json; charset=utf-8',
global: false,
async: false,
dataType: 'json',
success: function (msg) {
if (msg.d == null || msg.d == '') {
//end of the road. not more categories. so don't add another DDL
jsonList = '';
console.log("No more DDLs: ");
} else {
//attempt 1: converting returned data to Json
//var json = JSON.parse(msg.d);//just returns [object object]
//jsonList = json.d;
//attemp2: trying to consume stringbuilder string as Json
//or if I do the below, I also get an error Table does not exist
//jsonList = msg.d
}
}
});
return false;
}
Returned JSON
{
"Table": [{
"categoryid": "0",
"categoryname": "--Select Category1--"
}, {
"categoryid": "2",
"categoryname": "subname2"
}, {
"categoryid": "3",
"categoryname": "subname3"
}, {
"categoryid": "4",
"categoryname": "subname4"
}]
}
Trying to use it in a loop here:
//simplified function inside the ready()
//add dynamic select with options from Json
$('<select id ="DDL' + nextSelect + '" class="cascade"><option value="-">-- Step' + nextSelect + ' --</option></select>').appendTo('div .chooseSteps');
console.log("Obj " + categoryJson); //shows the Json string
console.log("TABLE " + categoryJson.Table); //returns undefined :(
var listItems = "";
//Says that Table does not exist (undefined)
for (var i = 0; i < categoryJson.Table.length; i++) {
listItems += "<option value='" + categoryJson.Table[i].categoryid + "'>" + categoryJson.Table[i].categoryname + "</option>";
}
So my goal is to get the options to display and get the values of Table.
I searched the forum all afternoon, and could not find a solution that worked, and this is driving me crazy. Thanks for your understanding.
I am using jQuery 1.7.1 AJAX with Json2.js (as a backup for older browsers) with Asp.Net 4.
Your response doesn’t have a
dproperty.Don’t try to parse it. jQuery does that.
Just do this:
Although I don’t see where you’re transitioning from the AJAX call to the code at the bottom, so I’m not sure what’s happening in between.
These suggest the JSON isn’t parsed:
So right here you would need to
$.parseJSONit. Again, I see no relationship between the two code examples.