Skip to content

Instantly share code, notes, and snippets.

@martinandersen3d
Forked from azproduction/LICENSE.txt
Created May 1, 2018 23:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save martinandersen3d/60ad87d64c1d65fb2f7d2bc9b27fa96a to your computer and use it in GitHub Desktop.
Save martinandersen3d/60ad87d64c1d65fb2f7d2bc9b27fa96a to your computer and use it in GitHub Desktop.
Tiny ajax

Tiny ajax: xhr get, post, whatever - for modern browsers in 130 bytes

function tiny_ajax(method, url, callback, post_data) {/* ... */}

// asynch call
tiny_ajax('get', '.', function (xhr) {
    console.log(xhr.responseText);
});

tiny_ajax('post', '.', function (xhr) {
    console.log(xhr.responseText);
}, 'data');

// synch call
var xhr = tiny_ajax('get', '.');

var xhr = tiny_ajax('post', '.', 0, 'data');

Demo: http://jsfiddle.net/y3msq/

There is also crossbrowse one, but 155 bytes long

function(m,u,c,d){with(new(this.XMLHttpRequest||ActiveXObject)("Microsoft.XMLHTTP"))onreadystatechange=function(){readyState^4||c(this)},open(m,u),send(d)}
function(
m, // method - get, post, whatever
u, // url
c, // [callback] if passed -> asych call
d, // [post_data]
x
){
with(x=new XMLHttpRequest)
return onreadystatechange=function(){ // filter only readyState=4 events
readyState^4||c(this) // if callback passed and readyState == 4 than trigger Callback with xhr object
},
open(m,u,c), // open connection with Method and Url and asyCh flag
send(d), // send Data
x
}
function(m,u,c,d,x){with(x=new XMLHttpRequest)return onreadystatechange=function(){readyState^4||c(this)},open(m,u,c),send(d),x}
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
Version 2, December 2004
Copyright (C) 2011 Mikhail Davydov <azazel.private@gmail.com>
Everyone is permitted to copy and distribute verbatim or modified
copies of this license document, and changing it is allowed as long
as the name is changed.
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. You just DO WHAT THE FUCK YOU WANT TO.
{
"name": "tiny_ajax",
"description": "Tiny ajax: xhr get, post, whatever... for modern browsers",
"keywords": [
"xhr",
"get",
"post",
"tiny",
"ajax"
]
}
<!DOCTYPE html>
<title>Tiny xhr</title>
<div>Expected value: <b>pass</b></div>
<div>Actual value: <b id="ret">loading...</b></div>
<script>
var tiny_ajax = function(m,u,c,d){with(new XMLHttpRequest)onreadystatechange=function(){readyState^4||c(this)},open(m,u),send(d)};
tiny_ajax('get', '.', function (xhr){
document.getElementById( "ret" ).innerHTML = "pass";
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment