Reputation: 168
here is the scenario: There is a questioner that includes 3 questions and each question has 4 multiple answers. User will select an answer to each question and these data is stored in a hidden form in labels, i.e.
<label id=q1>A</label>
<label id=q2>C</label>
<label id=q3>D</label>
Now in case the device is connected to the internet these data can easily be submitted but in case the device has no internet, I need to find a way to store the label data on user's device and then next time there is a connection, the application to have a submit button which will submit all the stored data (every time the questioner is answered).
Thanks
Upvotes: 1
Views: 2487
Reputation: 6371
What I would do is saving the data in localStorage (although this link points to Phonegap Docs, localStorage is a Html5 feature, quite useful) and periodically calling a function that would check if there's something to send.
So, to check the network connection availability:
function isOnline(){
try{
var status = navigator.network.connection.type;
var val = (status != 'none' && status != 'unknown');
return val;
}catch(err){ console.error('isOnline(): '+err); return false; }
}
Include these lines of code to add some functionality to localStorage, as it just allow to save strings, but with these two functions it will be capable to store JSON data too:
Storage.prototype.setObject = function(key, value) {
this.setItem(key, JSON.stringify(value));
}
Storage.prototype.getObject = function(key) {
var value = this.getItem(key);
return value && JSON.parse(value);
}
In your form submit handler, just check if there is connection. If there's not, save the data to be sent:
if(isOnline()){
// do stuff
}else{
var data = // The data to be sent
var toBeSent = localStorage.getObject('toBeSent') || [];
toBeSent.push(data); // It's better to store the data in an array, in case there's more than a questioner to be sent
localStorage.setObject('toBeSent', toBeSent);
}
After that write a function that checks and sends the data:
function sendPending(){
var toBeSent = localStorage.getObject('toBeSent') || [];
var data;
for(var i in toBeSent){
data = toBeSent[i];
// send data
}
// Remove the list
localStorage.removeItem('toBeSent');
}
Finally, to execute the function periodically:
setInterval(sendPending, 60000); // The system will check every minute if there's something to send
Upvotes: 3