Samples programs for working with Ajax

AJAX Overview

AJAX stands for Asynchronous Javascript And XML which is based on the Javascript and HTTP Requests.moreover its a new way of technology to use existing standards since its not a programming language.it can be used to creating better, faster, and more interactive web applications.

we can using JavaScript to communicate directly with the server by using Ajax with the XMLHttpRequest object. it helps to accessing the web server without reloading the page.AJAX uses asynchronous data transfer (HTTP requests) between the browser and the web server that allowing web pages to request small bits of information from the server instead of whole pages.

AJAX based on the Following

  • JavaScript
  • XML
  • HTML
  • CSS
AJAX Provide better Internet-applications

Normally, Website applications are using more than the desktop applications; they can reach a much more audience, they are easier to handling, and easier to develop. However, Internet-applications are not always as "rich" and user-friendly as desktop applications. we can using AJAX to provide Internet applications with richer and more user-friendly.

How AJAX is Working?

Ajax working as a programming model with display and events. These events are user actions, they call functions associated to elements of the web page.

To read and retrieve the contents from the server, XMLHttpRequest provides two methods:

  • open: create a connection.
  • send: send a request to the server.

Server Provided the Data by using attributes of XMLHTTPRequest objects as:

  • responseXml for an XML file or
  • responseText for a plain text.

along the time of processing the data, the state of data is given by the readyState attribute of XMLHttpRequest.those ready states are as follows,

  • 0: not initialized.
  • 1: connection established.
  • 2: request received.
  • 3: answer in process.
  • 4: finished.
AJAX with DHTML

Dynamic HTML contains the following

  • HTML
  • CSS
  • JavaScript

DHTML can be used to change the page display according to the user commands or user text. Ajax allows also to send requests asynchronously and load data from the server.

The XMLHttpRequest object

the following Objects are used by AJAX to interact with the Server

Attributes
  • readyState -the code successively changes value from 0 to 4 that means for "ready".
  • status -200 : ok, 404 : page not found
  • responseText -holds loaded data as a string of characters.
  • responseXml -holds an XML loaded file, DOM's method allows to extract data.
  • onreadystatechange property that takes a function as value that is invoked when the readystatechange event is dispatched.
Methods
  • open(mode, url, boolean)  here mode: GET or POST   url: the location of the file, with a path.  boolean: true (asynchronous) / false (synchronous).
  • send("string") null for a GET command.
Performing a request Step1: Create instance

use the following code snippets that denotes Instance of the Class, and two options for browser compatibility,

if (window.XMLHttpRequest)  // Object of the current windows
{ 
    xhr = new XMLHttpRequest();  // Firefox, Safari, ...
} 
else 
 if (window.ActiveXObject) // ActiveX version
 {
    xhr = new ActiveXObject("Microsoft.XMLHTTP");  // Internet Explorer 
 } 
                        
 
Step2: wait for the Response

The response of the server will be assigned to the onreadystatechange attribute of the object previously created.

 xhr.onreadystatechange = function()
if (xhr.readyState == 4)
{
   // Received, OK
} else 
{
  // Wait...
}
                         
Step3: Perform a Request

Two methods of XMLHttpRequest are used:

  • open: GET or POST
  • send: with POST only, the data to send to the server.

 

xhr.open('GET', 'http://www.xul.fr/somefile.xml', true);                  
xhr.send(null); 
                         
 
Examples

Get a Text

                  
<html>
<head>
<script>
function submitForm()
{ 
    var xhr; 
    try {  xhr = new ActiveXObject('Msxml2.XMLHTTP');   }
    catch (e) 
    {
        try {   xhr = new ActiveXObject('Microsoft.XMLHTTP');    }
        catch (e2) 
        {
          try {  xhr = new XMLHttpRequest();     }
          catch (e3) {  xhr = false;   }
        }
     }
  
    xhr.onreadystatechange  = function()
    { 
         if(xhr.readyState  == 4)
         {
              if(xhr.status  == 200) 
                  document.ajax.dyn="Received:"  + xhr.responseText; 
              else 
                 document.ajax.dyn="Error code " + xhr.status;
         }
    }; 

   xhr.open(GET, "data.txt",  true); 
   xhr.send(null); 
} 
</script>
</head>
                 
<body>
    <FORM method="POST" name="ajax" action="">                  
         <INPUT type="BUTTON" value="Submit"  ONCLICK="submitForm()">
         <INPUT type="text" name="dyn"  value=""> 
    </FORM>
 </body>
 </html>

Get a XML
To get data from an XML file, we have just to replace the code as:

                  
var doc = xhr.responseXML;   // Assign the XML file to a var
var element = doc.getElementsByTagName('root').item(0);   // Read the first element
document.ajax.dyn.value= element.firstChild.data;    // Assign the content to the form

