Skip to content

Instantly share code, notes, and snippets.

@romidane
Last active September 19, 2015 21:56
Show Gist options
  • Select an option

  • Save romidane/d98e587550d13eaf7e11 to your computer and use it in GitHub Desktop.

Select an option

Save romidane/d98e587550d13eaf7e11 to your computer and use it in GitHub Desktop.
Simple cached HTTP requests with Jquery Supports both GET and POST with data
function fetchData(url, options, cb){
if(!cb) throw new Error('Please suply a callback function!');
if(!fetchData._cache) fetchData._cache = {};
var settings = {
method: "GET",
url: url
}
extend(settings, options);
if(!fetchData._cache[url]){
$.ajax(settings)
.done(function(data){
fetchData._cache[url] = data;
cb(null,data);
})
.fail(function(jqXHR, textStatus, errorThrown){
var errData = {
jqXHR: jqXHR,
textStatus:textStatus,
errorThrown:errorThrown
};
cb(errData, null);
})
} else{
cb(null,fetchData._cache[url]);
}
}
function extend(source, target) {
if (!target) return;
// All or nothing approach
for( var key in target ) {
if(target.hasOwnProperty(key)){
source[key] = target[key];
}
}
}
//Example using Defaults
fetchData("http://someurl.com", null, function(err, data){
if(err) {
// do something about it
}
//No errors? Sweet let do some work!
//...
})
//Example using options overide
fetchData("http://someurl.com", { method: 'post'}, function(err, data){
if(err) {
// do something about it
}
//No errors? Sweet let do some work!
//...
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment