1

I am receiving a Java string list from Servlet in json format on my front end. To explain in brief, I wish to populate one select based on selection from another dropbox without page refresh.

i.e. if user selects a category from first select menu, it fires a query in database to select all the parameters related to the category and then populate the other select box. I intend to do this without page refresh.

Below is my java code :

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
 String categoryValue = req.getParameter("bellCategorySel");
 List<String> paramList = insightDbConn.getParametersList(categoryValue);
 String parsedParamList = new Gson().toJson(paramList);
 PrintWriter out= resp.getWriter(); 
 JSONObject json = new JSONObject(); 
 json.put("name", parsedParamList); 
 out.print(json); 
}

I am calling this Java code on "onchange" event of select menu.

Below is my jQuery ajax code :

 $("#bellCategorySel").change(function(e) { 
 $.ajax({
 type : 'POST',
 cache : false,
 data : {
 bellCategorySel : document.getElementById("bellCategorySel").value
 },
 dataType: 'json',
 url : '/AnalysisPanel/gaussianbell',
 success : function(jsonResponse) {
 var name = $.parseJSON(jsonResponse.name);
 var tostr = name.toString();
 var commsep = tostr.split(",");
 alert(commsep);
 }
 });
 e.preventDefault();
 return false;
});
});

Now the problem is I am receiving a string in following format :

["a", "b", "c"]

When I parse it, it becomes :

a,b,c

I am unable to split the string based on comma delimeter so that I can populate the second select menu based on the array I get after comma separation.

I am kind of new to this stuff, so please go easy on me :)

zapping
4,1266 gold badges41 silver badges56 bronze badges
asked Jan 3, 2017 at 5:24
3
  • Array.prototype.map() inside its callback populate your list entries Commented Jan 3, 2017 at 5:28
  • 1
    There is no need to split it again to create an array. That is extra work like array > string > split to array again. Also there is no need to use $.parseJSON as you already have dataType:'json', it automatically does it for you. What you need is just iterate over the array and put the options in the select. Commented Jan 3, 2017 at 5:39
  • exactly, working with the initial array is far simpler Commented Jan 3, 2017 at 5:44

5 Answers 5

1

As i mentioned in the comment that:

  1. You don't need to split the string to produce array again, instead use the response data.
  2. You don't need to parse it again as dataType:"json" automatically does it for you.

Use this way:

success : function(jsonResponse) {
 var arr = jsonResponse.name, // <-----the array ["a", "b", "c"]
 opts = '<option value="0">Please select...</option>'; // <---default option
 $.each(arr, function(key, val){
 opts += '<option value="' + val + '">' + val + '</option>'; //<----generate options
 });
 $('#targetSelectElement').empty().append(opts); //<-----put the options in select element.
}

var arr = ["a", "b", "c"], // <-----the array ["a", "b", "c"]
 opts = '<option value="0">Please select...</option>'; // <---default option
$.each(arr, function(key, val) {
 opts += '<option value="' + val + '">' + val + '</option>'; //<----generate options
});
$('#myselect').empty().append(opts); //<-----put the options in select element.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id='myselect'></select>

answered Jan 3, 2017 at 5:46
Sign up to request clarification or add additional context in comments.

3 Comments

@charlietfl yes i also doubt that so just changed to working one. Thanks for pointing it.
Tried ur solution. Following was the error I got : pastebin.com/fi7wDHBH . Here you see the kind of array I am getting
got it :) just had to parse it once dont know why. thanks btw
0

As you are getting json object, which is having reference to Array you should be able to iterate through array rather than using it as string and do split based on comma

answered Jan 3, 2017 at 5:31

Comments

0

you can also use split to split the string by comma like below :

var array = string.split(',');
answered Jan 3, 2017 at 5:31

1 Comment

as you can see in the above code snippet, I have done that ... but it doesnt work :( It either gives me error on split function or it doesnt work
0

var res = "a,b,c".split(","); 
console.log(res);

answered Jan 3, 2017 at 5:50

Comments

0

Just take the intial array and parse it directly into <option>'s

success : function(data) {
 var $sel = $('#selectID').html($('<option>',{text:'Pick one', value:''}));
 $.each(data.name, function(_, val){
 $sel.append( $('<option>',{text:val, value:val}) ); 
 });
}
answered Jan 3, 2017 at 5:47

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.