Write on Body
the text read is put into the body of the page

                  
document.getElementById("zone").innerHTML = "Received:" + xhr.responseText;	               

Post a Text
a text is sent to the server and is written into a file.

                  
xhr.open("POST", "ajax-post-text.php", true); 
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");                  
xhr.send(data);     
Using an external file

here,we can include a JavaScript file and calling a function using following code,

                  
<script src="ajax.js" type="text/javascript"></script> 
var xhr = createXHR();
 
Disadvantages
  • Ajax will not works when a JavaScript is not activated, . The user must be asked to set JavaScript from within options of the browser, with the "noscript" tag.
  • Since data to display are loaded dynamically, they are not part of the page, and the keywords inside are not viewed by search engines.
  • The asynchronous mode may change the page with delays (when the processing on the server take some times), this may be disturbing.
  • The back button may be deactivated (this is not the case in examples provided here). This may be overcomed.

Posted by: Admin
Posted on: 9/8/2009 at 4:47 PM
Tags: , , , ,
Categories: Ajax
Actions: E-mail | Kick it! | DZone it! | del.icio.us
Post Information: Permalink | Comments (35) | Post RSSRSS comment feed

Comments

cash advance United States

Friday, October 16, 2009 6:13 PM

cash advance

I guess there's always an easier way ...

payday loans United States

Monday, November 09, 2009 12:10 AM

payday loans

Like your writing! Still you can do some things to improve it.

cash loans United States

Monday, November 16, 2009 4:40 PM

cash loans

Searching for this for some time now - i guess luck is more advanced than search engines Smile

New Mexico Payday Loans United States

Thursday, December 17, 2009 4:07 PM

New Mexico Payday Loans

Like your writing! Still you can do some things to improve it.

ucvhost United States

Friday, February 05, 2010 1:01 PM

ucvhost

love your writing

teeth whitening United States

Tuesday, March 02, 2010 10:36 AM

teeth whitening

A leader is best when people barely know he exists, when his work is done, his aim fulfilled, they will say: we did it ourselves.

df United States

Friday, March 05, 2010 5:12 PM

df

hi..

Fighting Baby Allergies United States

Saturday, March 06, 2010 5:14 AM

Fighting Baby Allergies

I don’t know how to use JavaScript up to now because I’m trying to work with ASP.Net but never get tired in exploring a lot of things about web applications. Hope to know this kind of web application. Have a nice day!

internet payday loans United States

Thursday, March 25, 2010 9:39 AM

internet payday loans

This is my first time i visit here. I found so many interesting stuff in your blog especially its discussion. From the tons of comments on your articles, I guess I am not the only one having all the enjoyment here! keep up the good work.

cash advance payday loan United States

Friday, March 26, 2010 4:45 PM

cash advance payday loan

I admire what you have done here. I like the part where you say you are doing this to give back but I would assume by all the comments that this is working for you as well.

fast loan approval United States

Monday, March 29, 2010 3:24 PM

fast loan approval

I am not really sure if best practices have emerged around things like that, but I am sure that your great job is clearly identified. I was wondering if you offer any subscription to your RSS feeds as I would be very interested and can?t find any link to subscribe here.

easy bad credit loans United States

Tuesday, March 30, 2010 4:25 AM

easy bad credit loans

Hey very nice blog!! Man .. Beautiful .. Amazing .. I will bookmark your blog and take the feeds also...

home remedies to get rid of stretch marks United States

Thursday, April 01, 2010 3:17 PM

home remedies to get rid of stretch marks

Have you ever considered adding more videos to your blog posts to keep the readers more entertained? I mean I just read through the entire article of yours and it was quite good but since I'm more of a visual learner,I found that to be more helpful well let me know how it turns out!

Helpful Car Rental Tips United States

Monday, April 05, 2010 4:12 AM

Helpful Car Rental Tips

This one looks awesome.  It was definitely a superb post. Thanks for sharing your remarkable thought and awesome ideas. Cheers!

Rapidshare United States

Wednesday, April 28, 2010 3:18 AM

Rapidshare

I\'m happy I found this blog, I couldnt discover any info on this subject matter prior to. I also run a site and if you want to ever serious in a little bit of guest writing for me if possible feel free to let me know, i\'m always look for people to check out my site. Please stop by and leave a comment sometime!

online payday loans United States

Friday, May 07, 2010 4:53 PM

online payday loans

The golden rule for every business man is this: "Put yourself in your customer's place".

personal loans United States

Tuesday, May 18, 2010 5:44 AM

personal loans

In searching for sites related to web hosting and specifically comparison hosting linux plan web, your site came up.You are a very smart person!

fast payday loans United States

Thursday, May 20, 2010 9:03 AM

fast payday loans

I keep listening to the news talk about getting free online grant applications so I have been searching around for the best site to get one.

