Skip to content

Instantly share code, notes, and snippets.

@egorvinogradov
Created February 3, 2013 15:45
Show Gist options
  • Save egorvinogradov/4702227 to your computer and use it in GitHub Desktop.
Save egorvinogradov/4702227 to your computer and use it in GitHub Desktop.
function ajax(params){
var request = new XMLHttpRequest();
var responseTimer;
function handleError(e){
console.error('Can\'t load data:', e.message, e);
params.error && params.error(e);
};
request.open(params.method || 'GET', params.url, true);
request.onreadystatechange = function(){
if ( request.readyState === 4 ) {
if ( request.status === 200 ) {
if ( params.success ) {
try {
var json = JSON.parse(request.responseText);
params.success(json);
}
catch(e){
params.success(request.responseText);
}
}
}
else {
handleError({
message: 'Bad request',
data: request
});
}
clearTimeout(responseTimer);
}
};
request.send(params.data || null);
responseTimer = setTimeout(function(){
request.abort();
handleError({
message: 'Time is over'
});
}, 10000);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment