Call and Run Ajax every X minutes - php

How call and run Ajax every X minutes without the page being open (client-side), running in the background on the server side.
My Code in Header.php:
(function($) {
function updateGo() {
$(window).load(function() {
$.ajax({
url: '/test.com/template/test/script.php',
dataType: 'html',
cache: false,
success: function(data) {
if (data) {
$('body').append(data);
}
}
});
})
}
updateGo();
setTimeout(updateGo, 60 * 1000);
})(jQuery);
In script.php there are some functions and codes jquery inside and it works perfectly, but only works when I enter the page (client-side), in case I am trying to make the functions and codes of this script always run without having to enter the page.

If you want to Call and Run Ajax every X minutes jQuery you can try the function setInterval doc like:
(function($) {
function updateGo() {
$(window).load(function() {
$.ajax({
url: '/test.com/template/test/script.php',
dataType: 'html',
cache: false,
success: function(data) {
if (data) {
$('body').append(data);
}
}
});
})
}
updateGo();
// for this example we take 3000 milliseconds
let interval = 3000;
setInterval(updateGo, interval);
})(jQuery);
so it's work when you load your page in your browser.
NB: in the background on the server side, we can't use Ajax, you must try to add cronJob little documentation about
I hope it's help you

Related

how to load data without page refresh using ajax

Here is my code for loading data
$(document).ready(function() {
$.get('get-answers.php', {
project_question_id: <?=$project_question_id?>,
project_id: <?=$project_id?>
}, function(data) {
$('#dispaly-answers').append(data);
});
});
This code retrieves data from database and working fine. But problem here is that if I add new data on the database, this data doesn't show up without page refresh.
So I don’t want to refresh the page to get the data. It should be displayed once new data added to database.
Any suggestions on this issue?
P.S : I also tried .ajax(), didn’t work.
Here is my $.ajax() request
$(document).ready(function() {
$.ajax( {
type: "GET",
url: "get-answers.php",
data: { project_question_id: <?=$project_question_id?>,
project_id: <?=$project_id?>
},
cache: false,
success: function(data) {
$('#dispaly-answers').append(data);
},// success
})// ajax
});
Does the same as $.get()
If your goal is to refresh the page data without refreshing the page, you can put your code in an interval timer and let it auto refresh every x seconds, like below.
setInterval(getAnswer(), 1000);
note: setInterval fires again and again until you clear it, while setTimeout only fires once.
The Ajax-Function get only called once: In the moment the document is ready (fully loaded). You have to use setTimeout to create a timer, which calls the function every minute or whatever you want. Like this:
function getData() {
setTimeout(function(){
$.get('get-answers.php', {
project_question_id: <?=$project_question_id?>,
project_id: <?=$project_id?>
}, function(data) {
$('#dispaly-answers').append(data);
getData();
});
}, 3000);
}
Here is my final approach
$(document).ready(function() {
setInterval(function(){
$.ajax( {
type: "GET",
url: "get-answers.php",
data: { project_question_id: <?=$project_question_id?>,
project_id: <?=$project_id?>
},
cache: false,
success: function(data) {
$('#dispaly-answers').html(data);
},// success
})// ajax
}, 1000);
});
Without creating and calling function getData(), this code working fine. Also I have changed .append(data) to .html(data).
But still I'm not happy with my code because it is constantly retrieving data from database that makes data server busy.
Whatever I wanted to tasks has to be done and it is done.
Try this you just need to replace this file retrieve_query.php and this id query-div with yours.
setInterval(function(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
$('#query-div').html(this.responseText);
}
};
xmlhttp.open("GET","retrieve_query.php",true);
xmlhttp.send();
},1000);

HowTo run a ShellScript in PHP in loop

