Naren Naren - 1 month ago 7
jQuery Question

array list format error using $.ajax post in jQuery

My web API accepts below JSON format (this is input parameter)

{
"districtID": "string",
"legendIDs": ["string","string"]
}


I am building request below in javascript.

var cityDistrictId = 'fb7b7ecd-f8df-4591-89de-0c9ddcd217ef'

var legendIds = ''

for (i = 0; i < list.get_items().get_count() ; i++)
{

legendIds += """" + list.getItem(i).get_value() + """" + ",";
}

legendIds = legendIds.substring(0, legendIds.length - 1);

legendIds = '[' + legendIds + ']';

var atrDistrictLegend = { districtID: cityDistrictId, legendIDs: legendIds };

var test = JSON.stringify(atrDistrictLegend);


test variable ouput is:


{"districtID":"fb7b7ecd-f8df-4591-89de-
0c9ddcd217ef","legendIDs":"[\"00D18EECC4A1BBA42E00011202\",\"00D18EECC4A1A6814C00011202\"]"}


getting error message:


{"legendIDs":["The input was not valid."]}


If I build the request statically like below it is working

var cityDistrictId = 'fb7b7ecd-f8df-4591-89de-0c9ddcd217ef'
var legendIds = ['00D18EECC4A1B4DBC000011202','00D18EECC4A1CCB9B400011202']
var atrDistrictLegend = { districtID: cityDistrictId, legendIDs: legendIds };
var test = JSON.stringify(atrDistrictLegend);


test variable ouput is:


{"districtID":"fb7b7ecd-f8df-4591-89de-0c9ddcd217ef","legendIDs":["00D18EECC4A1B4DBC000011202","00D18EECC4A1CCB9B400011202"]}


Please help me on this how to fix this simple issue

Answer

Instead of this:

var legendIds = ''

for (i = 0; i < list.get_items().get_count(); i++) {
    legendIds += """" + list.getItem(i).get_value() + """" + ",";
}

legendIds = legendIds.substring(0, legendIds.length - 1);

legendIds = '[' + legendIds + ']';

Try this:

var legendIds = [];

for (var i = 0; i < list.get_items().get_count(); i++) {
    legendIDs.push(list.getItem(i).get_value());
}

You were building up a string instead of an array.