Asynchronous JavaScript vs. Ajax


Asynchronous JavaScript, as used by Google Analytics, allows to run scripts on a deferred mode without slowing down the page loading. The script runs when it is available and it may come from another site, from the statistical online service on the Google site for Analytics.
This technology is it an alternative to Ajax?

Short answer

After some tests (see last link at bottom), we see that we can be dispensed of the XMLHttpRequest object to load data on the server, or run scripts on the server side, this from JavaScript. And the asynchronous mode adds the same fluidity allowed by Ajax.
So it is an alternative to Ajax, but limited. And to use XML files, we must add a support to this format while it is natively implemented in the XHR object.

Long answer

JavaScript can execute PHP scripts and load data on the server. Detailed example ...

Reading data on the server

The JavaScript file contains PHP code, it has the PHP extension:

<script src="javascript.php" type="text/javascript"></script>

The HTML page uses the function hello that is defined in the JavaScript file:

<form name="form1" method="post" action="">
<input type="button" name="Submit" value="message" onclick="hello()">

The javascript.php script file contains PHP code:

<?php $x="Hello World!"; ?>
function hello()
alert("<?php echo $x ?>");

The PHP code is executed on the server before the JavaScript file is loaded. It can be developed to access files or a database on the server and return the results.

Passing parameters

The XMLHttpRequest object can send data to a server side script. The same is done with a simple HTML form.

<form name="form1" method="post" action="script.php">
  <input type="text" name="message" value="my message">
<input type="submit" name="Submit" value="Send">

Script.php retrieves the form data:

$y = $_POST['message'];

The script that receives data can then perform a processing that will produce files dynamically reusable in the HTML page. This will not be as simple as with Ajax.


Asynchronous JavaScript is an alternative to Ajax in some cases and is a way to lighten the pages. It does not allow full interactivity with the server as does the XMLHttpRequest object.

More infos
© 2009-2012