Web Development
Using PHP

Follow on
Twitter

AJAX

AJAX is a way to dynamically update a web page with content from the web server without having to reload the entire page. For more information on AJAX and its history, read the Wikipedia article on AJAX.

The example below replaces everything in the paragraph with the id "result" with the contents of the ajax/load.php file.

This is done using AJAX implemented via jQuery's load command.

<p>This is a small file</p>
<p id="foo">This is the foo paragraph</p>
<?php 
if( isset($_REQUEST['name'])) {
	echo "<p>Hi ".$_REQUEST['name']."!</p>";
}
?>
<html>
	<head>
		<script type="text/javascript" src="js/jquery.js"></script>
		<script type="text/javascript">
		$(document).ready(function(){
			var loadUrl = "ajax/load.php";
			$("#load_basic").click(function(){
				$("#result").load(loadUrl);
			});
		});
		</script>

		<title>Javascript sample</title>
	</head>
	<body>
		<p id="load_basic">Click me!</p>
		<p id="result">Stuff goes here</p>
	</body>
</html> 
			

Try it out: [link]

This next example simulates a page load that takes a long time, and shows the user a graphic while the page loads.

Note that the load_long.php file has a sleep command in it. This command causes the computer to pause for the number of specified seconds.

<?php 
echo "<p>This takes a while</p>";
sleep(10);
echo "<p id='foo'>This is the foo paragraph</p>"

?>
<html>
	<head>
		<script type="text/javascript" src="js/jquery.js"></script>
		<script type="text/javascript">
		// From http://www.freeiconsdownload.com/Free_Downloads.asp?id=585
		$(document).ready(function(){
			$.ajaxSetup ({
				cache: false
			});
			var ajax_load = "<img src='img/loading2.gif' alt='loading...' />";

//			load() functions
			var loadUrl = "ajax/load_long.php";
			$("#load_basic").click(function(){
				$("#result").html(ajax_load).load(loadUrl);
			});
			
		});
		</script>

		<title>Javascript sample</title>
	</head>
	<body>
		<p id="load_basic">Click me!</p>
		<p id="result">Stuff goes here</p>
	</body>

</html> 
			

Try it out: [link]

Sometimes only part of a page is desired. This next example pulls the entire ajax/load.php across the network, but only uses the paragraph with the id of foo.

<html>
	<head>
		<script type="text/javascript" src="js/jquery.js"></script>
		<script type="text/javascript">
		$(document).ready(function(){
			var loadUrl = "ajax/load.php";
			$("#load_basic").click(function(){
				$("#result").load(loadUrl+" #foo");
			});
		});
		</script>

		<title>Javascript sample</title>
	</head>
	<body>
		<p id="load_basic">Click me!</p>
		<p id="result">Stuff goes here</p>
	</body>

</html> 
			

Try it out: [link]

It is possible to send parameters to the page that is being pulled via AJAX. This example sets the parameter name to the value fred.

<html>
	<head>
		<script type="text/javascript" src="js/jquery.js"></script>
		<script type="text/javascript">
		$(document).ready(function(){
			var loadUrl = "ajax/load.php";
			$("#load_basic").click(function(){
				$("#result").load(loadUrl,"name=fred");
			});
		});
		</script>

		<title>Javascript sample</title>
	</head>
	<body>
		<p id="load_basic">Click me!</p>
		<p id="result">Stuff goes here</p>
	</body>

</html> 
			

Try it out: [link]

A callback may also be used. Once the AJAX call has finished, additional JavaScript code may be run. This next example replaces the "Click me" with "Done" once the call has finished.

<html>
	<head>
		<script type="text/javascript" src="js/jquery.js"></script>
		<script type="text/javascript">
		$(document).ready(function(){
			var loadUrl = "ajax/load.php";
			$("#load_basic").click(function(){
				$("#result").load(loadUrl,null,function() {
					$("#load_basic").html("Done!");
				});
			});
		});
		</script>

		<title>Javascript sample</title>
	</head>
	<body>
		<p id="load_basic">Click me!</p>
		<p id="result">Stuff goes here</p>
	</body>

</html> 
			

Try it out: [link]

Sometimes the data returned from an AJAX call is not going to replace HTML elements on a page. This next example shows how to get the results on an AJAX call and use the results in other JavaScript code.

Rather than use jQuery's load command, this example uses the more complex and more flexible ajax command.

This also shows use of JavaScript's alert command for making alert boxes.

<html>
	<head>
		<script type="text/javascript" src="js/jquery.js"></script>
		<script type="text/javascript">
		$(document).ready(function(){
			var loadUrl = "ajax/load.php";
			$("#load_basic").click(function(){
				$.ajax({
					  url: loadUrl,
					  dataType: 'html',
					  data: ”,
					  success: function(data) {
						  alert(data);
					  }
					});
			});
		});
		</script>

		<title>Javascript sample</title>
	</head>
	<body>
		<p id="load_basic">Click me!</p>
		<p id="result">Stuff goes here</p>
	</body>

</html> 
			

Try it out: [link]

This next example is similar to the prior example, however only part of the returned data is used.

<html>
	<head>
		<script type="text/javascript" src="js/jquery.js"></script>
		<script type="text/javascript">
		$(document).ready(function(){
			var loadUrl = "ajax/load.php";
			$("#load_basic").click(function(){
				$.ajax({
					  url: loadUrl,
					  dataType: 'html',
					  data: ”,
					  success: function(data) {
						  var data2 = $(data);
						  var data3 = $(data2)[2];
						  alert(data3.textContent);
					  }
					});
			});
		});
		</script>

		<title>Javascript sample</title>
	</head>
	<body>
		<p id="load_basic">Click me!</p>
		<p id="result">Stuff goes here</p>
	</body>

</html> 
			

Try it out: [link]

This shows getting the resulting data in XML format, and using a loop to iterate through the data.

<?xml version="1.0"?>
<nutrition>

<daily-values>
	<total-fat units="g">65</total-fat>
	<saturated-fat units="g">20</saturated-fat>
	<cholesterol units="mg">300</cholesterol>
	<sodium units="mg">2400</sodium>
	<carb units="g">300</carb>
	<fiber units="g">25</fiber>
	<protein units="g">50</protein>
</daily-values>

<food>
	<name>Avocado Dip</name>
	<mfr>Sunnydale</mfr>
	<serving units="g">29</serving>
	<calories total="110" fat="100"/>
	<total-fat>11</total-fat>
	<saturated-fat>3</saturated-fat>
	<cholesterol>5</cholesterol>
	<sodium>210</sodium>
	<carb>2</carb>
	<fiber>0</fiber>
	<protein>1</protein>
	<vitamins>
		<a>0</a>
		<c>0</c>
	</vitamins>
	<minerals>
		<ca>0</ca>
		<fe>0</fe>
	</minerals>
</food>

<food>
	<name>Bagels, New York Style </name>
	<mfr>Thompson</mfr>
	<serving units="g">104</serving>
	<calories total="300" fat="35"/>
	<total-fat>4</total-fat>
	<saturated-fat>1</saturated-fat>
	<cholesterol>0</cholesterol>
	<sodium>510</sodium>
	<carb>54</carb>
	<fiber>3</fiber>
	<protein>11</protein>
	<vitamins>
		<a>0</a>
		<c>0</c>
	</vitamins>
	<minerals>
		<ca>8</ca>
		<fe>20</fe>
	</minerals>
</food>

<food>
	<name>Beef Frankfurter, Quarter Pound </name>
	<mfr>Armitage</mfr>
	<serving units="g">115</serving>
	<calories total="370" fat="290"/>
	<total-fat>32</total-fat>
	<saturated-fat>15</saturated-fat>
	<cholesterol>65</cholesterol>
	<sodium>1100</sodium>
	<carb>8</carb>
	<fiber>0</fiber>
	<protein>13</protein>
	<vitamins>
		<a>0</a>
		<c>2</c>
	</vitamins>
	<minerals>
		<ca>1</ca>
		<fe>6</fe>
	</minerals>
</food>

<food>
	<name>Chicken Pot Pie</name>
	<mfr>Lakeson</mfr>
	<serving units="g">198</serving>
	<calories total="410" fat="200"/>
	<total-fat>22</total-fat>
	<saturated-fat>9</saturated-fat>
	<cholesterol>25</cholesterol>
	<sodium>810</sodium>
	<carb>42</carb>
	<fiber>2</fiber>
	<protein>10</protein>
	<vitamins>
		<a>20</a>
		<c>2</c>
	</vitamins>
	<minerals>
		<ca>2</ca>
		<fe>10</fe>
	</minerals>
</food>

