Reputation: 275
We have the following jquery which get data from the backend .php script. Everything works fine. What need help on is how to do this without the button press but say for every 30 seconds or 1 minutes interval to do the same thing.Below is our current script?
<script>
$(document).ready(function() {
$("#searchBtn").click(function(){
$(this).attr('src', 'images/searching.png');
var data = $(this).val();
var dateFrom=document.getElementById("beginDate").value;
dateFromArray=dateFrom.split("/");
var myDateFrom=new Date(dateFromArray[2],dateFromArray[1],dateFromArray[0]);
var dateTo=document.getElementById("endDate").value;
dateToArray=dateTo.split("/");
var myDateTo=new Date(dateToArray[2],dateToArray[1],dateToArray[0]);
mysqlDateFrom=dateFromArray[2]+"-"+dateFromArray[1]+"-"+dateFromArray[0];
mysqlDateTo=dateToArray[2]+"-"+dateToArray[1]+"-"+dateToArray[0];
$.post('getBK.php', {b: mysqlDateFrom,e: mysqlDateTo}, function(data){
$("#searchBtn").attr('src', 'images/search.png');
$('#dbData').html(data);
}
);
}
);
}
);
</script>
Upvotes: 1
Views: 95
Reputation: 422
<script>
$(document).ready(function() {
function myfunc(){
$("#searchBtn").attr('src', 'images/searching.png');
var data = $("#searchBtn").val();
var dateFrom=document.getElementById("beginDate").value;
dateFromArray=dateFrom.split("/");
var myDateFrom=new Date(dateFromArray[2],dateFromArray[1],dateFromArray[0]);
var dateTo=document.getElementById("endDate").value;
dateToArray=dateTo.split("/");
var myDateTo=new Date(dateToArray[2],dateToArray[1],dateToArray[0]);
mysqlDateFrom=dateFromArray[2]+"-"+dateFromArray[1]+"-"+dateFromArray[0];
mysqlDateTo=dateToArray[2]+"-"+dateToArray[1]+"-"+dateToArray[0];
$.post('getBK.php', {b: mysqlDateFrom,e: mysqlDateTo}, function(data){
$("#searchBtn").attr('src', 'images/search.png');
$('#dbData').html(data);
}
);
}
myfunc();
setInterval( function(){ myfunc(); } , 30000 );
});
</script>
Upvotes: 2
Reputation: 4081
Use setInterval()
$(function(){
// set interval
var tid = setInterval(mycode, 30000);
function mycode() {
// place your button click logic over here
}
function abortTimer() { // to be called when you want to stop the timer
clearInterval(tid);
}
});
Upvotes: 2
Reputation: 34846
To have the POST to PHP run automatically when the DOM is loaded, then use the setInterval()
function, like this:
$(document).ready(function() {
setInterval(function() {
// Do something every 30 seconds
$.post('getBK.php', {b: mysqlDateFrom,e: mysqlDateTo}, function(data){
$("#searchBtn").attr('src', 'images/search.png');
$('#dbData').html(data);
}
);
}, 30000);
);
Note: the second value of setInterval()
is the time for the interval in milliseconds (so 30000 for 30 seconds or 60000 for 1 minute).
Upvotes: 1