AJAX with JQuery example

From Knowledge Kitchen
Jump to: navigation, search


This example is for a simple web page with one link. One a user clicks that link, the browser makes an AJAX request to the server, i.e. a "background" request that does not require a full page reload in the browser. The AJAX request is for additional content from the server. Assuming the server responds with that content, the browser will make that additional content magically appear on the web page.

This example relies on the JQuery library, which simplifies the Javascript syntax. However this same functionality could, of course, be done without using JQuery.

Main page

Save this in an HTML file called index.html:

<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="utf-8" />
		<title>JQuery Example</title>
		<link type="text/css" href="css/main.css" rel="stylesheet" />
		<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
		<script type="text/javascript">
$(document).ready(function() {
	$("a#the_link").click(function() {
		$("div#foo").load("_additional_content.html");
	});
});		
		</script>		
	</head>
	<body>
		<h1>Simple Ajax Example</h1>

		<a href="#" id="the_link">click here to perform an AJAX request</a>

		<div id="foo">additional content from the server will go here.</div>
	</body>
</html>

Additional content hosted on server

This file represents the additional content that the browser will request via AJAX.

Save this into a file named _additional_content.html:

here is the additional stuff

What links here