<food>
	<name>Cole Slaw</name>
	<mfr>Fresh Quick</mfr>
	<serving units=" cup">1.5</serving>
	<calories total="20" fat="0"/>
	<total-fat>0</total-fat>
	<saturated-fat>0</saturated-fat>
	<cholesterol>0</cholesterol>
	<sodium>15</sodium>
	<carb>5</carb>
	<fiber>2</fiber>
	<protein>1</protein>
	<vitamins>
		<a>30</a>
		<c>45</c>
	</vitamins>
	<minerals>
		<ca>4</ca>
		<fe>2</fe>
	</minerals>
</food>

<food>
	<name>Eggs</name>
	<mfr>Goodpath</mfr>
	<serving units="g">50</serving>
	<calories total="70" fat="40"/>
	<total-fat>4.5</total-fat>
	<saturated-fat>1.5</saturated-fat>
	<cholesterol>215</cholesterol>
	<sodium>65</sodium>
	<carb>1</carb>
	<fiber>0</fiber>
	<protein>6</protein>
	<vitamins>
		<a>6</a>
		<c>0</c>
	</vitamins>
	<minerals>
		<ca>2</ca>
		<fe>4</fe>
	</minerals>
</food>

<food>
	<name>Hazelnut Spread</name>
	<mfr>Ferreira</mfr>
	<serving units="tbsp">2</serving>
	<calories total="200" fat="90"/>
	<total-fat>10</total-fat>
	<saturated-fat>2</saturated-fat>
	<cholesterol>0</cholesterol>
	<sodium>20</sodium>
	<carb>23</carb>
	<fiber>2</fiber>
	<protein>3</protein>
	<vitamins>
		<a>0</a>
		<c>0</c>
	</vitamins>
	<minerals>
		<ca>6</ca>
		<fe>4</fe>
	</minerals>
</food>

<food>
	<name>Potato Chips</name>
	<mfr>Lees</mfr>
	<serving units="g">28</serving>
	<calories total="150" fat="90"/>
	<total-fat>10</total-fat>
	<saturated-fat>3</saturated-fat>
	<cholesterol>0</cholesterol>
	<sodium>180</sodium>
	<carb>15</carb>
	<fiber>1</fiber>
	<protein>2</protein>
	<vitamins>
		<a>0</a>
		<c>10</c>
	</vitamins>
	<minerals>
		<ca>0</ca>
		<fe>0</fe>
	</minerals>
</food>

<food>
	<name>Soy Patties, Grilled</name>
	<mfr>Gardenproducts</mfr>
	<serving units="g">96</serving>
	<calories total="160" fat="45"/>
	<total-fat>5</total-fat>
	<saturated-fat>0</saturated-fat>
	<cholesterol>0</cholesterol>
	<sodium>420</sodium>
	<carb>10</carb>
	<fiber>4</fiber>
	<protein>9</protein>
	<vitamins>
		<a>0</a>
		<c>0</c>
	</vitamins>
	<minerals>
		<ca>0</ca>
		<fe>0</fe>
	</minerals>
</food>

<food>
	<name>Truffles, Dark Chocolate</name>
	<mfr>Lyndon's</mfr>
	<serving units="g">39</serving>
	<calories total="220" fat="170"/>
	<total-fat>19</total-fat>
	<saturated-fat>14</saturated-fat>
	<cholesterol>25</cholesterol>
	<sodium>10</sodium>
	<carb>16</carb>
	<fiber>1</fiber>
	<protein>1</protein>
	<vitamins>
		<a>0</a>
		<c>0</c>
	</vitamins>
	<minerals>
		<ca>0</ca>
		<fe>0</fe>
	</minerals>
</food>

</nutrition>
<html>
	<head>
		<script type="text/javascript" src="js/jquery.js"></script>
		<script type="text/javascript">
		$(document).ready(function(){
			var loadUrl = "ajax/loadxml.php";
			$("#load_basic").click(function(){
				$.ajax({
					  url: loadUrl,
					  dataType: 'xml',
					  data: ”,
					  success: function(xml) {
						  $(xml).find('food').each(function(){
							  var name = $(this).find('name').text();
							  $("#result").append("<br />"+name);
						  });
					  }
					});
			});
		});
		</script>

		<title>Javascript sample</title>
	</head>
	<body>
		<p id="load_basic">Click me!</p>
		<p id="result">Stuff goes here</p>
	</body>

</html> 
			

Try it out: [link]

XML has started to fall out of favor in many website API's in favor of JSON. The jQuery web site shows how to do JSON queries.

You are not logged in. Log in here and track your progress.