Shankara Nethran S.N Shankara Nethran S.N - 1 year ago 76
jQuery Question

How to get the values from JsonObject using jquery and ajax call?

I have an JsonObject which is returned from the spring controller to populate select boxes. But I am not able to load it in Ajax

Here is my Jquery Code

$("#category").click(function(){

$.ajax({
type: "POST",
url: "loadSelectBox",
dataType: 'json',
success: function(data){
$("#category").empty();
var options = '';
for(var i = 0; i <= data.length - 1; i++){
options += "<option value='" + data[i].id + "'>" + data[i].name + "</option>";
}
$("#category").append(options);
$("#category").trigger('chosen:updated');
}
});

})


My controller Code is

@PostMapping(name="loadSelectBox")
public JSONObject getCategoryJsonObj() throws Exception{
System.out.println("loadSelectBox:::::: ");
JSONObject catJsonObj=new JSONObject();
try {
ArrayList<CategoryDTO> catDTOList=globalCatList;
System.out.println("catDTOList::: " +catDTOList);
ArrayList<String> dbList=rawDataProcessService.getCurrentCategoriesInserted(structureID);
System.out.println("dbList:: " +dbList);

System.out.println("catDTOList before removing : " +catDTOList.size());
if(dbList!=null && dbList.size() >0){
for(int db=0;db<dbList.size();db++){
String dbData=dbList.get(db);
for(int cat=0;cat<catDTOList.size();cat++){
CategoryDTO dto=catDTOList.get(cat);
String currentData=dto.getCategory();
if(dbData.trim().equals(currentData)){
catDTOList.remove(cat);
}

}
}
System.out.println("catDTOList after removing : " +catDTOList.size());
for(int cat=0;cat<catDTOList.size();cat++){
CategoryDTO categoryDTO=catDTOList.get(cat);
String categoryValue=categoryDTO.getCategory();
System.out.println("categoryValue: ::" + categoryValue);
catJsonObj.put(categoryValue, categoryValue);
}
System.out.println("catJsonObjLLL " +catJsonObj);
}else{

}
} catch (Exception e) {
throw e;
}
return catJsonObj;

}


JSONObject from the spring controller will be as following Key value pair:

{"MONTH":"MONTH","TYPE OF DATA 5":"TYPE OF DATA 5","TYPE OF DATA 3":"TYPE OF DATA 3","TYPE OF DATA 4":"TYPE OF DATA 4"}


I am not able to load the above jsonObject values into the select box.

Help is appreciated, Thanks

Answer Source

That kind of forloop is used to iterate through array of data.In your case its just an object.So iterate through the object to retrieve key value pair.

Change you for loop like this

for(var key in data){
      options += "<option value='" + key + "'>" + data[key] + "</option>";
}

Thus the js will look like

$("#category").click(function(){

    $.ajax({
        type: "POST",
        url: "loadSelectBox",
        dataType: 'json',
        success: function(data){
            $("#category").empty();
            var options = '';
            for(var key in data){
                options += "<option value='" + key + "'>" + data[key] + "</option>";
            }
            $("#category").append(options);
            $("#category").trigger('chosen:updated'); 
        },
        error: function(response){
            alert("ERROR\n"+response);
            console.log(response);
        },
    });
}) ;

Note: Don not send json with keys with space separator.

In yous sample response "TYPE OF DATA 5" these are not valid json keys.Either separate with underscore("TYPE_OF_DATA_5") or use 'camelCase' notation for referring keys

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download