I have a shell script which is excecuted in a php file to get the temperature.
<?php
$output = shell_exec('sh temperature.sh');
echo "<pre>$output°C</pre>";
?>
Right now it is only excecuted once.
How do I need to change the php file so the Value is always up to date?
Thanks
PHP is a server side language. that means that when its loaded, its done.
if you want to update it always, you should use ajax calls for that.
var interval = 1000; // 1 second
function doAjax() {
$.ajax({
type: 'GET',
url: 'get_what_you_want.php',
data: {},
dataType: 'json',
success: function (data) {
$('body').text(data) // or put it on your page
},
complete: function (data) {
// Schedule the next
setTimeout(doAjax, interval);
}
});
}
setTimeout(doAjax, interval);

Do not want to wait till server response to the AJAX request

I have created a long polling using jQuery / PHP. and it is working perfectly. The issue is when a user click on other links or refresh the current page, it will hang on the current page till it get response from last AJAX request from server.
I have set about 30 sec in the server side to pick the latest data, means if someone sent a request to get the latest data, he cannot go to another page or refresh the current page till it returns the response. The worse case is, if the server didnt find the latest data, it will send the response after 30 sec.
I have use the following code to abort the request.
window.onbeforeunload = function(event) {
xhr.abort();
}
I have check on the console before and after execute xhr.abort() it shows readyState=1 and then readyState=0. Does this means xhr.abort() executed successfully? But why still the page hang on the current page till it returns the response.
Please help me to solve my issue. I don't want to wait until the server response when user click on other link or refresh page or do other stuff on the page.
This is my jQuery code
function setNoti(ntotal)
{
var t;
xhr = $.ajax({
type: "POST", url: myURL, data: "", dataType: "JSON", cache: false, async: true,
success: function(data) {
// do my work here
clearInterval(t);
t = setTimeout(function() {
setNoti(20);
}, 1000);
return false;
},
error: function()
{
clearInterval(t);
t = setTimeout(function() {
setNoti(0);
}, 40000);
return false;
}
});
}
You are assigning an xhr which can then be used to abort the request on subsequent calls to the function.
function setNoti(ntotal)
{
if (xhr) {
xhr.abort();
}
var t;
xhr = $.ajax({
type: "POST", url: myURL, data: "", dataType: "JSON", cache: false, async: true,
success: function(data) {
// do my work here
clearInterval(t);
t = setTimeout(function() {
setNoti(20);
}, 1000);
return false;
},
error: function()
{
clearInterval(t);
t = setTimeout(function() {
setNoti(0);
}, 40000);
return false;
}
});
}
No need for the window.onbeforeunload handler, which being a separate event is likely being called at the wrong time.
I have added session_write_close() in the server side and it is working perfectly. Following post helped me to find the solution :)
Multiple AJAX requests delay each other

Ajax on interval

I'm having trouble with lag and script execution.
I have the following code:
$(function(){
$("#results").html("Loading work order queue...");
setInterval("showWorkOrders();", 15000)
});
function showWorkOrders()
{
$.ajax({
url: '/ajax/job_queue_ajax.php',
type: 'POST',
cache: false,
data: 'update=true',
success: function(data)
{
$("#results").html(data);
$('span#ref_msg').html('');
},
error: function()
{
a = new customModal('ajax');
$("#results").html("<font class='msgDivError'>"+a.ajaxError+"</font>");
$('span#ref_msg').html('');
}
});
}
My backend PHP (only an example):
$SQL = MySQL_query("SELECT * FROM table")
while($data = MySQL_fetch_array($SQL))
{
//// OUTPUTS A TABLE WITH INFORMATION
}
Now, this whole thing executes however with a lot of lag (takes very long to load) and sometimes creates an script error because it took too long to load. If I extend the refresh interval, things start getting better (the lag remains) and I don't get the execution error. I need to have a short interval for what I need, but I cannot figure out an efficient way of doing so. Any suggestions on how to improve this?
Also, after a while of being on the page that has the refresher, the browser becomes extremely slow to the point where it locks...
I would solve it using setTimeout instead:
$(function(){
$("#results").html("Loading work order queue...");
showWorkOrders();
});
function showWorkOrders()
{
$.ajax({
url: '/ajax/job_queue_ajax.php',
type: 'POST',
cache: false,
data: 'update=true',
success: function(data)
{
$("#results").html(data);
$('span#ref_msg').html('');
setTimeout("showWorkOrders();", 5000)
},
error: function()
{
a = new customModal('ajax');
$("#results").html("<font class='msgDivError'>"+a.ajaxError+"</font>");
$('span#ref_msg').html('');
setTimeout("showWorkOrders();", 5000)
}
});
}
This would mean that it waits 5s before doing a new ajax request, the previous one can take however long it wants. Still waits 5s before it tries again.
Try this. Start next request only after response from server.
$(function(){
$("#results").html("Loading work order queue...");
showWorkOrders();
});
function showWorkOrders()
{
$.ajax({
url: '/ajax/job_queue_ajax.php',
type: 'POST',
cache: false,
data: 'update=true',
success: function(data)
{
$("#results").html(data);
$('span#ref_msg').html('');
setTimeout(showWorkOrders, 15000);
},
error: function()
{
a = new customModal('ajax');
$("#results").html("<font class='msgDivError'>"+a.ajaxError+"</font>");
$('span#ref_msg').html('');
setTimeout(showWorkOrders, 15000)
}
});
}
Instead of Ajax on interval, I'd suggest next Ajax after completion.
Since the ajax request takes an indeterminate amount of time to complete, I would suggest that you trigger the next ajax request when the first one completes using setTimeout() and so on like this so that you never have multiple ajax requests going at once and so each subsequent ajax call starts a known time from when the previous one completed.
You probably want to troubleshoot why your server is taking so long to respond to the request, but you can also extend the timeout for the ajax call if your server sometimes takes a long time to respond:
function showWorkOrders()
{
$.ajax({
timeout: 15000,
url: '/ajax/job_queue_ajax.php',
type: 'POST',
cache: false,
data: 'update=true',
success: function(data)
{
$("#results").html(data);
$('span#ref_msg').html('');
setTimeout(showWorkOrders, 5000);
},
error: function()
{
a = new customModal('ajax');
$("#results").html("<font class='msgDivError'>"+a.ajaxError+"</font>");
$('span#ref_msg').html('');
setTimeout(showWorkOrders, 5000);
}
});
}
$(function(){
$("#results").html("Loading work order queue...");
showWorkOrders();
});

pause jQuery function for 5 seconds before script returns true and posts

Im using jQuery to post a form to a database, before posting the HTML form to a remote server via the form action method.
All works fine, but I am trying to build in a message pre-the server POST , so is there a way that just before my jQuery function returns true to get it to pause for 5 seconds and display a message?
...
$.ajax({
type: "POST",
url: "myform.php",
data: dataString,
success: function() {
$('#details').html("<div id='post-message'></div>");
$('#post-message').html("<h2 style='color:#fff'>Thanks for getting in touch</h2>")
//.append("<p>Thank you</p>")
.hide()
.fadeIn(1500, function() {
// $('#message').append("<img id='tick' src='images/tick.png' />");
});
}
});
return true;
});
...
I ideally need a pause of 5 seconds just before the script returns true and finishes - any help much appreciated! Presently the message has no time to display as the script returns true and posts!
Thanks
You could use setTimeout('func', 5000); in the success function.
function doItLater()
{
$('#details').html("<div id='post-message'></div>");
$('#post-message').html("<h2 style='color:#fff'>Thanks for getting in touch</h2>")
//.append("<p>Thank you</p>")
.hide()
.fadeIn(1500, function() {
// $('#message').append("<img id='tick' src='images/tick.png' />");
});
}
$.ajax({
type: "POST",
url: "myform.php",
data: dataString,
success: function() {
// do stuff now ...
// wait 5 seconds
window.setTimeout('doItLater', 5000);
return true;
});
});
If you need to be sure that POST request is complete before doing some other things, try setting "async" param to "false" - see http://api.jquery.com/jQuery.ajax/

Categories