How To Use Ajax (asynchronous Javascript)

Welcome. Please Login, Register, Or Activate! 
type your username and password to login
Date: November 22, 2009, 01:36 AM
430643 members and 297796 Topics
Latest Member: KELVIN5000
Nairaland [Nigerian Forum] Home Help Search Who is currently online? Login Register
Nairaland Forum  |  Technology  |  Webmasters (Moderators: OmniPotens, yawa-ti-de)  |  How To Use Ajax (asynchronous Javascript)
Pages: (1) Go Down Send this topic Notify of replies
Author Topic: How To Use Ajax (asynchronous Javascript)  (Read 929 views)
*dhtml
How To Use Ajax (asynchronous Javascript)
« on: January 04, 2009, 06:44 PM »

We are now going to learn that branch of javascript called ajax (Asynchronous Javascript).
This guy has been around for a long time - just that most browsers do not support it then - but now - virtually all
the desktop browsers are now DHTML compliant and so they now support ajax.

If you don't know some javascript - u may try reading my other thread http://www.nairaland.com/nigeria?topic=213492.0 before you continue this thread.

You so we are going to be talking about ajax here today.
*dhtml
Re: How To Use Ajax (asynchronous Javascript)
« #1 on: January 04, 2009, 07:15 PM »

Fundamentals of Ajax - Understand this last post - Then U Can Start using Ajax.

We are now going to a very small demo site loading with ajax:

The sample can be found on http://mwebng.net/demos/ajax_starter/

Download from www.mwebng.net/?net=dl

home.html
Code:
Welcome to my home page,

about.html
Code:
I am a freelance software programmer and website developer

contact.html
Code:
Contact me on 08027069307

Those are the content files we want to download with ajax. Now for the ajax loader.
index.html
Code:
<title>My Web Site</title>

<script>
function ajaxRequest() {
var activexmodes=["Msxml2.XMLHTTP", "Microsoft.XMLHTTP"] //activeX versions to check for in IE
if (window.ActiveXObject){ //Test for support for ActiveXObject in IE first (as XMLHttpRequest in IE7 is broken)
  for (var i=0; i<activexmodes.length; i++){try{return new ActiveXObject(activexmodes[i])} catch(e){alert("Failed");}}
} else if (window.XMLHttpRequest) {return new XMLHttpRequest()} else {return false}
return;
}

function download(url) {
var mygetrequest=new ajaxRequest()

    mygetrequest.onreadystatechange=function(){
     if (mygetrequest.readyState==4){
      if (mygetrequest.status==200) {document.getElementById('display').innerHTML=mygetrequest.responseText;}
  else {alert("Download was not successful");}
}
}
mygetrequest.open("POST", url, true);
mygetrequest.send(null);
}


</script>

<a href="javascript:download('home.html')">Home</a>
<a href="javascript:download('about.html')">About</a>
<a href="javascript:download('contact.html')">Contact</a>

<hr size=1>

<div id="display"></div>

So let us now break it down into bits and pieces

Code:
function ajaxRequest() {
var activexmodes=["Msxml2.XMLHTTP", "Microsoft.XMLHTTP"] //activeX versions to check for in IE
if (window.ActiveXObject){ //Test for support for ActiveXObject in IE first (as XMLHttpRequest in IE7 is broken)
  for (var i=0; i<activexmodes.length; i++){try{return new ActiveXObject(activexmodes[i])} catch(e){alert("Failed");}}
} else if (window.XMLHttpRequest) {return new XMLHttpRequest()} else {return false}
return;
}

This code is meant to check the browser and return a copy of the ajax engine the browser supports - do not even bother yourself - even i cannot write that function offhand - yet i have used it to pull lots of stuffs with ajax - it is only important to know how to use it.


Code:
function download(url) {
var mygetrequest=new ajaxRequest()

    mygetrequest.onreadystatechange=function(){
     if (mygetrequest.readyState==4){
      if (mygetrequest.status==200) {document.getElementById('display').innerHTML=mygetrequest.responseText;}
  else {alert("Download was not successful");}
}
}
mygetrequest.open("POST", url, true);
mygetrequest.send(null);
}

This other one shows how to use the engine to perform a transaction with the server and get the results.
Yes, and what they mean by asynchronous in ajax is that - since a request is sent to the server and back - this means you will not get your results immediately. This code i am tryin to explain is the fundamental of ajax - if u understand it then you are ready for ajax.
So i am going to try to move slowly and assume u don't know much about javascript.


function download(url) -   My custom download function accept a url [which must be on your website - can be php, anything]

var mygetrequest=new ajaxRequest() - creates a new copy of the ajax engine for use.

Because of the nature of the transaction, there is something programmers refer to as callback function
that is what the  onreadystatechange function does. it keep monitoring the transfer,
and as it does its value keeps changing from 0 to 4 - don't worry if u do not understand the last statement.

To track that readystate function we declare the next line
mygetrequest.onreadystatechange=function() {, }

At the point that readyState becomes 4 - the transaction is completed - that could mean success or failure.
if (mygetrequest.readyState==4){ - this is activated the moment download is either successful or failed.

//so we want to check for success - we need to check another property of that ajax engine called status
status will return 200 when download is successful. The next next line checks for success:
      if (mygetrequest.status==200) {document.getElementById('display').innerHTML=mygetrequest.responseText;}

If successful, the property of the ajax engine (copied into mygetrequest) called reponseText will now return
the content of the downloaded url.
It was at this point we now write the content downloaded into the DIV called display by using
document.getElementById('display').innerHTML=mygetrequest.responseText;

If status is not 200 and readystate is false, then download has failed: so the next line comes into play
else {alert("Download was not successful");}

So after declaring all of the above, we now allow the ajax engine to go and fetch the url
That is where the next lines come into play
mygetrequest.open("POST", url, true);
mygetrequest.send(null);      

That does it. At this point i think you should analyze the demo - use it, look at the source code - and read all the jargons i have posted here -
it  just might make some sense.


webdezzi (m)
Re: How To Use Ajax (asynchronous Javascript)
« #2 on: January 04, 2009, 07:36 PM »

you mentioned 0-4,

does this mean that when the ready state is say 3, then the content is 75% fetched

or

does 3 mean some status like say connection problem, server timeout or 404

if it is the first, then it means i can display a progess bar with that or the latter, i can tell users what went wrong.
*dhtml
Re: How To Use Ajax (asynchronous Javascript)
« #3 on: January 04, 2009, 07:43 PM »

Code:
Readystatechange Values

String that specifies one of the following values: uninitialized Object is not initialized with data.
0 - initializing.
1 - loading Object is loading its data.
2 - loaded Object has finished loading its data.
3 - interactive User can interact with the object even though it is not fully loaded.
4 - complete Object is completely initialized.

"readyState", "status", and "statusText" properties

During an Ajax request, a few properties on the returned object inform you of the status of the request. The "readyState" keeps track of the current stage of the request by returning an integer:

0: uninitialized
1: loading
2: loaded
3: interactive
4: complete
Typically you simply test for a value of 4 to know when the request is complete.

"status" returns the status code of the request, for example, "404" for a failed request, "200" for a successful one etc.  If you're running the Ajax request offline locally on your PC, a value of 0 is returned in some browsers regardless of the actual request status.

"statusText" returns a string describing the status of the request, such as "Not Found".
*dhtml
Re: How To Use Ajax (asynchronous Javascript)
« #4 on: January 04, 2009, 07:45 PM »

To learn more about ajax, please visit http://www.javascriptkit.com/jsref/ajax.shtml - and come back here to ask your questions.
And also http://w3schools.com/ajax/default.asp - pending my next post.
 Are FemaleClients More Difficult To Satisfy?  An E-book That Will Make You A Webmaster In No Time  Buy Albenza  Page 2
Pages: (1) Go Up Send Topic to Friend by E-mail Reply 


Sections: Autos/Cars (2) Jobs/Vacancies (2) (3) Career Talk Education General(2) Politics Romance Computers Phones Travel
Sports Fashion Health Religion Celebrities TV/Movies (2) Music/Radio (2) Books Webmasters Programming

Links: Page1 Page2 Page3 Page4 Page5 Page6 Page7 Page8 Page9 Page10

Nairaland is owned by Oluwaseun Osewa. See also: Nairalist Classified Ads
Nairaland Forum | Powered by SMF 1.0.12.
© 2001-2005, Lewis Media. All Rights Reserved.