ajax for dummies, and not only

26
Ajax For dummies and not only… Author: Alexios Tzanetopoulos - Developer

Upload: nerd-tzanetopoulos

Post on 07-Dec-2014

1.756 views

Category:

Technology


2 download

DESCRIPTION

Ajax, what is ajax, main idea, technologies used, history behind, examples, xml and json, drawbacks, jquery and ajax...

TRANSCRIPT

Page 1: Ajax for dummies, and not only

AjaxFor dummies and not only…

Author: Alexios Tzanetopoulos - Developer

Page 2: Ajax for dummies, and not only

So…. What is Ajax?

Ajax stands for: Asynchronous JavaScript and XML

It is a set of techniques for creating highly interactive web sites and web applications.

Examples?

http://www.aia.gr/traveler/flight-info/rtfi/

http://peteranswers.com/

Page 3: Ajax for dummies, and not only

Main idea

The idea is to make what’s on the Web appear to be local by giving you a rich user experience, offering you features that usually only appear in desktop applications.

Page 4: Ajax for dummies, and not only

Is Ajax a technology?

Ajax is NOT a technology. It’s a combination of several technologies:

standards-based presentation using XHTML and CSS;

dynamic display, interaction using the Document Object Model (DOM);

data interchange and manipulation using XML and JSON;

asynchronous data retrieval using XMLHttpRequest object;

and JavaScript binding everything together.

Page 5: Ajax for dummies, and not only

A little bit of History

Microsoft Outlook Web Access team implemented Ajax in 1998

Google maps and Gmail used it in 2005

James Garret wrote an article combining the techniques that google used and that’s how the term Ajax was coined (2005)

W3C released the first draft specification for the XMLHttpRequest object in an attempt to create an official web standard in 2006

Page 6: Ajax for dummies, and not only

Hands on code…

HTML - CSS

<H1>An Ajax example</H1>

<form>

<input type = "button" value = "Fetch the message“ onclick = "getData('data.php', 'targetDiv')">

</form>

<div id="targetDiv">

<p>The fetched message will appear here.</p>

</div>

Page 7: Ajax for dummies, and not only

Hands on code… continued Javascript – XmlHttpRequest – DOM Manipulation

<script language = "javascript">

var XMLHttpRequestObject = false;

if (window.XMLHttpRequest) XMLHttpRequestObject = new XMLHttpRequest();

else if (window.ActiveXObject) {

XMLHttpRequestObject = new

ActiveXObject("Microsoft.XMLHTTP");}

