I'm newbie on servlet and I need to get data from database to display chart
$.ajax({
url : "NameServlet",
dataType : 'json',
error : function(){
alert("Error Occured");
},
success : function(data) {
var receivedData = [];
//how to put data in var (i.e. receivedData) which is received from servlet
}
});
what would be my servlet to get data
Calling a servlet method explicitly inside a javascript function is usually done through AJAX. Following are the different ways to make AJAX requests through jQuery: $. get(URL,data,function(data,status,xhr),dataType): this method loads data from the server through HTTP GET request.
You can in the servlet distinguish between normal requests and Ajax requests as below: @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String foo = request. getParameter("foo"); String bar = request.
You cannot call the method directly. You should map an URL to the method you want to call. This can be done in a servlet. If you're already serving pages through your Java code, you just add a new method to serve a page with the content you want.
How AJAX Calls Work. AJAX uses both a browser built-in XMLHttpRequest object to get data from the web server and JavaScript and HTML DOM to display that content to the user. Despite the name “AJAX” these calls can also transport data as plain text or JSON instead of XML.
so here is the answer
you jquery to push data to your variable
$.ajax({
url : "NameServlet",
dataType : 'json',
error : function() {
alert("Error Occured");
},
success : function(data) {
var receivedData = [];
$.each(data.jsonArray, function(index) {
$.each(data.jsonArray[index], function(key, value) {
var point = [];
point.push(key);
point.push(value);
receivedData.push(point);
});
});
}
});
after this you need servlet to get JSON object
Servlet would be like
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class NameServlet extends HttpServlet {
int []sampleData=null;
//sampleData= here you can get data from database
//writing data to json
response.setContentType("application/json;charset=utf-8");
JSONObject json = new JSONObject();
JSONArray array = new JSONArray();
JSONObject member = new JSONObject();
member.put("arrayData", sampleData);
array.add(member);
json.put("jsonArray", array);
PrintWriter pw = response.getWriter();
pw.print(json.toString());
pw.close();
}
Hope this helps
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With