how to save the state of a page after F5 - php

How can I save the state of a page after to press F5.(with php or javascript)
I have this page, which if I I press the button 1, div 1 disappears, and if you press the div 1 again, it reappears.
the button 2 has the same function.
is there any way that if I press button 1(or button2) disappears the div, and then if I press F5 continue the div1(or div2) hidden, ??
<input type="submit" id="button1" name="button1" value="ID1"><br/>
<div id="div1" name="div1"/>
<b>Hello1</b><br>
<img src="pic1.png" height="100px" width="100px" />
</div>
<input type="submit" id="button2" name="button2" value="ID2"><br/>
<div id="div2" name="div2"/>
<b>Hello2</b><br>
<img src="pic2.png" height="100px" width="100px" />
</div>
<script>
$(document).ready(function(){
$("#button1").toggle(function(){
$("#div1").hide();
},
function(){
$("#div1").show();
});
});
//
$(document).ready(function(){
$("#button2").toggle(function(){
$("#div2").hide();
},
function(){
$("#div2").show();
});
});
</script>
Thanks in Advance

Well Cookies could do the trick of saving the last state and so on.
If you aren't sure that html5 is available on all browsers.

one way is to use HTML5 history for this.
var state = { div1: true, div2: false };
history.pushState(state, 'Page', 'mypage/10');

Local Storage
When you want to save localy great amount of data, you have another opportunity — to use local storage (since HTML5). You can do it directly using JavaScript or using one of available jQuery plugins.
for example, with totalStorage:
var scores = new Array();
scores.push({'name':'A', points:10});
scores.push({'name':'B', points:20});
scores.push({'name':'C', points:0});
$.totalStorage('scores', scores);

Related

Window popup to refresh base file when a text a submited?

In my base page index.php I make use of this
SHOW
to open a dialog window that has a form and allow me to submit some text using PHP.
The Show link does not change, you click it, the window opens and may have some data in it.
When I submit something to the dialog.php how can I refresh the index.php?
My goal is to show that data to the index.php
Thank you
UPDATE
I added this to the dialog.php
<script>
window.onunload = refreshParent;
function refreshParent() {
window.opener.location.reload();
}
</script>
and when I close the window it refreshes the parent page.
Is there a way to make it happen when the
<input type="submit" name="submit" class="button" id="submit_btn" value="ADD">
is submited?
Just add your function, refreshParent() to an onclick event for the submit button.
<input onclick="refreshParent()" type="submit" name="submit" class="button" id="submit_btn" value="ADD">
Note that using 'onclick' tags is generally discouraged. A better way would be to use addEventListener:
document.getElementById('submit_btn').addEventListener('click', function () {
refreshParent;
}, false);
Or with JQuery:
$( "#submit_btn" ).click(function() {
refreshParent;
});

JS working locally, but not on webserver - any odd JS quirks I'm missing?

First, let's get this out of the way:
No errors (JS, etc) exist on the local and remote dev page. The jQuery lib is also called correctly.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
Basically both pages are identical.
What I'm trying to have my webpage achieve:
Submit my form if the user (accidentally) clicks away on a link instead of using the normal form submit button.
Link:
<a class="arrow autoSaveLeft" href="<?php echo $prevWeekURL ?>">←</a>
<form>
// ...
<input type="submit" name="submit" class="submitForm" value="Update" />
</form>
JS (at bottom):
<script>
$(document).ready(function() {
$('.autoSaveLeft').click(function(event){
event.preventDefault();
$('.submitForm').click();
window.location = $(this).attr('href');
});
});
</script>
Any idea why this might fire correctly on MAMP (form is submitted and url is followed), but not when I try live on a shared host (form is NOT submitted, but url is followed)?
Thank you.
If you wanted to save your user's progress on a form before leaving, you'd have to submit the form without actually, submitting it via the browser. Thus you could use AJAX to send the information that's been provided so far, upon success - carry on with the href provided on the original .click() handler.
<a class="arrow autoSaveLeft" href="somepage.php">←</a>
<form id="userform">
<input type="submit" name="submit" class="submitForm" value="Update" />
</form>
<script>
$(document).ready(function() {
$(document).on('click', '.autoSaveLeft', function( event ) {
var $that = $(this);
event.preventDefault();
$.ajax({
type: "POST",
data: $('#userform').serialize(),
url: 'yourpostscript.php',
success: function(){
window.location.href = $that.attr('href');
}
});
});
});
</script>

jquery .submit() wont deliver data to php when in setTimeout

I am trying to add an effect to the login form and when the effects is done ( like 1 sec) it then goes to php.
I tried to make a setTimeout() function inside the .submit with e.preventDefault() so I can delay it for a sec but the problem is it didnt take the data but instead it goes to the php in a blank webpage that sopposed to be checking the data that was inputted.
And when the e.preventDefault() is been taken away the php works but it didnt give me a second to perform the animation first then go to php file to check all the data
here is my code
<script> $("#effectsExplode").submit(function (e) {
var form = this;
e.preventDefault();
$("#effectsExplode").toggle("explode");
setTimeout(function () {
form.submit();
},1000);
});
</script>
<form id="effectsExplode" class="form-1" method="post" action="checklogin.php">
<p class="field">
<input type="text" name="login" placeholder="Username or email">
<i class="icon-user icon-large"></i>
</p>
<p class="field">
<input type="password" name="password" placeholder="Password">
<i class="icon-lock icon-large"></i>
</p>
<p class="submit">
<button id="buttonexplode" type="submit" name="loginsubmit">
<i class="icon-arrow-right icon-large"></i>
</button>
</p>
</form>
You've created an infinite loop. If for example I had a button and this javascript:
$('button').click(function() {
var b = this;
$('#status').append('Clicked<br/>');
setTimeout(function() {
b.click();
}, 1000);
});
http://jsfiddle.net/b9chris/yaNdc/
Once I click that button, I'll get another "Clicked" message appended to that status tag every second... forever. That's because jquery fires all its event handlers for the events you manually trigger; in this case you attached to 'submit' then fired 'submit' and looped right back into your own code, which keeps preventing the form from ever actually submitting.
Most likely on your local test machine this form submission happens almost instantly, but once you put it out on the webserver the live version will take longer, and your animation will have time to play. Simplest solution is to just get rid of the ev.preventDefault() and let it submit and play while the submission takes its time.

launching a jquery pop up window on html form submit?

can anyone please help. i have this login form:
<form id="myform" form action="login.php" method="post" class="loginform">
Email
<input type="text" name="email" maxlength="30" />
Password
<input type="password" name="password" maxlength="30" />
<input type="image" src="../PTB1/assets/img/icons/loginarrow1.png" name="submit" class="loginbutton" value="Login" />
</form>
i also have this script which brings up the form action page "login.php" in a popup window when my form is submitted.
at the moment it brings up a basic pop up window but i want to know if i can tweak the jquery code to implement a jquery lightbox window which opens up instead.
heres the jquery code that launches the pop up window when my login form is submitted.
<script>
$(document).ready(function() {
$('#myform').submit(function() {
window.open('', 'formpopup', 'width=400,height=400');
this.target = 'formpopup';
});
});
</script>
but now i want to have this pop up window open using my jquery lightbox window which is called "shadowbox" (available to download on the net) which you would normally open your links with like so.
<a href="link" rel="shadowbox;height=300;width=500" >link</a>
so just to be clear, i am asking if there is a way to launch my jquery lightbox "shadowbox" in place of the normal pop up window which is being launched when the user clicks the submit button on the login form.
Please can someone show me a way of doing this. thank you.
I would add e.preventDefault() to the previous statement
$(function() {
$('#myform').submit(function(e) {
e.preventDefault();
this.target = 'formpopup';
Shadowbox.open({
content: 'link',
height: 300,
width: 500
});
});
});
$(function() {
$('#myform').submit(function() {
this.target = 'formpopup';
Shadowbox.open({
content: 'link',
height: 300,
width: 500
});
});
});

How to display content within modal window?

I have a simple application here (QandATable2.php) where when the user clicks on the plus button, it will open a modal window and it displays the details which is stored in another page (previousquestions.php).
Now the problem I have is that if you straight away click on the "Search" button when the textbox is blank, you will see that it loads the page on its own page, displaying the message to enter in a phrase for the search and it also displays all of the features previously from the modal window into that page as well. This is incorrect.
What I want it to do is that if the user has clicked on the search button, then when it post's the form and outputs the message, it does it within the modal window, not on its own whole page. So does anyone know how this can be acheived?
The modal window I am using is known as SimpleModal and it's website is here
Below is the QandATable2.php code where it displays the plus button and where it opens the modal window, linking the content of the modal window to the previousquestions.php page:
<script type="text/javascript">
function plusbutton()
{
$.modal( $('<div />').load('previousquestions.php #previouslink') );
return false;
}
</script>
<h1>CREATING QUESTIONS AND ANSWERS</h1>
<table id="plus" align="center">
<tr>
<th>
<a onclick="return plusbutton();">
<img src="Images/plussign.jpg" width="30" height="30" alt="Look Up Previous Question" class="plusimage"/>
</a>
<span id="plussignmsg">(Click Plus Sign to look <br/> up Previous Questions)</span>
</th>
</tr>
</table>
Below is the previousquestions.php code, where it displays the details in the modal window and where the search feature is stored:
<?php
foreach (array('questioncontent') as $varname) {
$questioncontent = (isset($_POST[$varname])) ? $_POST[$varname] : '';
}
?>
<div id="previouslink">
<button type="button" id="close" onclick="return closewindow();">Close</button>
<h1>PREVIOUS QUESTIONS</h1>
<p>Search for a previous question by entering in a phrase in the search box below and submitting the phrase</p>
<form action="previousquestions.php" method="post">
<p>Search: <input type="text" name="questioncontent" value="<?php echo $questioncontent; ?>" /></p>
<p><input id="searchquestion" name="searchQuestion" type="submit" value="Search" /></p>
</form>
</div>
<?php
//...connected to DB
if (isset($_POST['searchQuestion'])) {
$questionquery = "SELECT QuestionContent FROM Question
WHERE(QuestionContent = '".mysql_real_escape_string($questioncontent)."')";
if (empty($questioncontent)){
echo "Please enter in a phrase in the text box in able to search for a question";
}
?>
You'll probably want to use AJAX, since you're already using jQuery you'll just need something like this:
// override the "default" form submitting behavior with a callback function
$("form").submit(
// this is the callback function for your form submit function.
function(e)
{
// this prevents the page from reloading -- very important!
e.preventDefault();
// get the search data from the input textbox
var s = $("input[name='questioncontent']").val();
// see annotation
$("#simplemodal-data").html("loading...")
.load("previousquestions.php #previouslink",
{
questioncontent : s,
searchQuestion : "Search"
}
);
}); // end submit wrapper
This will send the value to the server and load it in the div with id simplemodal-data
Annotation:
The last line in the code does several things. First, it replaces the simplemodal DIV with a "loading" message. At the same time, it makes a POST request to your previousquestions.php page. This part { questioncontent : s, searchQuestion : "Search"} is where the data from the form gets passed to the PHP page, (remember the variable var s assignment above. Lastly, the results from the previousquestions.php page should be loaded in the simplemodal-data modal window.
One thing that's missing is to add #previousquestions in the load method so that only a portion of your HTML document gets inserted in the modal. It's never a good idea to load an entire HTML page inside another HTML document, and "load" is designed to allow you to just pick the part of the document you want to insert, which is just that DIV.
I added "#previouslink" after the php filename. This is where the magic happens. The browser knows to extract that DIV from your PHP file and insert just that part on the page, no <head> <body> or any of the unneeded markup.
You can achieve what you're looking for by using AJAX to submit the form instead of using the default behavior where the page reloads with the new content. You can't use modal.load because you need to POST data in the request in order to get the appropriate response.
However, when using AJAX to post your data, you can take the response as HTML and add that HTML to a DIV on your page, and then invoke the SimpleModal command on that DIV container.
First, modify the submit button on your form so that it's type="button" instead of type="submit". This will prevent the form from submitting and redirecting the page. Alternatively, you could add event.preventDefault(); and return false to the form submit click handler (see the second step), but it's probably easier to try this method while you're making the changes:
Step 1:
<!-- change type to button -->
<input id="searchquestion" name="searchQuestion" type="button" value="Search" />
Step 2:
Create a handler for the form button, which uses serializeArray to serialize the form into a string and then POST it to the server. In the success callback handler, you'll then take the HTML response and replace the content in the modal window with the new HTML. This also catches errors, if any, and alerts them and writes them to the console:
$('form[type="button"]').click(function() {
var dataString = $('form').serializeArray();
$.ajax({
url: "/previousquestions.php?t="+new Date().getTime(),
type: "POST",
data: dataString,
context: document.body,
success: function(data){
alert(data); // results from server, either the HTML page, or JSON/XML
$('simplemodal-data').html(data); // if HTML, just insert into div#results
},
error: function(jqXHR, textStatus, errorThrown) {
if(window.location.hostname == "localhost") {
alert("Error submitting the form :: " + textStatus + " : " + errorThrown);
}
console.error("Error submitting the form :: " + textStatus + " : " + errorThrown);
}
});
});
Step 3:
Lastly, be sure that your previousquestions.php code returns only a partial HTML document, not a full HTML document. Since you're injecting HTML into an existing page, you don't need the <html>, <head>, or <body> sections. These will just cause your page to not validate, and may cause undesired behavior in legacy browsers. Here is an example of what your response might look like:
<div id="previouslink">
<button type="button" id="close" onclick="return closewindow();">Close</button>
<h1>PREVIOUS QUESTIONS</h1>
<p>Search for a previous question by entering in a phrase in the search box below and submitting the phrase</p>
<form action="previousquestions.php" method="post">
<p>Search: <input type="text" name="questioncontent" value="test" /></p>
<p><input id="searchquestion" name="searchQuestion" type="submit" value="Search" /></p>
</form>
</div>
<p>
Your Search: 'test' </p>
<p>Number of Questions Shown from the Search: <strong>0</strong></p><p>Sorry, No Questions were found from this Search</p>
I have found out from an answer on another page to a similar question to this that like Bergi has stated, it is easier using an iframe than using ajax to keep content displayed within a modal window. So the best answer for this question is below where it shows how an iframe is used for the question above:
function plusbutton() {
// Display an external page using an iframe
var src = "previousquestions.php";
$.modal('<iframe src="' + src + '" style="border:0;width:100%;height:100%;">');
return false;
}

Categories