Ankur Chachra
Ankur Chachra

Reputation: 131

JSP not receiving AJAX response from Servlet

I have a simple jsp page that sends an ajax request to a servlet and awaits a response. Unfortunately, it's not receiving the response after many attempts. The ajax requests are being transmitted but response isn't being received.

As of now, I have a dropdown in my page and a textbox. I am trying to get the value selected in the dropdown to be printed in the textbox on the dropdown's "onchange" event. Here's my code. Any help regarding this would be very welcome.

JSP PAGE

 <script>            
 function ajaxrequest(){ return new XMLHttpRequest();}        
 function ac()
   {
     var myajaxrequest = new ajaxrequest();
     if(myajaxrequest==null){alert("AJAX NOT WORKING");}         
     else
       {
         alert("AJAX WORKING");                 
         var ind2=document.getElementById("dd1").value;
         myajaxrequest.onreadystatechange=connection;                   
         myajaxrequest.open("GET", "../ajaxservlet?dd1="+ind2,true );
         myajaxrequest.send(null);
       }
    }

 function connection()  
   {               
     if(myajaxrequest.readyState==4)  
        {  
          var x=myajaxrequest.responseText; 
          document.getElementById("result").innerHTML = x;
        }  
   }  
 </script>
 <body>
   <form id = "form1" name ="form1" >
      <select id="dd1" name="dd1" onchange= "ac()">
        <option>Please select </option>
        <option>ankur</option>
        <option>akshay</option>
      </select>
      <input type="text" id="result" name="result" /> 
   </form>
 </body>

SERVLET :

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

  System.out.println("hitting servlet");
  String abc = request.getParameter("dd1");
  System.out.println(abc);
  PrintWriter pw=response.getWriter();  
  response.setContentType("text/html");  
  pw.println(abc);
  }

The values selected in the dropdown are getting printed in the console but aren't being transmitted back. Thanks for your time.

Upvotes: 0

Views: 454

Answers (2)

Sid
Sid

Reputation: 371

Try initializing myajaxrequest globally.

Upvotes: 0

c.P.u1
c.P.u1

Reputation: 17094

myajaxrequest is local to the ac() function since you've used the var keyword. You cannot access it in the connection() function.

Try declaring your connection() function within ac() itself.

Instead of checking the status of readyState, using XHR level 2, you can simply attach a handler to the onload event.

BTW, if native XHR isn't supported ajaxrequest() will throw an error; it won't return null.

Upvotes: 1

Related Questions