Vikas Reddy
Vikas Reddy

Reputation: 45

how to call servlet from javascript using ajax

I am doing a samall jsp page to search a name enter in text box .. i called javascript function from jsp .. the bello is javascript code

function fncStudsearch()
{
//alert("yes")
var ele=document.getElementById("stdSearch").value;
var xmlhttp;
var strAjUrlData="stdSearch?key="+ele;
//alert(strAjUrlData)
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
     xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
 }
 xmlhttp.onreadystatechange=function()
 {
 if (xmlhttp.readyState==4 && xmlhttp.status==200)
{

}
  else
  {
  alet(xmlhttp.status);
  }
 }
  xmlhttp.open("GET",strAjUrlData,true);
      xmlhttp.send();

  }

I am calling servlet .. and i configured web.xml as follows

   <servlet>  
      <servlet-name>stdSearch</servlet-name>
       <servlet-class>com.slokam.Act.StudentSearch</servlet-class>
  </servlet>

<servlet-mapping>
     <servlet-name>stdSearch</servlet-name>
     <url-pattern>/stdSearch</url-pattern>
</servlet-mapping>

</web-app>


I am unable ti go to servlet class and servlet code i have written is

   public class StudentSearch extends HttpServlet {


   private static final long serialVersionUID = 1L;

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub

    String stdkey=request.getParameter("key");
    stdkey="%"+stdkey+"%" ;
    System.out.println(stdkey);
  }
}

please help in this regard how to goto servlet

Upvotes: 0

Views: 10665

Answers (2)

user2575725
user2575725

Reputation:

Possibly this might help, there is an javascript error:

alet(xmlhttp.status); // you're missing here `r`

alert(xmlhttp.status);

Secondly, you have to print out some contents from servlet, use PrintWriter for that.

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String stdkey=request.getParameter("key");
    stdkey="%"+stdkey+"%" ;
    // test purpose
    PrintWriter pw = response.getWriter ();
    pw.print(stdkey);
    pw.close();
}

Upvotes: 0

Si Kelly
Si Kelly

Reputation: 703

If the app is not deployed as the root application on the appserver, you might need the context path in the url you are calling:

var ctx = "${pageContext.request.contextPath}/";
var strAjUrlData=ctx+"stdSearch?key="+ele;

...

This code assumes you are using jsp 2.0 and EL

Upvotes: 1

Related Questions