Simple AJAX code to Fill DIV tag with text from server
Post by efox | Date: 2008-08-31
This is the simplest AJAX code that allows you to get text from the server on an onclick and fill a div with it. Good base code to start from.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8"/>
<title>Javascript</title>
<style type="text/css">
#content {
width: 400px;
height: 200px;
border: 1px solid #555;
padding: 10px;
overflow: auto; /* produces scroll effect */
margin-bottom: 5px;
}
</style>
<script type="text/javascript">
//variables
var request = null;
//initialize
window.onload = function() {
document.getElementById("button").onclick = function() {
request = createRequest();
request.onreadystatechange = complete;
request.open("GET", "log.txt", true);
request.send(null);
}
}
function complete() {
switch(request.readyState) {
case 0:
case 1:
case 2:
case 3: return;
case 4: var out = request.responseText; break;
}
//variables
var content = document.getElementById("content");
//change text
content.innerHTML = out;
}
function createRequest() {
try {
//mozilla browsers
var request = new XMLHttpRequest();
} catch(ex) {
try {
//newer internet explorers
var request = new ActiveXObject("MSXML2.XMLHTTP");
} catch(ex) {
//older internet explorers
var request = new ActiveXObject("Microsoft.XMLHTTP");
}
}
return request;
}
</script>
</head>
<body>
<div id="content"></div>
<button id="button">Get Log File Text</button>
</body>
</html>





Previous
Next
Tags: