Skip to content

Instantly share code, notes, and snippets.

@OscarGodson
Created September 21, 2011 19:03
Show Gist options
  • Save OscarGodson/1232995 to your computer and use it in GitHub Desktop.
Save OscarGodson/1232995 to your computer and use it in GitHub Desktop.
A quick and dirty way to prototype AJAX
/**
* fakejax is a simple way to prototype AJAX. It will give you a random response time of 0-3 seconds
* and it will also give you a 1 in 10 chance of returning an error
* @param {String} dummyCall This is the fake path like "/api/users"
* @param {Object} returnThis This is what you want it to return if it's successful like {data:'hi'}
* @param {Function} callback This is the callback to your AJAX after it completes
* @example http://jsbin.com/oguyoz/5
*/
var fakejax = function(dummyCall,returnThis,callback){
dummyCall = dummyCall || '';
returnThis = returnThis || '{"data":"Hello World"}';
callback = callback || function(){};
if(typeof returnThis == 'function'){
callback = returnThis;
}
var failed = Math.floor(Math.random()*11) //Fake the error (1 in 10 chance)
, processTime = (Math.floor(Math.random()*3))*1000; //0-3 second response time
console.log('Process time will be: '+ processTime + ' seconds');
setTimeout(function(){
if(failed !== 0){
callback.call(this,returnThis);
}
else{
console.error('Fakejax failed');
callback.call(this,{"error":0});
}
},processTime);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment