HowTo run a ShellScript in PHP in loop - php

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);

Related

Call and Run Ajax every X minutes

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

Making asynchronous and synchronous calls parallely in ajax

I am abit confused with idea of asynchronous and synchronous ajax calls.Is it possible to make one ajax call asynchrononously followed with a synchronous call??
Here's my scenerio,
I am trying to make a real time progress bar to show no of data inserted where postdata() inserts data into table while getprocess() function returns the current no of data inserted to show in a progress bar.
Reference:: making progress bar
function getprogress(data){
console.log(data);
$.ajax({
method: 'POST',
url: '<?php echo base_url()?>setting/processoffline/getprogressdata',
data:{ table:data },
dataType: 'json',
async: false,
success: function(val) {
var off=parseFloat(Number(val.dataoffline),10);
var on=parseFloat(Number(val.dataonline),10);
var percent=Math.round((off/on)*100);
// $('#'+data+'success').addClass('hidden');
console.log('offline- '+off);
console.log('online- '+on);
$('#'+data+'progressbar').css('width',percent+"%");
$('#'+data+'progressbar').html(percent+"%" + off+' out of '+on );
if(percent=='100'){
console.log(percent);
// $('#'+data+'progressbox').addClass('hidden');
$('#'+data+'success').removeClass('hidden');
$('.download').removeAttr('disabled','disabled');
// clearTimeout();
}
console.log(postComplete);
if (!postComplete)
setTimeout( function() { getprogress(data); }, 1500);
} ,
error: function() {
if (!postComplete){
setTimeout( function() { getprogress(data); }, 1500);
}
}
});
}
function postdata(data)
{
// if(!data)
$.ajax({
method: 'POST',
url: '<?php echo base_url()?>setting/processoffline/processdata',
data:{ master_table:data },
dataType: 'html',
success: function() {
postComplete = true;
},
error: function() {
postComplete = true;
}
});
}
Now here's how I call these functions for use
$(this).parent('td').parent('tr').siblings('tr').children('td').find('input:checked').each(function(){
data=$(this).attr('id');
postdata(data);
$('#'+data+'success').addClass('hidden');
$('#'+data+'progressbox').removeClass('hidden');
i++;
getprogress(data);
if(!postComplete)
setTimeout( function() { getprogress(data);}, 2);
Here postdata() function is called multiple times in loop asynchronously my case is that since loop can be for unlimited number, that can start lot of parallel processes that can hang up my system so .I need to start next loop for postdata() only when the earlier process is over.Function postdata() makes ajax call for php function that requires a lot of time.So my technique is to define postdata() function asynchronously so that I can call getprogress() function parallely but (don't know if possible) I want to call getprocess ajax call synchronously so that loop will wait until value returned from getprogress is over.In this way I can start a new process in ajax call only when earlier process is over.
I want to know if it is possible or not and if not how can i manage this issue.Sorry for bad english and If unclear please comment and I am stuck to this for 3-4 days.
Thanks in advance

calling a php function using ajax after interval of time

hi i am working on a codeigniter project. I want to execute a php function after an interval of 10seconds. When a user visits that specific page after 10 seconds i want that php function to be executed. In that php function i have set a counter which adds 1 to the specific table into the database. I have tried using AJAX but didnt get the desired result. Kindly explain me with examples as i am new in ajax. Thanks in advance...
#Majid Golshadi s answer is the right answer.
Working version is here
Please in view that is loaded all the time (like header_view.php)
add this few lines
<script type="text/javascript">
var _baseUrl = "<?= base_url() ?>";
</script>
This makes that your base_url is usable in JavaScript anywhere in page (but make sure to have it somewhere on "TOP" of page)
and literraly use #Majid Golshadi s answer in this way
$(document).ready(function() {
setTimeout(function() {
$.ajax({
url: _baseUrl + "/your/controller/param",
type: 'post',
data: {"token": "your_token"}, });
}, 10000);
});
using jquery this will be the easiest and fastest way to do that
`//setting timeout to 3 seconds = 3 thousand milli seconds
setInterval(function(){
//ajax call
$.ajax({
url: _baseUrl + "/controller_name/function_name/", //the url where you want to fetch the data
type: 'post', //type of request POST or GET
data: {"data": "value"}, }); //data passed to controller
},3000);`
in your controller you may use
function function_name(){
$var = $this->input->post();//getting data passed from ajax
//process here...
echo json_encode($var)//parses and returns the processed value
}
try this
setTimeout(function(){
$.ajax({
url: "<?php echo base_url('your/controller/address');?>",
type: 'post',
data: {"token": "your_token"},
});
}, 10000);
Example
in your view
$(document).ready(function(){
setTimeout(function(){
$.ajax({
url: "<?php echo base_url('MyController/Mymethod');?>",
type: 'post',
data: {"token": "12majid18"},
});
}, 10000);
});
and in Your Controller write method like this
public function Mymethod()
{
$token = $this->input->post('token');
if ( $token == '12majid18' )
{
/*call your model and insert your data in Table*/
}
}
you can try this:
window.jQuery(function(){
var y=setInterval(function() {
window.jQuery.post(url,{"token": "your_token"},function(res){
alert(res);
});
}, 10000);
});

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();
});

Perform 2 background tasks simultaneous with jQuery and Ajax

updated my question below
I made a script where a user can import large amounts of data. After the form is submitted and the data validated I add 2 background tasks: 1 is a script that imports all the data. This script also lets the databases know how many in total and how many he has done. The second is a script that reads how much is done from the database and displays it in a nice progress bar.
Code:
$.ajax({
type: "GET",
url: "import-process.php",
success: function(data) {}
});
var process = 0;
var checkPercentage = function() {
$.ajax({
type: "GET",
url: "get-process-status.php",
data: "importcode=123456",
success: function(data) {
if (!data.indexOf("ERROR") !== -1) {
process = data;
$("#process_balk").css('width', process + '%');
}
}
});
if (process != 100) {
setTimeout(checkPercentage, 1000);
} else {
window.location.href = "import-finished.php";
}
}
checkPercentage();
Both scripts, work fine. Except that the second script (getting the status of the process) isn't started after the first (importing the data) is finished. Which makes the complete thing kinda useless.
Any ideas how to solve this?
update:
I found out that the background process gets called only once. That's the problem. I'm just not sure how to fix it..
var checkPercentage = function() {
alert("Is this function getting called every second?");
$.ajax({
type: "GET",
async: true,
url: "required/get-process-status.php",
data: "importcode=123456",
success: function(data) {
alert(data);
}
});
setTimeout(checkPercentage, 1000);
}
The code above alerts "Is this function getting called every second?" every second. Like it should. However, the value 'data' is called only once. That's not what I expected.. Any ideas?
You mean like this?:
$.ajax({
type: "GET",
url: "import-process.php",
success: function(data) {
checkPercentage();
}
});
var process = 0;
var checkPercentage = function() {
$.ajax({
type: "GET",
url: "get-process-status.php",
data: "importcode=123456",
success: function(data) {
if (!data.indexOf("ERROR") !== -1) {
process = data;
$("#process_balk").css('width', process + '%');
}
}
});
if (process != 100) {
setTimeout(checkPercentage, 1000);
} else {
window.location.href = "import-finished.php";
}
}
I just moved checkPercantage function call from end of script to success function of first ajax. You can also move it to complete function if you wish to run it despite of errors.
Set your callback function to be:
success: function(data) {
if (!data.indexOf("ERROR") !== -1) {
process = data;
$("#process_balk").css('width', process + '%');
if (process != 100) {
setInterval(checkPercentage, 1000);
} else {
window.location.href = "import-finished.php";
}
}
}
Firstly, the if statement has to be in a callback function to work the way you want it. Secondly, you should use setInterval() instead of setTimeout() because it will recheck it every interval time.
Also, yabol is right saying that the top of your code should look like this:
$.ajax({
type: "GET",
url: "import-process.php",
success: function(data) {
checkPercentage();
}
});

Categories