0

I'm new to jsp and ajax.

How to pass multiple variables to servlet using xmlhttp.open("GET",servlet,false); from ajax in jsp.

I have two Select boxes like name and a phone no, I need to send that selected values to servlet, in servlet I pass address,city like multiple details to the jsp using ajax.

Cinthiyal
  • 3
  • 1
  • 4

2 Answers2

1
jQuery.ajax({
        url : "<portlet:resourceURL id='URL'/>",
        data : {
            "A":value,
            "B":Value
        },type : "POST",
        dataType : "json",
        success : function(data) {
        }
Khusboo
  • 117
  • 1
  • 1
  • 9
0

If you want to use GET, you can pass the variables by URL encode it and add them to the url request, like this :

var url = "/path/to/myservlet";
var params = "somevariable=somevalue&anothervariable=anothervalue";
var http = new XMLHttpRequest();

http.open("GET", url+"?"+params, true);
http.onreadystatechange = function()
{
    if(http.readyState == 4 && http.status == 200) {
        alert(http.responseText);
    }
}
http.send(null);

If you have long datas to pass, using POST is the preferred way, here is an example of such code :

var http = new XMLHttpRequest();
var url = "/path/to/myservlet";
var params = "lorem=ipsum&name=binny";
http.open("POST", url, true);

//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

http.onreadystatechange = function() {//Call a function when the state changes.
  if(http.readyState == 4 && http.status == 200) {
      alert(http.responseText);
  }
}
http.send(params);

You will be able to read those datas in your servlet HttpServletRequest using the getParameter(String name) method.

Hope this helps. :-)

Simon Oualid
  • 365
  • 2
  • 9
  • thanks for ur reply (xmlhttp.open("GET","ClientDetails"+ "?client=" + documnt.getElementById("client").value+ "&contact=" + documnt.getElementById("contact").value, false); xmlhttp.send(); if (xmlhttp.readyState == 4) { if (xmlhttp.status == 200) { alert(xmlhttp.responseText); document.getElementById("address").value =xmlhttp.responseText; document.getElementById("city").value=xmlhttp.responseText; } This is my script please check is it right or wrong – Cinthiyal Nov 15 '16 at 07:31