I'm currently adding data into db table via Ajax like this: When user pushes button with id #submit_btn it fires following function and posts data. The code of function looks like this.
$("#submit_btn").click(function () {
$("#add_form").submit(function (e) {
e.preventDefault();
dataString = $("#add_form").serialize();
$.ajax({
type: "POST",
url: "processor/dbadd.php",
data: dataString,
dataType: "json",
success: function (result, status, xResponse) {
//do something if ajax call is success
var message = result.msg;
var err = result.err;
if (message != null) {
$.notifyBar({ cls: "success", html: message });
}
if (err != null) {
$.notifyBar({ cls: "error", html:err});
}
},
error: function (e) {
//ajax call failed
alert(e);
}
});
});
Is there anyway to modify this code for automatic submission in every 2-3 seconds? (autosave)
A possible solution would be to put the content of $('#add_form')
in a separate function, say, submt()
and call submit on setTimeout
or if the $('#submit_btn')
is clicked.
Instead of setTimeout
, which you have to set over and over again, consider using setInterval
, which needs to be called only once.
Pleas try this code
<script>
$(document).ready(function(){
var int = window.setInterval("call();",2000);
$("#add_form").submit(function (e) {
// PLACE YOUR SUBMIT CODE HERE
});
$("#submit_btn").click(function () {
$('#add_form').submit();
});
});
function call(){
$('#add_form').submit();
}
</script>
/// NEW ANSWER
<script>
var int;
$(document).ready(function(){
$("#add_form").submit(function (e) {
// PLACE YOUR SUBMIT CODE HERE
});
$("#submit_btn").click(function () {
int = window.clearInterval(int)
int = window.setInterval("call();",3000);
});
});
function call(){
$('#add_form').submit();
}
</script>
///THIRD ANSWER
<script>
$(document).ready(function(){
$("#add_form").submit(function (e) {
// PLACE YOUR SUBMIT CODE HERE
});
$("#submit_btn").click(function () {
int = window.setInterval("call();",3000);
$(this).attr({'disabled':'disabled'});
$(':input#autosave').attr({'disabled':'disabled'});
});
$(':input#autosave').click(function(){
if($(this).is(':checked')){
$(':input#submit_btn').attr({'value':'Save & exit'});
}
else{
$(':input#submit_btn').attr({'value':'Save'});
}
});
});
function call(){
$('#add_form').submit();
}
</script>
</head>
<body>
<form id="add_form" action="" method="post">
<input type="checkbox" id="autosave" value="1"/>
<input id="submit_btn" type="submit" name="save" value="Save"/>
</form>
</body>