Ajax

19

description

 

Transcript of Ajax

Page 1: Ajax
Page 2: Ajax

AJAX:

Ajax is a way of developing Web applications that combines:

* XHTML and CSS standards based presentation * Interaction with the page through the DOM * Data interchange with XML and XSLT * Asynchronous data retrieval wit XMLHttpRequest * JavaScript to tie it all together

Page 3: Ajax

What is XMLHttpRequest (XHR)?

XMLHttpRequest (XHR) is an API available in web browser scripting languages such as JavaScript. It is used to send HTTP or HTTPS requests directly to a web server and load the server response data directly back into the script.The data might be received from the server as XML textor as plain text

Page 4: Ajax

ASYNCHRONOUS

This is the key. In standard Web applications, the interaction between the customer and the server is synchronous. This means that one has to happen after the other. If a customer clicks a link, the request is sent to the server, which then sends the results back.

With Ajax, the JavaScript that is loaded when the page loads handles most of the basic tasks such as data validation and manipulation, as well as display rendering the Ajax engine handles without a trip to the server. At the same time that it is making display changes for the customer, it is sending data back and forth to the server. But the data transfer is not dependent upon actions of the customer.

Page 5: Ajax

How does it work?

Page 6: Ajax

Creating XMLHttpRequest Objects:

Most of the modern browsers have the XMLHttpRequest support. However, in Internet Explorer browsers till IE7 XMLHttpRequest was offered only using ActiveX object. The later versions of Internet Explorer would support XMLHttpRequest.

The following function would create an XMLHttpRequest Object in most of the Browsers

function createXMLHttpRequest() {try { return new XMLHttpRequest(); } catch(e) {}try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) {}alert("Sorry, the XMLHttpRequest is not supported");return null;}var xhrObj = createXMLHttpRequest();

Page 7: Ajax

Request

SENDING REQUEST:To send a request to a server, we use the open() and send()

methods of the XMLHttpRequest object:

xmlhttp.open("GET","ajax_info.txt",true);xmlhttp.send();

GET Requests:xmlhttp.open("GET","demo_get.asp",true);xmlhttp.send();

POST Requests:xmlhttp.open("POST","demo_post.asp",true);xmlhttp.send();

Page 8: Ajax

Making a request:

1. Get whatever data you need from the Web form.

2. Build the URL to connect to.

3. Open a connection to the server.

4. Set up a function for the server to run when it's done.

5. Send the request.

Page 9: Ajax

SIMPLE EXAMPLE:

Inorder to make a text box ,and getting values thereby sending request to the server ,we need to make a text box and make the javascript with the coding and also calling functions with in the server ,by return sending the values back to the webpage,the javascript is as follows:

Page 10: Ajax

STEP 1 :TEST

<html><head><title>AJAX Hello World Test Page</title><link rel="stylesheet" href="http://www.EXAMPLE.com"

type="text/css" title="default" media="screen"><script type="text/javascript" src="ajax.js"></script></head><body><p><input id="testmsg" type="text" value="Hello AJAX"><button onclick="talktoServer()">Say Hello to Server</button><div id="msg_display" style="{ background: yellow; font-weight:

bold; }"> The data from the server will go here ...</div></body></html>

Page 11: Ajax

STEP 2: POST

function talktoServer(){var req = newXMLHttpRequest();//register the callback handler function

var callbackHandler = getReadyStateHandler(req, updateMsgOnBrowser);

req.onreadystatechange = callbackHandler; req.open("POST", "servertime.php", true); req.setRequestHeader("Content-Type", "application/x-www-form-

urlencoded"); //get the value from the text input element and send it to server var testmsg = document.getElementById("testmsg"); var msg_value = testmsg.value; req.send("msg="+msg_value);}

Page 12: Ajax

NOTE:

If browser is mozilla or safari or operaThen it creates new xmlhttprequest

Otherwise it is Internet explorerThen it creates new activexoject

Else ,browser does not support xmlhttprequest

Page 13: Ajax

Step 3: response from server

// This is the callback functions that gets called// for the response from the server with the XML datavar lastPing = 0;function updateMsgOnBrowser(testXML) {var test = testXML.getElementsByTagName("test")[0];var message = testXML.getElementsByTagName("message")[0];var ip = testXML.getElementsByTagName("ip")[0];var timestamp = test.getAttribute("timestamp");if (timestamp > lastPing) {astPing = timestamp;var ip_value = ip.firstChild.nodeValue;var message_value = message.firstChild.nodeValue;var msg_display = document.getElementById("msg_display");msg_display.innerHTML = " Server got the message: \"" + message_value + "\"" +"<br>Server IP: "+ ip_value + " Server Timestamp: \""+ timestamp + "\"" ;

}}

Page 14: Ajax

For callback functions

//the following two functions are helper infrastructure to //craete a XMLHTTPRequest and register a listner callback functionfunction newXMLHttpRequest() {

var xmlreq = false;if (window.XMLHttpRequest) {

xmlreq = new XMLHttpRequest();} else if (window.ActiveXObject) {

// Try ActiveXtry {

xmlreq = new ActiveXObject("Msxml2.XMLHTTP");} catch (e1) {

// first method failed try {

xmlreq = new ActiveXObject("Microsoft.XMLHTTP");} catch (e2) {

// both methods failed } }}return xmlreq;}

Page 15: Ajax

function getReadyStateHandler(req, responseXmlHandler) {return function () {if (req.readyState == 4) {

if (req.status == 200) { responseXmlHandler(req.responseXML);

} else {var hellomsg = document.getElementById("hellomsg");hellomsg.innerHTML = "ERROR: "+ req.status;

} } }}

Page 16: Ajax

<?header('Content-Type: application/xml');$msg = htmlentities(trim(stripslashes($_REQUEST['msg'])));$ts = time();$ip = gethostbyname("example.com"); print ("<?xml version=\"1.0\"?>");print ("<test timestamp=\"$ts\">");print ("<ip>$ip</ip>");print ("<message>$msg</message>");print ("</test>");?>

Thus the data request sent from the webpage to server and after certain schematic conditions,the data is back on the [as said asynchronous] it displayed without affecting the process

Step 4:Data back to the weboage

Page 17: Ajax

RESPONSE HANDLING:

There are two types of response

*response text and response xml

*many other forms like json,html etc[ these may come under one of the those two categories]

Page 18: Ajax

USAGE IN BLOGS:

1.We need to check whether the client can actually handle this or we need to import one [just the same of creating xml request]

2.we can link in the database as we needed ,example lets take calender,it need to be updated from a site and then that particular data need to be used in here.

AJAX is combination of twoAJAX =DOM +XMLhttprequest

Page 19: Ajax

DRAWBACKS:

1.AJAX are mainly suitable for thier dynamic pages,so its harder to develop them in static web pages

2.Dynamically created pages will not go on with the brower's page ,so when the user click on the back button,they might not go to the previous page but to a very first page

3.Dynamic webpages will make bookmarking difficult for the uers

4.Many web crawlers will not allow java script,so inorder to prevent it,alternate method must be induced in order to index them using the search engines

5.AJAX powered webpages generate lot of user requests ,taking longer access rate in server to respong the user