How Ajax Works

Wdd Logo.
November 11, 2008
In traditional JavaScript coding, if you want to get any information from a database or a file on the server, or send user information to a server, you will have to make an HTML form and GET or POST data to the server. The user will have to click the "Submit" button to send/get the information, wait for the server to respond, and then a new page will load with the results. Because the server returns a new page each time the user submits input, traditional web applications can run slowly and tend to be less user-friendly. With AJAX, your JavaScript communicates directly with the server, through the JavaScript XMLHttpRequest object. With an HTTP request, a web page can make a request to, and get a response from a web server, without reloading the page. The user will stay on the same page, and he or she will not notice that scripts request pages, or send data to a server in the background. This picture is a simplified introduction about how Ajax works: The user sends a request that executes an action and the action's response is showed into a layer, identify by an ID, without reload the full page. For example a layer with this id: <div id="ajaxResponse"></div> In the next steps we will see how to create an XMLHttpRequest and receive response from the server.

1. Create XMLhttpRequest

Different browsers use different methods to create the XMLHttpRequest object. Internet Explorer uses an ActiveXObject, while other browsers use the built-in JavaScript object called XMLHttpRequest. To create this object, and deal with different browsers, we are going to use a "try and catch" statement. function ajaxFunction() { var xmlHttp; try { // Firefox, Opera 8.0+, Safari xmlHttp=new XMLHttpRequest(); } catch (e) { // Internet Explorer try { xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { alert("Your browser does not support AJAX!"); return false; } } }

2. Sending request to the server

To send off a request to the server, we use the open() method and the send() method. The open() method takes three arguments. The first argument defines which method to use when sending the request (GET or POST). The second argument specifies the URL of the server-side script. The third argument specifies that the request should be handled asynchronously. The send() method sends the request off to the server. xmlHttp.open("GET","time.asp",true); xmlHttp.send(null);

3. Writing server side script

The responseText will store the data returned from the server. Here we want to send back the current time. The code in "time.asp" looks like this: <% response.expires=-1 response.write(time) %>

4. Consuming the response

Now we need to consume the response received and display it to the user. xmlHttp.onreadystatechange=function() { if(xmlHttp.readyState==4) { document.myForm.time.value=xmlHttp.responseText; } } xmlHttp.open("GET","time.asp",true); xmlHttp.send(null); }

5. Complete the code

Now we must decide when the AJAX function should be executed. We will let the function run "behind the scenes" when the user types something in the username text field. The complete code looks like this: <html> <body> <script type="text/javascript"> function ajaxFunction() { var xmlHttp; try { // Firefox, Opera 8.0+, Safari xmlHttp=new XMLHttpRequest(); } catch (e) { // Internet Explorer try { xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { alert("Your browser does not support AJAX!"); return false; } } } xmlHttp.onreadystatechange=function() { if(xmlHttp.readyState==4) { document.myForm.time.value=xmlHttp.responseText; } } xmlHttp.open("GET","time.asp",true); xmlHttp.send(null); } </script> <form name="myForm"> Name: <input type="text" onkeyup="ajaxFunction();" name="username" /> Time: <input type="text" name="time" /> </form> </body> </html>

WDD Staff

WDD staff are proud to be able to bring you this daily blog about web design and development. If there's something you think we should be talking about let us know @DesignerDepot.

Read Next

10+ Best Resources & Tools for Web Designers (2024 update)

Is searching for the best web design tools to suit your needs akin to having a recurring bad dream? Does each…

3 Essential Design Trends, April 2024

Ready to jump into some amazing new design ideas for Spring? Our roundup has everything from UX to color trends…

How to Plan Your First Successful Website

Planning a new website can be exciting and — if you’re anything like me — a little daunting. Whether you’re an…

15 Best New Fonts, March 2024

Welcome to March’s edition of our roundup of the best new fonts for designers. This month’s compilation includes…

LimeWire Developer APIs Herald a New Era of AI Integration

Generative AI is a fascinating technology. Far from the design killer some people feared, it is an empowering and…

20 Best New Websites, March 2024

Welcome to our pick of sites for March. This month’s collection tends towards the simple and clean, which goes to show…

Exciting New Tools for Designers, March 2024

The fast-paced world of design never stops turning, and staying ahead of the curve is essential for creatives. As…

Web Tech Trends to Watch in 2024 and Beyond

It hardly seems possible given the radical transformations we’ve seen over the last few decades, but the web design…

6 Best AI Productivity Apps in 2024

There’s no escaping it: if you want to be successful, you need to be productive. The more you work, the more you…

3 Essential Design Trends, February 2024

From atypical typefaces to neutral colors to unusual user patterns, there are plenty of new website design trends to…

Surviving the Leap from College to Real-World Design

So, you’ve finished college and are ready to showcase your design skills to the world. This is a pivotal moment that…

20 Mind-Bending Illusions That Will Make You Question Reality

Mind-bending videos. Divisive Images. Eye-straining visuals. This list of optical illusions has it all. Join us as we…