0

Can i be provided with an example of a scenario whereby i have a Servet as such :

@WebServlet(name = "testservlet", urlPatterns = {"/testservlet"})
public class testservlet extends HttpServlet {    

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

          Data d = new Data();  
          ArrayList infos = d.getData(String ID);  

        }

How can i pass the value for getData method in javascript using ajax and receive the reply by sending back the infos object ? I will appreciate an example in javascript. This should be triggered by an on button click. Please your reply should be like a tutorial

2 Answers2

2

When user enters value to web page, you have to use ajax to transfer that value to java servlet. This is not the exact code but an example,You can have the servlet retrieve data from postVariableName.

Lets say you have a id=1 in javascript file,

var id= document.getElementById(id);

then use ajax:

$.ajax({
    url: 'path/to/testservlet',
    data: {
        postVariableName: id
    },
    type: 'POST'
});​ 

In servlet, you will access the value by:

id = request.getParameter("id")
System.out.print("id is:"+id); //prints 1

See also:

jQuery.ajax() documentation

fscore
  • 2,567
  • 7
  • 40
  • 74
  • Thanks for the reply. Any idea where the return value is stored ? it's in json format. I will like to iterate though the return value. How may i store the return values ? is it in the ajax{ ? –  May 06 '14 at 01:09
  • return value for what? – fscore May 06 '14 at 01:12
0

This is what I have in my mind:

  1. Convert values from getData method to JSON

  2. Put the JSON value in a HTML hidden element.

  3. Use javascript to fetch hidden element's value and send via Ajax.

sendon1982
  • 9,982
  • 61
  • 44