-1

All I want to do is send a buttons value from a .jsp file to a servlet which then retrieves values from a database specific to the button value sends values back to the page. So for example...

For example: If the user clicks a button with the value of 1 they should retrieve user 1's data from the database.

I suppose my problem is... How would i go about sending a paramater to a servlet and have the servlet respond with the requested data on the click of a button, without the page refreshing.

2 Answers2

1

You can simply send data along with ajax request and retrieve it from your request object in Servlet.

Step1 - Send button value to javascript function :

<button type="button" value="value1" onclick="loadDoc(this.value)">Get Content</button>

Step2 - Create javacript function to get this value and send it with ajax request:

function loadDoc(data) { 
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
  document.getElementById("demo").innerHTML =
  this.responseText;
}
};
xhttp.open("GET", "http://www.example.com?data1="+data, true);
xhttp.send();
}

Step3 - Use your HttpServletRequest to retrive this data in servlet :

String reqData = request.getParameter("data1");
0

This can be easily done using basic jQuery. In the jsp/html part you just need to define a button with the reuqired value you need to convey to the servlet. For eg:

<button id="toClick" value="1"></button>

Then in the jquery part, you should give a ajax call when this particular button is being clicked. Something like this,

$("#toClick").click(function() {
$.ajax({
    url:"/servlet_goes_here",
    data: {id:$("#toClick").val()}
})
 .done(function(response) {
    alert("do whatever you want to do with the response")
 });
});

The response will be the json response coming from the servlet side. If there is no requirement/ no json response, you can avoid the done block, or use it for testing the ajax call.

Alan Pallath
  • 99
  • 3
  • 14