Skip to content

Instantly share code, notes, and snippets.

@joechan3
Created April 23, 2016 04:10
Show Gist options
  • Save joechan3/7a8097e1551ec78c78973d4deca726f0 to your computer and use it in GitHub Desktop.
Save joechan3/7a8097e1551ec78c78973d4deca726f0 to your computer and use it in GitHub Desktop.
Ajax Example from Lynda: JavaScript Essential Training
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div id="mainContent">
<h1>This is an AJAX Example</h1>
</div>
<script src="script_finished.js"></script>
</body>
</html>
// Simple Ajax example.
// 1: Create the request
var myRequest;
// feature check!
if (window.XMLHttpRequest) { // does it exist? we're in Firefox, Safari etc.
myRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) { // if not, we're in IE
myRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
// 2: create an event handler for our request to call back
myRequest.onreadystatechange = function(){
console.log("We were called!");
console.log(myRequest.readyState);
if (myRequest.readyState === 4) {
var p = document.createElement("p");
var t = document.createTextNode(myRequest.responseText);
p.appendChild(t);
document.getElementById("mainContent").appendChild(p);
}
};
// open and send it
myRequest.open('GET', 'simple.txt', true);
// any parameters?
myRequest.send(null);
//....
This is the contents of a simple text file.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment