PHP Simple AJAX example     

AJAX is really powerful. You can have the server rewrite part of a page, or parse it's response, or just about anything else you would normally do with a full page reload.

Here's an extremely simple example.

When you click on the link it makes a request to the server, and displays the response in the box. The response page is at php_simple_ajax_target.html.

Example

Request Ajax
The response will go here

Code


<html><head>
<script language="javascript">
var http_request = false;
if (window.XMLHttpRequest) {
   http_request = new XMLHttpRequest();
} else if (window.ActiveXObject) {
   http_request = new ActiveXObject("Microsoft.XMLHTTP");
}
function do_ajax() {
   url = "php_simple_ajax_target.html";
//alert(url); // for debugging
   http_request.onreadystatechange = ajax_process;
   http_request.open("GET", url, true);
   http_request.send(null);
}
function ajax_process() {
   if (http_request.readyState == 4 && http_request.status == 200) {
//alert(http_request.responseText);
   document.getElementById("thediv").innerHTML = http_request.responseText;
//eval(http_request.responseText); // if you want to just execute the response, ie javascript (can be very dangerous)
   }
}
</script>
</head><body>
<p><a href="#" onclick="do_ajax(); return false;">Request Ajax</a>
<div id="thediv">The response will go here</div>
</body></html>

License:


This code is public domain, you are free to do whatever you want with it, including adding it to your own project which can be under any license.

  Site by Kallahar - kallahar@kallahar.com - Hosted by DreamHost