JaiswalTraining

Get the online training



Corejava Servlet Jsp  Php  Hibernate  Ajax Web Service   Ejb2.1 Ejb3.0 Struts Struts2  JPA Spring Ibatis   JSF    JSF2.0  CoreJavaDesignPattern    Jquery  Flex J2EE-Design-Patterns  Jboss7  Maven  Contact Me                                                                                                                                                                        
            IGNOU SMU PTU Project                                           Training                                                                                                                              
              

Contact Us  0091- 9210721663         jaiswaltraining@gmail.com




Corejava
Servlet
Jsp
Php
Hibernate
Ajax
Web Service
Ejb2.1
Ejb3.0
Struts  
Struts2
JPA
Spring
Ibatis
JSF
JSF2.0
CoreJavaDesignPattern
Jquery
Flex
J2EE-Design-Patterns
Jboss7
Maven








 

AJAX Intro and Overview

What is AJAX

  • Asynchronous Java Script And XML.
  • AJAX is not a new programming language
  • AJAX is based on the following web standards:
    • JavaScript
    • XML
    • HTML
    • CSS
    • DOM

Features
  • It is a technique for creating better, faster, and more interactive web applications.
  • With AJAX, your JavaScript can communicate directly with the server.
  • It uses the JavaScript XMLHttpRequest object from communication.
  • With this object, your JavaScript can trade data with a web server,
    without reloading the page.
  • AJAX uses asynchronous data transfer (HTTP requests) between the browser
    and the web server.
  • It allows web pages to request small bits of information from the server
    instead of whole pages.
  • It makes Internet applications smaller, faster and more user-friendly.
  • AJAX is Based on Web Standards
  • AJAX applications are browser and platform independent.
Advantages
  • Connection between client side script and server side script.
  • Better user experience
  • More flexibility
  • More options

How does Ajax work?

  • Browser-based presentation using HTML and Cascading Style Sheets.
  • Data stored in XML format and fetched from the server
  • Behind-the-scenes data fetches using XMLHttpRequest objects in the browser
  • JavaScript to make everything happen
  • A client script asynchronously calls a server side function.
  • AJAX Uses HTTP Requests
  • With AJAX, your JavaScript communicates directly with the server,
  • Through the JavaScript XMLHttpRequest object
  • With an HTTP request, a web page can make a request to, and
    get a response from a web server - without reloading the page.
  • The user will stay on the same page, and he or she will not notice that
     scripts request pages, or send data to a server in the background.

  • The XMLHttpRequest Object
  • By using the XMLHttpRequest object, you can update a page with data
  • from the server after the page has loaded!
  • AJAX was made popular in 2005 by Google (with Google Suggest).

Interaction with the Server.
  • XMLHTTPRequest object
  • Allows for asynchronous GETs + POSTs to the server
  • Does not show the user anything—no status messages
  • Can have multiple XMLHTTPRequest active at one time
  • Allows you to specify a handler method for state changes
  • Handler notified when request is:
  • Initialized
  • Started
  • In the process of being returned
  • Completely finished
  • Originally only available for Microsoft IE
  • XMLHttpRequest Object: Methods
    • open(“method”, “URL”)
    • open(“method”, “URL”, async, username, password)
      • Assigns destination URL, method, etc.
    • send(content)
      • Sends request including postable string or DOM object data
    • abort()
      • Terminates current request
    • getAllResponseHeaders()
      • Returns headers (labels + values) as a string
    • getResponseHeader(“header”)
      • Returns value of a given header
    • setRequestHeader(“label”,”value”)
      • Sets Request Headers before sending
Basic AJAX Process

Step:

JavaScript
  • Define an object for sending HTTP requests
  • Initiate request
    • Get request object
    • Designate a request handler function
    • Supply as onreadystatechange attribute of request
    • Initiate a GET or POST request
    • Send data
Handle response
  • Wait for readyState of 4 and HTTP status of 200
  • Extract return text with responseText or responseXML
  • Do something with result
HTML
  • Loads JavaScript
  • Designates control that initiates request
  • Gives ids to input elements that will be read by script

Defining  Object

