Haran Murthy
Haran Murthy

Reputation: 341

Send data from js to servlet and get back the response

I am a newbit to ajax and js.

I have a simple jsp page with a html in it. I have an accompanying javascript file where I have defined all my functions. I have one such function to send some json data to servlet. I require help on retrieving back the response from servlet into the calling js file only.

I have the servlet up and running with post method as it receives the ajax call.

Assume js file name is: First.js and servlet is FirstServlet.java

Javascript part to send the data from js to servlet:

    var fullpath="contextpath/FirstServlet";

    //Sending the tradedata using ajax to the FirstServlet
    $.ajax({
        dataType: 'json',
        url: fullpath,
        type: 'POST',
        data: {jsonText:jsonText}

  });

On the servlet side I do some modifications to the data and build a dynamic html The output of the servlet will be something like this added to a string variable.

 <div>
   <table>
     <tbody>
        <tr>
           <td>
            <input name="hi" value="hello" />
            </td>
           <td>
            <input name="bye" value="goodbye" />
            </td>
        </tr>
     </tbody>
   </table>
  </div>

I want to return this tag back to the same javascript file that called it //Need solution for this part.

End goal: I then want to append it to a div tag I have on the jsp file //I will use jquery to add this. This way I can refresh the div container without using iframe.

Upvotes: 1

Views: 7707

Answers (1)

laker
laker

Reputation: 599

If you are using a Java Servlet, you need to build a custom HttpServlet, which must implement the functions doGet(HttpServletRequest req, HttpServletResponse resp) and doPost(HttpRequest req, HttpResponse resp). Once you map a specific domain name (contextpath/FirstServlet in your example) to your custom servlet class (in your web.xml file), the servlet will automatically route any get or post requests to your doGet or doPost functions.

Then you can use the functions available for HttpServletRequest (reference) to handle the data received. Then you place whatever you want to send back to the client into HttpServletResponse (see example link below), and the servlet automatically sends the HttpServletResponse back to the client.

In order to receive the response data from the client-side, you just need to add a callback function (that accepts two arguments, see reference here) as the last argument of your ajax request, like so:

$.ajax({
    dataType: 'json',
    url: fullpath,
    type: 'POST',
    data: {jsonText:jsonText}

}, function(responseData, textStatus) {
    console.log(responseData);
    //do something with responseData
});

Here's a simple example servlet

Upvotes: 1

Related Questions