Skip to content

Instantly share code, notes, and snippets.

@RimonEkjon
Forked from rajasika/localStorage_example2.js
Created August 26, 2014 04:13
Show Gist options
  • Save RimonEkjon/f35f2a6067246fc2f9c2 to your computer and use it in GitHub Desktop.
Save RimonEkjon/f35f2a6067246fc2f9c2 to your computer and use it in GitHub Desktop.
// 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