Thursday 31 March 2016

Example For AJAX


EXAMPLE For AJAX :

  • To create ajax example, you need to use any server-side language e.g. servlet, jsp, php, asp.net etc. Here we are using JSP for generating the server-side code.
  • In this example, we are simply printing the table of the given number.
  • Steps to create ajax example with jsp
  • You need to follow following steps:
  • load the org.json.jar file
  • create input page to receive any text or number
  • create server side page to process the request
  • provide entry in web.xml file
  • Load the org.json.jar file
  • create input page to receive any text or number
  • In this page, we have created a form that gets input from the user. When user clicks on the showTable button, sendInfo()function is called. We have written all the ajax code inside this function.
  • We have called the getInfo() function whenever ready state changes. It writes the returned data in the web page dynamically by the help of innerHTML property.table1.html

  1. <html> 
  2. <head> 
  3. <script> 
  4. var request; 
  5. function sendInfo() 
  6. var v=document.vinform.t1.value; 
  7. var url="index.jsp?val="+v; 

  8. if(window.XMLHttpRequest){ 
  9. request=new XMLHttpRequest(); 
  10. else if(window.ActiveXObject){ 
  11. request=new ActiveXObject("Microsoft.XMLHTTP"); 
  12. try 
  13. request.onreadystatechange=getInfo; 
  14. request.open("GET",url,true); 
  15. request.send(); 
  16. catch(e) 
  17. alert("Unable to connect to server"); 
  18. function getInfo(){ 
  19. if(request.readyState==4){ 
  20. var val=request.responseText; 
  21. document.getElementById('amit').innerHTML=val; 
  22. </script> 
  23. </head> 
  24. <body> 
  25. <marquee><h1>This is an example of ajax</h1></marquee> 
  26. <form name="vinform"> 
  27. <input type="text" name="t1"> 
  28. <input type="button" value="ShowTable" onClick="sendInfo()"> 
  29. </form> 
  30. <span id="amit"> </span> 
  31. </body> 
  32. </html> 
create server side page to process the request

In this jsp page, we printing the table of given number.index.jsp


  1. <% 
  2. int n=Integer.parseInt(request.getParameter("val")); 
  3. for(int i=1;i<=10;i++) 
  4. out.print(i*n+"<br>"); 
  5. %> 

web.xml


  1. <?xml version="1.0" encoding="UTF-8"?> 
  2. <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" 
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
  4. xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
  5. http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> 
  6. <session-config> 
  7. <session-timeout> 
  8. 30 
  9. </session-timeout> 
  10. </session-config> 
  11. <welcome-file-list> 
  12. <welcome-file>table1.html</welcome-file> 
  13. </welcome-file-list> 
  14. </web-app> 

Output