Skip to content

Instantly share code, notes, and snippets.

@bevacqua
Last active December 18, 2015 03:59
Show Gist options
  • Save bevacqua/5722029 to your computer and use it in GitHub Desktop.
Save bevacqua/5722029 to your computer and use it in GitHub Desktop.
A CodePen by Nicolas Bevacqua. Bare XMLHttpRequest - A demonstration on how to perform an XMLHttpRequest without any added sauce.
html {
margin: 20px;
}
div, button {
font-size: 18px;
font-family: 'Georgia';
}
#response {
padding: 10px;
margin-bottom: 10px;
border: 2px solid #fcc;
background-color: #ececec;
display: inline-block;
}
#poller {
display: block;
cursor: pointer;
border: 2px solid #ff0;
background-color: #ffc;
border: none;
padding: 10px;
}
#poller:hover {
background-color: #ffff88;
}
<div id="response">...</div>
<button id="poller">Poll</button>
function url(){
return '/';
}
function poll(done){
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if(xhr.readyState === 4 && xhr.status == 200 ){
var foo = xhr.responseText;
done(foo);
}
};
xhr.open('get',url(),true);
xhr.send(null);
}
var button = document.querySelector('#poller');
var response = document.querySelector('#response');
button.addEventListener('click', function(){
response.innerText = '...';
poll(function(data){
button.innerText = 'Poll again';
response.innerText = data.substr(0, 180) + '\n...';
});
},false);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment