Welcome, Guest: Register On Nairaland / LOGIN! / Trending / Recent / New
Stats: 3,150,680 members, 7,809,575 topics. Date: Friday, 26 April 2024 at 11:30 AM

How To Use Ajax (asynchronous Javascript) - Webmasters - Nairaland

Nairaland Forum / Science/Technology / Webmasters / How To Use Ajax (asynchronous Javascript) (6774 Views)

Form Validation Tutorial Using Javascript, Php And Ajax! / Create Ajax Chat & Learn Web Page Data Xchange via Json Vs Xml / Dynamic Web Design Tutorials Ft Javascript,Ajax,DOM,PHP,MySQL... (2) (3) (4)

(1) (Reply) (Go Down)

How To Use Ajax (asynchronous Javascript) by Nobody: 6:44pm On Jan 04, 2009
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 https://www.nairaland.com/nigeria?topic=213492.0 before you continue this thread.

You so we are going to be talking about ajax here today.
Re: How To Use Ajax (asynchronous Javascript) by Nobody: 7:15pm On Jan 04, 2009
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

Welcome to my home page,


about.html

I am a freelance software programmer and website developer


contact.html

Contact me on 08027069307


Those are the content files we want to download with ajax. Now for the ajax loader.
index.html

<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"wink;}}
} 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"wink;}
}
}
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


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"wink;}}
} 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.



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"wink;}
}
}
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"wink;}

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.
Re: How To Use Ajax (asynchronous Javascript) by Nobody: 7:36pm On Jan 04, 2009
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.
Re: How To Use Ajax (asynchronous Javascript) by Nobody: 7:43pm On Jan 04, 2009
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".
Re: How To Use Ajax (asynchronous Javascript) by Nobody: 7:45pm On Jan 04, 2009
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.
Re: How To Use Ajax (asynchronous Javascript) by baccifinejewelry: 7:13am On Jul 13, 2010
Thank you guys for starting this topic. Sooner or later I will learn how to build my own site through the different tutorials posted here.
Re: How To Use Ajax (asynchronous Javascript) by Textaiwo: 12:24pm On Dec 30, 2011
Asynchronous thinking
Re: How To Use Ajax (asynchronous Javascript) by Nobody: 1:09pm On Dec 30, 2011
^^^Interesting, i love that

(1) (Reply)

How To Get More Readers On Your Blog / 100 Euro Itunes Gift Card For Sale / Diffrent Wapka Css Stylesheets For Ur Wapka Site.

(Go Up)

Sections: politics (1) business autos (1) jobs (1) career education (1) romance computers phones travel sports fashion health
religion celebs tv-movies music-radio literature webmasters programming techmarket

Links: (1) (2) (3) (4) (5) (6) (7) (8) (9) (10)

Nairaland - Copyright © 2005 - 2024 Oluwaseun Osewa. All rights reserved. See How To Advertise. 31
Disclaimer: Every Nairaland member is solely responsible for anything that he/she posts or uploads on Nairaland.