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
- <html>
- <head>
- <script>
- var request;
- function sendInfo()
- {
- var v=document.vinform.t1.value;
- var url="index.jsp?val="+v;
- if(window.XMLHttpRequest){
- request=new XMLHttpRequest();
- }
- else if(window.ActiveXObject){
- request=new ActiveXObject("Microsoft.XMLHTTP");
- }
- try
- {
- request.onreadystatechange=getInfo;
- request.open("GET",url,true);
- request.send();
- }
- catch(e)
- {
- alert("Unable to connect to server");
- }
- }
- function getInfo(){
- if(request.readyState==4){
- var val=request.responseText;
- document.getElementById('amit').innerHTML=val;
- }
- }
- </script>
- </head>
- <body>
- <marquee><h1>This is an example of ajax</h1></marquee>
- <form name="vinform">
- <input type="text" name="t1">
- <input type="button" value="ShowTable" onClick="sendInfo()">
- </form>
- <span id="amit"> </span>
- </body>
- </html>
In this jsp page, we printing the table of given number.index.jsp
- <%
- int n=Integer.parseInt(request.getParameter("val"));
- for(int i=1;i<=10;i++)
- out.print(i*n+"<br>");
- %>
web.xml
- <?xml version="1.0" encoding="UTF-8"?>
- <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
- http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
- <session-config>
- <session-timeout>
- 30
- </session-timeout>
- </session-config>
- <welcome-file-list>
- <welcome-file>table1.html</welcome-file>
- </welcome-file-list>
- </web-app>