Levoca - the heart of Spis region United States

Friday, June 04, 2010 5:56 AM

Levoca - the heart of Spis region

I wish to know more about this because it actually catches my attention. Keep on posting valuable information about this dude! Thank you so much for sharing.  

Svitlana.Net.Ua United States

Tuesday, June 15, 2010 4:54 PM

Svitlana.Net.Ua

I would like to thank you for the efforts you have made in writing this post. I am hoping the same best work from you in the future as well. In fact your creative writing abilities has inspired me to start my own BlogEngine blog now.

няня United States

Thursday, June 17, 2010 3:17 PM

няня

I would like to thank you for the efforts you have made in writing this post. I am hoping the same best work from you in the future as well. In fact your creative writing abilities has inspired me to start my own BlogEngine blog now.
http://svitlana.net.ua/staff/category/3/ гувернантка, http://svitlana.net.ua/staff/category/5/ повар, http://svitlana.net.ua/staff/category/6/ садовник, http://svitlana.net.ua/staff/category/10/ репетитор, http://svitlana.net.ua/staff/category/4 домработница, http://svitlana.net.ua/staff/category/8/ семейная пара, http://svitlana.net.ua/pages/2/ работа няней.

Проститутки United States

Wednesday, June 23, 2010 7:59 PM

Проститутки

За умеренную суму они могут получить все, что хотят, причем жрицы любви от этого получат не меньше удовольствия, чем их клиентки. Большинство женщин, которые имеют такие наклонности, стараются их скрыть, потому что уже имеют семью и мужа, который может негативно отреагировать на такие желания своей супруги, а это чревато скандалом и, что еще хуже, разводом. Именно по этой причине, женщины предпочитают тихонько заказать эту услугу у проститутки Сочи, и отлучиться на часок, другой, чтобы удовлетворить свои природные желания и фантазии.

Игра в Покер United States

Sunday, June 27, 2010 3:27 AM

Игра в Покер

Can you please provide more information on this subject? BTW your blog is great. Cheers.

piano music not lessons United States

Friday, July 02, 2010 2:06 PM

piano music not lessons

H  o  w   t  o   p  l  a  y   t  h  e   p  i  a  n  o   u  s  i  n  g t  h  e   h  a  r  m  o  n  i  c s  t  r  uc  tu  r  e  s   o  f   c  h  o  r  d  s   A brief tutorial  not being utilised for profit  copyright   1997 Sonia Balcer

Магазин сантехники United States

Sunday, July 04, 2010 10:45 PM

Магазин сантехники

You have some honest ideas here. I done a research on the issue and discovered most peoples will agree with your blog.

проститутка в Москве United States

Thursday, July 08, 2010 4:50 AM

проститутка в Москве

It\\\\\\\'s an intriguing approach. I ordinarily stumble upon ordinary thoughts on the theme but yours it\\\\\\\'s written in a pretty special way. Sure enough, I will revisit your website for additional information.

Проститутки United States

Saturday, July 10, 2010 10:01 PM

Проститутки

You gave nice ideas here. I done a research on the issue and learnt most peoples will agree with your blog. Certainly, these practices are unfair; but they say that most of their rules are only to apply to people who overdraw.

Новинки сантехники United States

Sunday, July 11, 2010 7:58 PM

Новинки сантехники

I really got a kick out of your article. I don\\\'t really have much to say in reply, I only wanted to comment to reply with wonderful operate. good luck in 2010.

loan consolidation United States

Saturday, July 17, 2010 10:46 PM

loan consolidation

Human beings, by changing the inner attitudes of their minds, can change the outer aspects of their lives.

California Escorts United States

Thursday, July 22, 2010 9:55 AM

California Escorts

Fine information and facts a lot of thanks to the creator

world of warcraft quests walkthrough United States

Friday, July 23, 2010 12:57 PM

world of warcraft quests walkthrough

Dragons  Wise  majestic and graceful beings entrusted because of the Titans to watch more than Azeroth in their absence  Should you have even a cursory knowledge of World of Warcraft  you ll know that dragons frequently perform an essential element in events  Nevertheless  right now we appear not to praise them but rather to bury them  for majestic they might be  but all as well typically they re either irredeemably evil or absolutely insane  generally equally  and  a lot more importantly  they tend to carry a fabulous volume of gold and loot on them

buy drugs online United States

Saturday, July 24, 2010 3:21 AM

buy drugs online

That is a great review of Ajax. It really helped me out.

without prescription United States

Saturday, July 24, 2010 3:22 AM

without prescription

I completely agree. I have never really had a easy time with Ajax.

canada pharmacy United States

Saturday, July 24, 2010 3:23 AM

canada pharmacy

Very true.

Add comment




  Country flag

biuquote
  • Comment
  • Preview
Loading