Funding for 'IT Lab' Project, Phase 1: Progress of sticker sales. Purchase a sticker to help us reach our target.Updated: 2010-02-28 11:53
10.7%
AJAX without the hassle


by Kusal Arthanayaka


Asynchronous JavaScript and XML (AJAX) is not hard as it may seems. As the name implies it is all about JavaScript. Even though the name talks about XML, AJAX is not limited to XML. It can easily communicate with text files, any server side script (php, asp, jsp) and JSON.

We are using AJAX to improve site speed and user experience and interactivity.

Most famous example is checking username without a page load. Usually found on register pages. If you look at both new Gmail and yahoo mails it uses AJAX extensively.

You don’t need to write raw JavaScript to use AJAX anymore. There are lot of frameworks that helps you write core AJAX functionalities with few as 10 code lines.

If you like to learn about core JavaScript underlining AJAX I recommend reading AJAX for dummies book which will teach you AJAX from the scratch.

For this article we’ll talk about how to write AJAX code within 10 minutes using the DOJO JavaScript framework.

Let’s look at the code:



Copy this code and create an html page. Also create a text file. Name it as result (using notepad). inside the text file write anything you like.

We are using Google CDN to attach dojo.js without actually downloading the file and attaching. If you like to download dojo.js follow this link http://www.dojotoolkit.org/downloads

Dojo.js has all the core functionalities we are going to use in this example.

In this example we have created a button with the function send_request() called on click. Also just above the button we have placed a span tag with the id “result” which will hold the result from the AJAX output.

When you click the button “Hit this” it will invoke the send_request fuction.

If you go thorough that fuction you’ll first see that we are using GET method to send the request using dojo.xhrGet

In the url: you give the path to the text file we created earlier.

Load: will invoke the function Callback

Callback function will get the content from the text file to the variable data.

Now we can use the variable data to assign the output to the span tag using DHTML

document.getElementById('result').innerHTML = data;

Error function will only be invoked if something goes worng.

This is the most basic example you can do. In following articles we will dig deep into AJAX examples using php.

Share/Save
No votes yet

Post new comment

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

More information about formatting options