| | |
PHP auto-save code
Please support our PHP advertiser: PostgreSQL or MySQL? Compare and contrast the two most popular open source databases
![]() |
I'm new to working with PHP and I am in need of some help. I am currently working on setting up a test using Dreamweaver so that users can log in, then go to the question page, and from there go to a page with a form to answer that question. I had the host up the garbage collection time from 24 minutes to 240, so that the user won't be timed out while working on the reply. I would like install a fail safe so they won't lose all their work. I found an auto-save code on http://jetlogs.org/2007/11/11/auto-saving-with-jquery/
I've been playing around with the code supplied from there, but so far no luck. Does anyone have any advice or is familiar at all with auto-saving with php? I appreciate any help, thanks.
I've been playing around with the code supplied from there, but so far no luck. Does anyone have any advice or is familiar at all with auto-saving with php? I appreciate any help, thanks.
•
•
Join Date: Dec 2007
Posts: 16
Reputation:
Solved Threads: 0
Post your code and I'll give you a hand. The auto-saving is easy to do, and there is no reason to use jQuery, if this is all you want to do. Note: I have not used jQuery myself in any significant way (nor Dreamweaver, for that matter), but I have written many scripts that implement various levels of auto-save functionality.
(Nor do you even need PHP to do specifically what you're asking. Using JavaScript, you can auto-save a cookie in the browser that will store the value, then send it across the wire when the user hits submit. I think it's a more elegant solution, but it would require little more coding (but not much)).
(Nor do you even need PHP to do specifically what you're asking. Using JavaScript, you can auto-save a cookie in the browser that will store the value, then send it across the wire when the user hits submit. I think it's a more elegant solution, but it would require little more coding (but not much)).
•
•
Join Date: Dec 2007
Posts: 16
Reputation:
Solved Threads: 0
here you go
edit: code does NOT save to a cookie, btw
edit: code does NOT save to a cookie, btw
php Syntax (Toggle Plain Text)
<?PHP /****************************************************************************** To be able to run this sample code, you need to have the mysql database and insert a dummy record: CREATE DATABASE autosave; CREATE TABLE asave( user_id INT, saved_text TEXT ); INSERT INTO asave(user_id, saved_text) VALUES (1, ''); ******************************************************************************/ //replace with your user/pass to get a connection to your database $db = mysql_connect("localhost:3306", "****" , "****"); mysql_select_db("autosave",$db) or die(mysql_error()); //your user_id is probably stored in your session...just replace $user_id = 1; if($_SERVER["REQUEST_METHOD"]=="POST"){ // Make sure you escape your saved data as you need it // It is not done here, in the interest of brevity $saved_text = mysql_real_escape_string($_POST["saved_text"]); // Assume an entry in the DB table exists for this user. $sql = "UPDATE asave SET saved_text = '".$saved_text."' "; $sql.= "WHERE user_id = $user_id"; mysql_query($sql) or die(mysql_error().$sql); echo "Your data has been saved ".date("h:m:s A"); exit; } //else implied by exit // Get saved_text from the DB to display in the textarea $sql = "SELECT saved_text FROM asave WHERE user_id = $user_id"; $rs = mysql_query($sql) or die(mysql_error().$sql); $arr = mysql_fetch_array($rs); $saved_text = $arr["saved_text"]; ?> <html> <head> <script type="text/javascript"> function init(){ window.setInterval(autoSave,10000); // 10 seconds } function autoSave(){ var saved_text = document.getElementById("saved_text").value; var params = "saved_text="+saved_text; var http = getHTTPObject(); http.onreadystatechange = function(){ if(http.readyState==4 && http.status==200){ msg = document.getElementById("msg"); msg.innerHTML = "<span onclick='this.style.display=\"none\";'>"+http.responseText+" (<u>close</u>)</span>"; } }; http.open("POST", window.location.href, true); http.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); http.setRequestHeader("Content-length", params.length); http.setRequestHeader("Connection", "close"); http.send(params); } //cross-browser xmlHTTP getter function getHTTPObject() { var xmlhttp; /*@cc_on @if (@_jscript_version >= 5) try { xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } catch (E) { xmlhttp = false; } } @else xmlhttp = false; @end @*/ if (!xmlhttp && typeof XMLHttpRequest != 'undefined') { try { xmlhttp = new XMLHttpRequest(); } catch (e) { xmlhttp = false; } } return xmlhttp; } </script> </head> <body onload="init();"> <span id="msg" style="cursor:pointer;"></span> <form method="POST"> <textarea id="saved_text" name="saved_text" rows="10" cols="100"><?PHP echo $saved_text;?></textarea> <br/> <input type="submit" value="save now" /> </form> </body> </html>
Last edited by bill mac; Dec 22nd, 2007 at 8:05 pm. Reason: note re: cookie
After doing some searching around forums some code I found that might work was
<script>
// auto-save the draft every 5 minutes
setInterval( "rcmail.command('savedraft','',null)", 5*60*60*1000 );
</script>
although I would have to change the "rcmail.command" portion to something that would fit my current project. And is there any way I could install a timer so that the user could see how much time remains on their session? Thanks for the help.
<script>
// auto-save the draft every 5 minutes
setInterval( "rcmail.command('savedraft','',null)", 5*60*60*1000 );
</script>
although I would have to change the "rcmail.command" portion to something that would fit my current project. And is there any way I could install a timer so that the user could see how much time remains on their session? Thanks for the help.
•
•
Join Date: Dec 2007
Posts: 16
Reputation:
Solved Threads: 0
•
•
•
•
After doing some searching around forums some code I found that might work was
<script>
// auto-save the draft every 5 minutes
setInterval( "rcmail.command('savedraft','',null)", 5*60*60*1000 );
</script>
But, that is essentially it.
1. Write the code that does the saving, 2. Call that code every 30 seconds (or whatever).
•
•
•
•
And is there any way I could install a timer so that the user could see how much time remains on their session? Thanks for the help.
Write a function that will use DHTML to decrement a visible timer and call that function every second.
html Syntax (Toggle Plain Text)
<html><head><script>
javascript Syntax (Toggle Plain Text)
var spanCounter = ""; // HTML elem that shows counter's value var counter; // An integer that just decrements var saveInterval = -1; // Auto-save frequency function init(si){ spanCounter = document.getElementById("spanCounter"); saveInterval = si; spanCounter.innerHTML = si; counter = si; setInterval(countDown, 1000); // once a second } function countDown(){ if(counter == -1){ counter = saveInterval; // reset the counter //autoSave(); // or whatever your function is named } spanCounter.innerHTML = (counter--); // decrement counter, and paint }
html Syntax (Toggle Plain Text)
</script></head> <body onload="init(5);"> <span id="spanCounter"><span> </body> </html>
mysql_query($sql) or die(mysql_error().$sql);
echo "Your data has been saved ".date("h:m:s A");
exit;
}
//else implied by exit
// Get saved_text from the DB to display in the textarea
$sql = "SELECT saved_text FROM asave WHERE user_id = $user_id";
$rs = mysql_query($sql) or die(mysql_error().$sql);
$arr = mysql_fetch_array($rs);
$saved_text = $arr["saved_text"];
?>
<html>
<head>
<script type="text/javascript">
function init(){
window.setInterval(autoSave,10000); // 10 seconds
}
function autoSave(){
var saved_text = document.getElementById("saved_text").value;
var params = "saved_text="+saved_text;
var http = getHTTPObject();
http.onreadystatechange = function(){
if(http.readyState==4 && http.status==200){
msg = document.getElementById("msg");
msg.innerHTML = "<span onclick='this.style.display=\"none\";'>"+http.responseText+" (<u>close</u>)</span>";
}
};
http.open("POST", window.location.href, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
http.send(params);
}
//cross-browser xmlHTTP getter
function getHTTPObject() {
var xmlhttp;
/*@cc_on
@if (@_jscript_version >= 5)
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (E) {
xmlhttp = false;
}
}
@else
xmlhttp = false;
@end @*/
if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
try {
xmlhttp = new XMLHttpRequest();
} catch (e) {
xmlhttp = false;
}
}
return xmlhttp;
}
</script>
</head>
<body onload="init();">
<span id="msg" style="cursor:pointer;"></span>
<form method="POST">
<textarea id="saved_text" name="saved_text" rows="10" cols="100"><?PHP echo $saved_text;?></textarea>
<br/>
<input type="submit" value="save now" />
</form>
</body>
</html>
[/code][/QUOTE]
Thanks for all your help so far! One problem that keeps occurring is that the autosave function only appears to work when I hit "save". I refresh the database and the text will be there, but only when save has been hit. If I was to remove the button, hypothetically the function would still work. Do you have any insight on why this is happening? Thanks.
echo "Your data has been saved ".date("h:m:s A");
exit;
}
//else implied by exit
// Get saved_text from the DB to display in the textarea
$sql = "SELECT saved_text FROM asave WHERE user_id = $user_id";
$rs = mysql_query($sql) or die(mysql_error().$sql);
$arr = mysql_fetch_array($rs);
$saved_text = $arr["saved_text"];
?>
<html>
<head>
<script type="text/javascript">
function init(){
window.setInterval(autoSave,10000); // 10 seconds
}
function autoSave(){
var saved_text = document.getElementById("saved_text").value;
var params = "saved_text="+saved_text;
var http = getHTTPObject();
http.onreadystatechange = function(){
if(http.readyState==4 && http.status==200){
msg = document.getElementById("msg");
msg.innerHTML = "<span onclick='this.style.display=\"none\";'>"+http.responseText+" (<u>close</u>)</span>";
}
};
http.open("POST", window.location.href, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
http.send(params);
}
//cross-browser xmlHTTP getter
function getHTTPObject() {
var xmlhttp;
/*@cc_on
@if (@_jscript_version >= 5)
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (E) {
xmlhttp = false;
}
}
@else
xmlhttp = false;
@end @*/
if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
try {
xmlhttp = new XMLHttpRequest();
} catch (e) {
xmlhttp = false;
}
}
return xmlhttp;
}
</script>
</head>
<body onload="init();">
<span id="msg" style="cursor:pointer;"></span>
<form method="POST">
<textarea id="saved_text" name="saved_text" rows="10" cols="100"><?PHP echo $saved_text;?></textarea>
<br/>
<input type="submit" value="save now" />
</form>
</body>
</html>
[/code][/QUOTE]
Thanks for all your help so far! One problem that keeps occurring is that the autosave function only appears to work when I hit "save". I refresh the database and the text will be there, but only when save has been hit. If I was to remove the button, hypothetically the function would still work. Do you have any insight on why this is happening? Thanks.
•
•
Join Date: Dec 2007
Posts: 16
Reputation:
Solved Threads: 0
Replace: with:
That should give you a good start of where to look. Anyway I can execute your code over the Internet?
javascript Syntax (Toggle Plain Text)
http.onreadystatechange = function(){ if(http.readyState==4 && http.status==200){ msg = document.getElementById("msg"); msg.innerHTML = "<span onclick='this.style.display=\"none\";'>"+http.responseText+" (<u>close</u>)</span>"; } };
javascript Syntax (Toggle Plain Text)
http.onreadystatechange = function(){ if(http.readyState==4){ if(http.status!=200){ // 200 = HTTP OK alert(http.responseText); }else{ msg = document.getElementById("msg"); msg.innerHTML = "<span onclick='this.style.display=\"none\";'>"+http.responseText+" (<u>close</u>)</span>"; } } };
That should give you a good start of where to look. Anyway I can execute your code over the Internet?
•
•
Join Date: Dec 2007
Posts: 16
Reputation:
Solved Threads: 0
•
•
•
•
One problem that keeps occurring is that the autosave function only appears to work when I hit "save". I refresh the database and the text will be there, but only when save has been hit. If I was to remove the button, hypothetically the function would still work. Do you have any insight on why this is happening? Thanks.
Hopefully the code I posted above this will let you know where the problem is. The code works on my setup, so I'll have to get some specific environment info from you, as well as any pertinent error messages.
Also, if you're not using Firefox w/ the Firebug extension (or Web Developer Toolbar), I highly recommend them. These tools help a lot when it comes to debugging javascript.
![]() |
Similar Threads
- Apache (Linux Servers and Apache)
- Popups, Virtumonde.O? (Viruses, Spyware and other Nasties)
- Questions For WebDevelopment =) (HTML and CSS)
- For idontno: Window Xp IE 6 (DNS ERROR) page not found! (Viruses, Spyware and other Nasties)
- cant get rid of LOP!! (Viruses, Spyware and other Nasties)
Other Threads in the PHP Forum
- Previous Thread: My IF ($email_settings == "0") isnt working! :(
- Next Thread: displaying image from database
| Thread Tools | Search this Thread |
.htaccess ajax apache api array beginner beneath binary broadband broken button cakephp checkbox class cms code countingeverycharactersfromastring crack cron curl database date decode display dynamic echo email error file files folder form forms function functions google href htaccess html image include insert integration ip java javascript joomla limit link login loop mail match menu mlm mod_rewrite multiple mysql oop paypal pdf php problem protocol query radio random recursion regex remote script search server sessions sms smtp soap source space sql strip_tags survey syntax system table tutorial undefined update upload url validation validator variable video virus votedown web window.onbeforeunload=closeme; xml youtube





