I have a webpage which is in some state currently, that is, some divs are shown and some are hidden. I am using cookies to post data to Python CGI scripts. So now, when I click a button, I want it to send data to the python cgi file, and so, I want the button reload the page, so that, due to reloading the cookie can be updated and thus, the updated cookie can be sent to the python-cgi file. (Also, I am using iframe to display the python-cgi file inside my html webpage).
Now, the methods such as location.load() doesn't work as it reloads the webpage into the initial state where all my divs were hidden but I want it to be in the same state as before reloading where some divs were shown and some were hidden.
How can I achieve that? Please help me with that! Thanks!
The are two solutions I can think of to this problem:
You can write a JavaScript function for when the button is clicked. And another one for when the page is loaded. Using the localStorage API, you can then save the current state of the page.
function buttonClickedEvent() {
const div1Visible = !document.querySelector('#div1').hidden || true;
const div2Visible = !document.querySelector('#div2').hidden || true;
const userInput = document.querySelector('#user-input').value || '';
localStorage.setItem('page-state', JSON.stringify({
div1Visible,
div2Visible,
userInput
}));
window.location.href = '/path/on/server';
}
function setupPage() {
const state = localStorage.getItem('page-state');
let stateObj;
try {
stateObj = JSON.parse(state);
} catch (e) {
return;
}
document.querySelector('#div1').hidden = !stateObj.div1Visible;
document.querySelector('#div2').hidden = !stateObj.div2Visible;
document.querySelector('#user-input').value = stateObj.userInput;
}
With the following HTML:
<body onload='setupPage()'>
<button onClick='buttonClickedEvent()'>
Click Me
</button>
</body>
What I would recommend you do instead, is rewrite your server code such that it is a REST API, rather than using HTTP redirects. Then on the frontend, instead of changing the page, you use a library such as Axios to create HTTP requests:
axios.get('/path/on/server', (response) => {
if (response.status === 200) { // HTTP success
// Code to run upon successful response
}
});
Please let me know if there is anything you would like me to clarify.