var request;
function getRequestObject() 
{
if  (window.ActiveXObject) {
return (new  ActiveXObject("Microsoft.XMLHTTP"));
else if  (window.XMLHttpRequest) {
return (new  XMLHttpRequest());
else  {
return (null );
}
}


Initiating Request

function sendRequest() {
request = getRequestObject();
request.onreadystatechange = handleResponse;
request.open("GET""message-data.html"true );
request.send(null );
}


Handling Response

function handleResponse() 
{
if  (request.readyState == 4) {
alert(request.responseText);
}
}

Ajax Example In Eclipse

   This is the simple example of the  ajax.
   It is using the javascript file, then retriveves the ajax value by reading the file. 
  • First create a new Dynamic Web project
  • Name it as Ajax1
  • Set server as Tomcat.

index.html

  • Inside the WebContent create one html file.
  • Save it as index.html
  • Add the code as given below.

HTML Code


<html>
<head>
<script src="show-message.js"
type="text/javascript"></script>
</head>

<body>
<big>Ajax: Simple Message</big>


<form action="#">
<input type="button" value="Show Message"
onclick="sendRequest()"/>

</form>

</body></html>

javascript file

  • navigate to WebContent
  • Now create one javascript file.
  • Save it as show-message.js.
  • Addd the code as shown below.

Complete Java script code(show-message.js)

var request;
function getRequestObject() {
if  (window.ActiveXObject) {
return (new  ActiveXObject("Microsoft.XMLHTTP"));
else if  (window.XMLHttpRequest) {
return (new  XMLHttpRequest());
else  {
return (null );
}
}
function sendRequest() {
request = getRequestObject();
request.onreadystatechange = handleResponse;
request.open("GET""message-data.html"true );
request.send(null );
}
function handleResponse() {
if  (request.readyState == 4) {
alert(request.responseText);
}
}


message-data.html

  • Create one html file inside WebContent
  • Save it as message-data.html.
  • Add the code as given below.

Hello AJAX.............


Running the index.html

It can be run in two ways

  • One in standalone
  • Second on the server

standalone

  • Directly run the index.html on the browser
Output:-




  • Click  on tthe Show Message button.
  • It will display the message in the alert box.
  • It is retrieving the data from the message-data.html




On the server

  • Rt Click on the index.html as shown below in the Eclipse IDE.
  • Select Run As-->Run On Server
  • Select Tomcat server
  • Click on the finish button on the wizard.



  • Now index.html is running  on the server.
  • Click  on the Show Message button.





  • It will display the message in the alert box.
  • It is retrieving the data from the message-data.html




Download Zip code


AJAX - Sending a Request to the Server

  • To send off a request to the server, we use the open() method and the send() method.
  • The open() method takes three arguments. 
  • The first argument defines which method to use when sending the
    request (GET or POST).
  • The second argument specifies the URL of the server-side script.
  • The third argument specifies that the request should be handled asynchronously. 
  • The send() method sends the request off to the server. 
  • If we assume that the HTML and PHP file are in the same directory,
    the code would be:
    • xmlHttp.open("GET",“getname.php",true); xmlHttp.send(null);
Javascript- State Changed

function stateChanged() 

if  (xmlHttp.readyState==4)

  document.getElementById("txtHint").innerHTML=xmlHttp.responseText;
}
}


State changed Function
  • The readyState property holds the status of the server's response.
  • Each time the readyState changes, the onreadystatechange function will be executed.
  • Request is not initialized -0
  • The request has been set up – 1
  • The request has been sent  - 2
  • The request is in process – 3
  • The request is complete - 4
XMLHttpRequest Properties

  • onreadystatechange
    • Event handler that fires at each state change
    • You implement your own function that handles this
  • readyState – current status of request
    • 0 = uninitialized
    • 1 = loading
    • 2 = loaded
    • 3 = interactive (some data has been returned)
    • This is broken in IE right now
    • 4 = complete
  • status
    • HTTP Status returned from server: 200 = OK
  • responseText
    • String version of data returned from server
  • responseXML
    • XML DOM document of data returned
  • statusText
    • Status text returned from server

Using dynamic content and JSP

Step:

JavaScript
  • Define an object for sending HTTP requests
  • Initiate request
  • Get request object
  • Designate a response handler function
  • Supply as onreadystatechange attribute of request
  • Initiate a GET or POST request to a JSP page
  • Send data
  • Handle response
  • Wait for readyState of 4 and HTTP status of 200
  • Extract return text with responseText or responseXML
  • Do something with result
  • HTML
  • Loads JavaScript from centralized directory
  • Designates control that initiates reques

Date Example Of AJAX

  • This is very simple example.
  • In this example we have one jsp file date.jsp and one html file index.html
  • When the user  click on the current date and time button the AJAX come into
    action. and It will show the the result without refreshing the whole page.
  • Only a part of the page will be refreshed.

index.html
  • This <div> has the ID “targetDiv”, and you can use that ID to reach it.
  •  You can reach this <div> by using the document object, which represents the
    Web page, in JavaScript code.
  •  The document object has a very handy method named getElementById
  • Iif you pass the ID of the <div> to this method
    it will pass back to you a JavaScript object corresponding to the <div>.
<html>
  <head>
    <title>JavaScript-Ajax Application</title>

    <script language = "javascript">
      var XMLHttpRequestObject = false ;

      if  (window.XMLHttpRequest) {
        XMLHttpRequestObject = new  XMLHttpRequest();
      else if  (window.ActiveXObject) {
        XMLHttpRequestObject = new
          ActiveXObject("Microsoft.XMLHTTP");
      }

      function getDateTime(datetimefile, divID)
      {
        if (XMLHttpRequestObject) {
          var obj = document.getElementById(divID);
          XMLHttpRequestObject.open("POST", datetimefile);

          XMLHttpRequestObject.onreadystatechange = function()
          {
            if  (XMLHttpRequestObject.readyState == &&
              XMLHttpRequestObject.status == 200) {
                obj.innerHTML =
                  XMLHttpRequestObject.responseText;
            }
          }

          XMLHttpRequestObject.send(null );
        }
      }
    </script>
  </head>

  <body>

    <H1>JavaScript-Ajax Application</H1>

    <form>
      <input type = "button" value = "Get Current Date and Time"
        onclick = "getDateTime('date.jsp', 'targetDiv')">
    </form>
    <div id="targetDiv">
      
    </div>

  </body>
</html>
  • You can use the innerHTML property of that object 
    like this: document.getElementById(‘targetDiv’).innerHTML) 
  • to be able to access the text inside the <div>.

To get the data with the XMLHttpRequest object, use one of the two usual
ways:
  • If you retrieved data that you want to treat as standard text, you can
    use the object’s responseText property.
  • If your data has been formatted as XML, you can use the responseXML
    property. In this example, data.txt simply contains text, so you use
    the responseText property.
date.jsp
<%@page contentType="text/html" import ="java.util.*" %>
<html>
<meta http-equiv="refresh" content="1"
<body>
<p>&nbsp;</p>
<div align="left">
<table border="0" cellpadding="0" cellspacing="0"
 
width="460" bgcolor="#ADADDE">
<tr>
<td width="100%"><font size="6"
color="#000000">AJAX Date</font></td>
</tr>
<tr>
<td width="100%"><b>&nbsp;Current Date and time
 is:&nbsp; <font color=
"#FF0000">
<%= new  java.util.Date()%>
</font></b></td>
</tr>
</table>

</div>
</body>
</html> 


Output:-
  • First Run the Server(tomcat).
  • Deploy the project.
  • Then run the index.html file
  • The  following window will apears.




  • When the user click on the above shown button, the index.html will be showing
    the current date and time.
  • As shown below.
  • The user will be unaware of the processing that happened.



Download Zip code


Dynamic Content from Servlet


Step:

JavaScript
  • Define an object for sending HTTP requests
  • Initiate request
  • Get request object
  • Designate a response handler function
  • Supply as onreadystatechange attribute of request
  • Initiate a GET or POST request to a servlet
  • Send data
  • Handle response
    • Wait for readyState of 4 and HTTP status of 200
    • Extract return text with responseText or responseXML
    • Do something with result
HTML
  • Loads JavaScript from centralized directory
  • Designates control that initiates request

Example:

index.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>Ajax Basics: Part I</title>
<script src="./scripts/ajax-basics-1.js"
        type="text/javascript"></script>
</head>
<body>
<div align="center">
<table border="5">
  <tr><th class ="title">Ajax Basics: Part I</th></tr>
</table>
<p/>
Data from JSP, Result Shown in Alert Box</legend>
  <form action="#">
    <input type="button" value="Show Server Time"
           onclick='ajaxAlert("show-time.jsp")'/>
  </form>

</div></body></html>

show-message.js
function getRequestObject() {
  if  (window.ActiveXObject) {
    return (new  ActiveXObject("Microsoft.XMLHTTP"));
  else if  (window.XMLHttpRequest) {
    return (new  XMLHttpRequest());
  else  {
    return (null );
  }
}

function sendRequest() {
  var request = getRequestObject();
  request.onreadystatechange = 
    function() { handleResponse(request)};
  request.open("GET""message-data.html"true );
  request.send(null );
}

function handleResponse(request) {
  if  (request.readyState == 4) {
    alert(request.responseText);
  }
}



show-time.jsp

<%= new  java.util.Date() %>

ShowTime.java
package  myservlet;

import  java.io.*;
import  javax.servlet.*;
import  javax.servlet.http.*;
import  java.util.*;


public class  ShowTime extends  HttpServlet {
  public  void  doGet(HttpServletRequest request,
                    HttpServletResponse response)
      throws  ServletException, IOException {
    response.setHeader("Cache-Control""no-cache");
    response.setHeader("Pragma""no-cache");
    PrintWriter out = response.getWriter();
    Date currentTime = new  Date();
    String message =
      String.format("It is now %tr on %tD.",
                     currentTime, currentTime);
    out.print(message);
  }
}

web.xml
<?xml version="1.0" encoding="ISO-8859-1"?> 
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation=
           "http://java.sun.com/xml/ns/j2ee web-app_2_4.xsd"
         version="2.4"

  
  <servlet>
    <servlet-name>ShowTime</servlet-name>
    <servlet-class >myservlet.ShowTime</servlet-class >
  </servlet>
  <servlet-mapping>
    <servlet-name>ShowTime</servlet-name>
    <url-pattern>/show-time</url-pattern>
  </servlet-mapping>

  
  
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>index.html</welcome-file>
  </welcome-file-list>

</web-app>

message-data.html

Hello AJAX.............

Output:






Download zip code