0

I post some via AJAX in my servet from my jsp

$.ajax({                    
    url: 'myServlet?action=FEP',
    type: 'post',
    data: {machine: i, name: txt}, // i, txt have some values.
    success: function (data) {
        alert('success');
    }
});

and in my Serlvlet

String jspAction = request.getParameter("action");

//...

if(jspAction.equals("FEP")){
    int idMachine = Integer.parseInt(request.getParameter("machine")); 
    String name = request.getParameter("name");
    double value = actions.getValue(idMachine, name); //<-- this variable I want to send it back to the JSP.
}

The data are sent succesfully. However I haven't understand how I send back the vaule to the jsp..

yaylitzis
  • 5,354
  • 17
  • 62
  • 107
  • could you clarify your problem? Which "value" are you referring to? You can access all GET and POST parameters via `request.getParameter("variable")`, take care to use the [right form encoding](http://stackoverflow.com/questions/3831680/httpservletrequest-get-post-data) though – SaschaM78 Dec 15 '15 at 10:54
  • I have defined a variable as `value`. – yaylitzis Dec 15 '15 at 10:56
  • I want the variable `value` to send it back to the JSP. – yaylitzis Dec 15 '15 at 10:57
  • The same way you send any data back to the browser. – Quentin Dec 15 '15 at 10:59
  • I send via session `session.setAttribute("value", value);`. How i will read then this variable from the javascript?? – yaylitzis Dec 15 '15 at 11:01

2 Answers2

0

returning a string would go as follows:

response.getWriter().write("a string");
return null;

If you want to return json, you can use many libraries like: http://www.json.org/

This would result in something like following code:

response.setContentType("application/json");
JSONObject jsonObject = new JSONObject();
double aDouble = 38d;
jsonObject.put("returnValue", aDouble);
response.getWriter().write(jsonObject.toString());
return null;
Tom
  • 4,096
  • 2
  • 24
  • 38
0

Use
response.getWriter().write(value); return null;

And in your ajax success block access the value. See the following link for more understanding http://www.javacodegeeks.com/2014/09/jquery-ajax-servlets-integration-building-a-complete-application.html

Pradeep Kr Kaushal
  • 1,506
  • 1
  • 16
  • 29