File "script.js"
Full Path: /home/ccipcixf/public_html/offline/script.js
File size: 2.85 KB
MIME-type: text/plain
Charset: utf-8
// script.js
document.getElementById('dataForm').addEventListener('submit', function(event) {
event.preventDefault();
const formData = {
name: document.getElementById('name').value,
email: document.getElementById('email').value,
};
if (navigator.onLine) {
sendDataToServer(formData);
} else {
saveDataOffline(formData);
alert('You are offline. Data saved locally and will be sent when you are online.');
}
// Clear input fields
document.getElementById('name').value = '';
document.getElementById('email').value = '';
});
function sendDataToServer(data) {
fetch('https://ccipk.com/offline/submit.php', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(result => {
console.log('Success:', result);
alert('Data submitted successfully.');
localStorage.removeItem('offlineData');
})
.catch(error => {
console.error('Error:', error);
saveDataOffline(data);
alert('Error submitting data. Data saved locally and will be sent when you are online.');
});
}
function saveDataOffline(data) {
let offlineData = JSON.parse(localStorage.getItem('offlineData')) || [];
offlineData.push(data);
localStorage.setItem('offlineData', JSON.stringify(offlineData));
}
function syncOfflineData() {
const offlineData = JSON.parse(localStorage.getItem('offlineData')) || [];
if (offlineData.length === 0) {
return;
}
function sendNext() {
if (offlineData.length === 0) {
alert('All offline data has been sent.');
localStorage.removeItem('offlineData');
return;
}
const data = offlineData.shift();
fetch('https://ccipk.com/offline/submit.php', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(result => {
console.log('Success:', result);
sendNext();
})
.catch(error => {
console.error('Error:', error);
offlineData.unshift(data); // Re-add the data to the front of the queue
alert('Error syncing offline data. Will retry when online.');
});
}
sendNext();
}
window.addEventListener('online', syncOfflineData);