function getData(dataSource, divID){

if(XMLHttpRequestObject) {

var obj = document.getElementById(divID);

XMLHttpRequestObject.open("GET", dataSource);

XMLHttpRequestObject.onreadystatechange = function(){

if (XMLHttpRequestObject.readyState == 4 && XMLHttpRequestObject.status == 200)

obj.innerHTML = XMLHttpRequestObject.responseText;

XMLHttpRequestObject.send(null);

}

}

</script>

Page 8: Ajax for dummies, and not only

Hands on code… continued PHP

<?php

echo 'This text comes to you thanks to PHP.';

?>

Page 9: Ajax for dummies, and not only

Result?

Don’t believe it? Click here!

Page 10: Ajax for dummies, and not only

Ready states and status codes

Ready states

0 Uninitialized

1 Loading

2 Loaded

3 Interactive

4 Complete

Page 11: Ajax for dummies, and not only

Ready states and status codesStatus codes

1xx Informational

2xx Successful

3xx Redirection

4xx Client error

5xx Server error

Famous examples

200 OK

201 Created

400 Bad Request

401 Unauthorized

403 Forbidden

404 Not Found

Page 12: Ajax for dummies, and not only

Possibilities

That was plain text answer from the server. It could also be a xml or json object

Connection with a database

Not only Get data but also Post data

Page 13: Ajax for dummies, and not only

Usages

Web forms (password strength, autocomplete searches e.t.c.)

On-page notifications (like facebook)

On-site Instant Messaging (every chat uses ajax)

Collaborative tools (many people working on the same doc)

External widgets

and many many many many more…

Page 14: Ajax for dummies, and not only

XML Format

<CATALOG><CD>

<TITLE>Empire Burlesque</TITLE><ARTIST>Bob Dylan</ARTIST><COUNTRY>USA</COUNTRY><COMPANY>Columbia</COMPANY><PRICE>10.90</PRICE><YEAR>1985</YEAR>

</CD>….

Page 15: Ajax for dummies, and not only

XML Parsing

x=xmlhttp.responseXML.documentElement.getElementsByTagName("CD");for (i=0;i<x.length;i++){      xx=x[i].getElementsByTagName("TITLE");{        txt=txt + "<td>" + xx[0].firstChild.nodeValue + "</td>";        }    xx=x[i].getElementsByTagName("ARTIST");      {          txt=txt + "<td>" + xx[0].firstChild.nodeValue + "</td>";        }      txt=txt + "</tr>";}

Page 16: Ajax for dummies, and not only

Drawbacks

Bookmarking a page

Going back on a previous page

Difficult for a web crawler to index a page

Now every browser support javascript and XHR

Difficult for screen readers

Page 17: Ajax for dummies, and not only

What About jQuery and AJAX?

Writing regular AJAX code can be a bit tricky

Different browsers have different syntax for AJAX implementation

This means that you will have to write extra code to test for different browsers

The jQuery team has taken care of this for us

We can write AJAX functionality with only one single line of code

Page 18: Ajax for dummies, and not only

jQuery load() Method

The jQuery load() method is a simple, but powerful AJAX method. It loads data from a server and puts the returned data into the selected element.

$(selector).load(URL,data,callback);

The required URL parameter specifies the URL you wish to load.

The optional data parameter specifies a set of querystring key/value pairs to send along with the request.

The optional callback parameter is the name of a function to be executed after the load() method is completed.

Page 19: Ajax for dummies, and not only

jQuery load() Method Ex.

jQuery

$("button").click(function(){  $("#div1").load("demo_test.txt",function(responseTxt,statusTxt,xhr){    if(statusTxt=="success")      alert("External content loaded successfully!");    if(statusTxt=="error")      alert("Error: "+xhr.status+": "+xhr.statusText);  });});

demo_test.txt

<h2>jQuery and AJAX is FUN!!!</h2><p id="p1">This is some text in a paragraph.</p>

Page 20: Ajax for dummies, and not only

jQuery $.get() Method

The $.get() method requests data from the server with an HTTP GET request.

$.get(URL,callback);

The required URL parameter specifies the URL you wish to request.

The optional callback parameter is the name of a function to be executed if the request succeeds.

Page 21: Ajax for dummies, and not only

jQuery $.get() Method Ex.

jQuery

$("button").click(function(){  $.get("demo_test.php",function(data,status){    alert("Data: " + data + "\nStatus: " + status);  });});

demo_test.php

<?php

echo 'This text comes to you thanks to PHP.';

?>

Page 22: Ajax for dummies, and not only

jQuery $.post() Method

The $.get() method requests data from the server with an HTTP POST request.

$.post(URL,data,callback);

The required URL parameter specifies the URL you wish to request.

The optional data parameter specifies some data to send along with the request.

The optional callback parameter is the name of a function to be executed if the request succeeds.

Page 23: Ajax for dummies, and not only

jQuery $.post() Method Ex.

jQuery

$("button").click(function(){  $.post("demo_test_post.asp",  {    name:"Donald Duck",    city:"Duckburg"  },  function(data,status){    alert("Data: " + data + "\nStatus: " + status);  });});

demo_test.asp

<%dim fname,cityfname=Request.Form("name")city=Request.Form("city")Response.Write("Dear " & fname & ". ")Response.Write("Hope you live well in " & city & ".")

%>

Page 24: Ajax for dummies, and not only

HTTP GET vs HTTP POST

GET POST

BACK button/Reload HarmlessData will be re-submitted (the browser should alert the user that the data are about to be re-submitted)

Bookmarked Can be bookmarked Cannot be bookmarked

Cached Can be cached Not cached

History Parameters remain in browser historyParameters are not saved in browser history

Restrictions on data length

Yes, when sending data, the GET method adds the data to the URL; and the length of a URL is limited (maximum URL length is 2048 characters)

No restrictions

Restrictions on data type Only ASCII characters allowedNo restrictions. Binary data is also allowed

Security

GET is less secure compared to POST because data sent is part of the URL

Never use GET when sending passwords or other sensitive information!

POST is a little safer than GET because the parameters are not stored in browser history or in web server logs

Visibility Data is visible to everyone in the URL Data is not displayed in the URL

Page 25: Ajax for dummies, and not only

Too easy for you?

Take a look at reverse-ajax, a.k.a. Comet.

A Web server pushes data to a browser, without the browser explicitly requesting it.

Good luck with it…

Page 26: Ajax for dummies, and not only

Like it?

Kris Hadlock – Ajax for Web Application Developers

http://www.w3schools.com/jquery/

http://en.wikipedia.org/wiki/Ajax_%28programming%29

http://thesharad.files.wordpress.com/2010/10/ajax-a-beginners-guide.pdf

Bibliography