Call (877) SITE-OPT (748-3678)

Code: jQuery Ajax library version of Hello World

Chapter 8 - Ajax Optimization

Here we show the jQuery version, which is even terser:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>JQuery Hello Ajax World</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">

function responseCallback(responseXML)
{
    var msg = responseXML.getElementsByTagName('message')[0].firstChild.nodeValue;
    $('#output').html(msg);
}

$(document).ready(function( ){
$('#button1').click(function( ){$.get("sayhello.php", responseCallback);});
});
//-->
</script>
</head>

<body>
<form action="#">
    <input type="button" value="Say it!" id="button1" />
</form>

<br /><br />
<div id="output"> </div>

</body>
</html>

If we desired, we could make the jQuery JavaScript code quite small by chaining even further, as shown here:

$(document).ready(function( ){$('#button1').click(function( ){$.get("sayhello.php",
function(responseXML){$('#output').html(responseXML.
getElementsByTagName('message')[0].firstChild.nodeValue;)};);});});

This shows how quickly you can start to optimize your code size with jQuery.

Copyright © 2002-2017 Website Optimization, LLC. All Rights Reserved - Free website speed test - Privacy Policy
Last modified: February 19, 2009.

Follow us on: Twitter, Google+, Facebook, Linked In