Return values from arraylist to an ajax success function
ajax, arraylist, jquery, jsp, servlets
Solution
Thank you for all the responses.
I finally found a solution to my own question. hope it will be useful for someone else.
I did the following code.
$.ajax({
url:'Servleturl?dataID='document.getElementById("#data_id").value;
type:'GET',
dataType:'json',
success:function(data) {
document.getElementById("#lat").value=data[0].Lat;
document.getElementById("#longi").value=data[0].Longi;
}
});
As the data is returned from a arraylist should give the data as array itself to retrieve the values..
Thank you all for the answers.
Problem
Retrieve data from an arraylist in the ajax success function. I need to populate my textfields latitude and longitude fields based on the ID passed via ajax. Everything works fine but the data is not rendered to the text fields. The success function returns nothing if the below code is executed. What is wroong in my code? FetchData.class ``` public static ArrayList<Info> getAllInfo(String data_id) { connection = FetchData.getConnection(); ArrayList<Info> inf = new ArrayList<Info>(); try { Statement statement = connection.createStatement(); ResultSet rs = statement.executeQuery("select * from info_table where data_id='"+data_id"'"); while(rs.next()) { Info in=new Info(); in.setData_id(rs.getString("data_id")); in.setLat(rs.getDouble("Lat")); in.setLongi(rs.getDouble("Longi")); inf.add(in); } } catch (SQLException e) { e.printStackTrace(); } return inf; } } ``` Servlet class ``` protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String dataID=request.getParameter("data_id"); ArrayList<Info> in=new ArrayList<Info>(); in=FetchData.getAllInfo(); Gson gson = new Gson(); JsonElement element = gson.toJsonTree(in, new TypeToken<List<Info>>() {}.getType()); JsonArray jsonArray = element.getAsJsonArray(); response.setContentType("application/json"); response.getWriter().print(jsonArray); } ``` my ajax ``` $.ajax({ url:'Servleturl?dataID='document.getElementById("#data_id").value; type:'GET', dataType:'json', success:function(data){ $("#lat").val(data.Lat); $("#longi").val(data.Longi); } }); }); ``` index.jsp ``` <input type="text" id="data_id" onblur=""/> <input type="text" id="lat"/> <input type="text" id="longi"/> ```