Skip to content

Instantly share code, notes, and snippets.

@rajasika
Created June 14, 2012 16:33
Show Gist options
  • Select an option

  • Save rajasika/2931356 to your computer and use it in GitHub Desktop.

Select an option

Save rajasika/2931356 to your computer and use it in GitHub Desktop.
Local Storage Example 2
// create a new dbStore stack
var myStack = localStack('myLocalStack');
function onFormSubmit(){
// push form data into local storage
myStack.push( $('form').serializeArray() );
// see if we can send data to the server
checkForConnection();
}
function checkForConnection(){
var ajax = new XMLHttpRequest();
var target = "http://mysite.com/upload.php";
// see if page is accessible
ajax.open("HEAD", target, true);
ajax.onreadystatechange = function(){
// if status is 200 we can access the page
if(ajax.readyState == 4 && ajax.status == 200) sendData();
}
ajax.send();
}
// run this function every 5 minutes to see if we obtained a connection
setInterval(checkForConnection, 5 * 60 * 1000);
function sendData(){
var ajax = new XMLHttpRequest();
var target = "http://mysite.com/upload.php";
ajax.onreadystatechange = function(){
if(ajax.readyState == 4){
if(ajax.status == 200 && ajax.responseText === 'OK'){
// request was processed successfully, continue sending
sendData();
}else{
// there was a problem; put data back into local storage
myStack.push(val);
}
}
}
// fire request
var val;
if(val = myStack.pop()){
ajax.open("POST", target, true);
ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajax.setRequestHeader("Content-length", val.length);
ajax.setRequestHeader("Connection", "close")
ajax.send(val);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment