Monday, 19 August 2013

autosaving form data with jquery and php

autosaving form data with jquery and php

I am quite ok with PHP, but a total noob with jQuery, and got stuck with
autosaving form data.
The autosave function gets called every 30 seconds. I'm sending the
serialized form data for processing (--> database) to the same php page
(dummy.php) that makes the form and holds the jQuery code.
At this moment, I am stuck with this question:
How do I get dummy.php to 'listen' to incoming data and react to it?
At this moment, I get the alert 'Oh no!' ( = no success) every 30 seconds.
Here's my shortened sample code:
dummy.php, snippet 1 (HTML & PHP):
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script type="text/javascript"
src="../../_include/jquery-1.9.1.min.js"></script>
</head>
<body>
<h1>My Form</h1>
<form name="form1" id="form1" method="post" action="<?php echo
$_SERVER['PHP_SELF'] ?>">
<input type="radio" name="item_2_1" id="c_2_1_0" value="0" />
<input type="radio" name="item_2_1" id="c_2_1_1" value="1" />
<input type="radio" name="item_2_1" id="c_2_1_2" value="2" />
<input type="radio" name="item_2_1" id="c_2_1_3" value="3" />
<input type="checkbox" name="item_3_1[]" id="c_3_1_0" value="yes" />
<input type="checkbox" name="item_3_1[]" id="c_3_1_1" value="no" />
<input type="text" name="item_4_1" id="c_4_1_0" />
</form>
dummy.php, snippet 2 (jQuery):
<script type="text/javascript">
function autosave() {
jQuery('form').each(function() {
jQuery.ajax({
url: '<?php echo $_SERVER['PHP_SELF'] ?>',
data:
'navigation=save&autosave=true&'+jQuery(this).serialize(),
type: 'POST',
success: function(data){
if(data && data == 'success') {
alert("OK!");
}else{
alert("Oh no!");
}
}// end successful POST function
}); // end jQuery ajax call
}); // end setting up the autosave on every form on the page
}// end function autosave()
$(function() {
setInterval(autosave, 30 * 1000);
});
</script>

No comments:

Post a Comment