I want to ask that how can i use php function again and again after some time automatically just like setInterval in Javascript. We set the time and it is on its job until the script is aborted or closed.
INDEX.PHP
<?
$Wall = new Wall_Updates();
$updatesarray=$Wall->Updates();
foreach($updatesarray as $data)
{
$likes=$data['likes'];
?>
<div id="likes"><?php echo $likes; ?></div>
<?
}
?>
And Wall_Updates() Function is defined here in FUNCTION.PHP
<?php
class Wall_Updates {
public function Updates() {
$myname=$_COOKIE['usename'];
$query=mysql_query("SELECT * FROM posts WHERE name='$myname'");
while($row=mysql_fetch_array($query))
$data[]=$row;
return $data;
}
}
?>
I want this Wall_Updates() function to fetch data from mysql again and again.So, It will be Updated.
For the record: I think it's bad idea. But whatever :)
Try this code
function setInterval($f, $milliseconds)
{
$seconds=(int)$milliseconds/1000;
while(true)
{
$f();
sleep($seconds);
}
}
Usage:
setInterval(function(){
echo "hi!\n";
}, 1000);
Or:
$a=1;
$b=2;
setInterval(function() use($a, $b) {
echo 'a='.$a.'; $b='.$b."\n";
}, 1000);
your solution is quite simple :
$event = new EVTimer(10,2, function() {
Do your things .. :)
});
https://www.php.net/manual/en/ev.examples.php
I would suggest using setInterval to poll for results from a .php page using AJAx and then output your results.
So it would look something like this using jQuery:
<script>
var poll = true;
var getData = function() {
if (poll) {
$.get('getData.php', function(data) { $('#likes').html(data); });
}
};
$(document).ready(function() {
setInterval(getData, 5000);
$('.comm').click(function() { poll = false; });
$('.comm').blur(function() { poll = true; });
});
</script>
It isn't clear what you want to achieve exactly.
Are you aware that PHP only delivers content on request?
If you want the server to update something once in a while (a file for example), use a cronjob (on *nix).
If you want your WEBPAGE to re-query something, do it in javascript and call a PHP script that delivers fresh content.
Unlike Javascript, PHP is executed on the server side. There is no setTimeout functionality in PHP. You can get close by using cronjobs - or other PHP scripts - that call your scripts though.
I will surgest that you use a cron job to implement such functionality in your code.
Cron will run in the background based on the instruction you give it. check out this article
Since the asynchronous concept of web development has to do with effecting the changes on a web page without reloading the page, we must not always run to the ways of Ajax when ever we need such effects on our web pages.
PHP can simply do the job of going to the database # sleep seconds to retrieve some sets of data for our usage especially for chat application purposes.
See the below codes:
function setInterval ( $func, $seconds )
{
$seconds = (int)$seconds;
$_func = $func;
while ( true )
{
$_func;
sleep($seconds);
}
}
Now, let's say we have a function get_msg() that goes to the database to download some sets of information. If we must do that repeatedly without the repeated usage of button calls, then, see the usage of the setInterval function written above with the get_msg function.
setInterval ( get_msg(), 5 );
Javascript executes setInterval in other threads to continue its code-flow execution. But php hangs on the line you have called the function that is implemented by for loops.
However php supports multithreading and forking tools, but they're not recommended and not thread safety yet.
Related
I have an AJAX call on a loop, set to 1000 miliseconds.
The PHP script is simple, it just puts some information (a number) into a session variable. Yesterday I've recived an email from my hosting provider (HostGator), which states that I've been using 75%+ of CPU on shared hosting. After looking the logs, I've found that the problem is in that AJAX call. Here is the code:
PHP (ajax.session.php):
<?php
session_start();
$movieID_e = $_POST['id'];
$state = trim(strtolower($_POST['status']));
if ($state == 'playing') {
if (empty($_SESSION[$movieID_e])) {
$_SESSION[$movieID_e] = 1;
}
else {
$_SESSION[$movieID_e]++;
}
}
echo $_SESSION[$movieID_e];
?>
Javascript:
function interval(func,wait,times){
var interv = function(w, t){
return function(){
if(typeof t === "undefined" || t-- > 0){
setTimeout(interv, w);
try{
func.call(null);
}
catch(e){
t = 0;
throw e.toString();
}
}
};
}(wait,times);
setTimeout(interv, wait);
};
var watched = (function() {
var executed = false;
return function () {
$.post('ajax.session.php',{id:'<?php echo encrypt($id); ?>',status:'none'},function(result) {
if (result == 1000) {
if (!executed) {
executed = true;
var highlightad = introJs();
highlightad.setOptions({
steps: [
{
element: '#advertisment1',
intro: 'test',
position: 'bottom'
},
{
element: '#advertisment2',
intro: 'test2',
position: 'left'
}
]
});
highlightad.start();
}
}
else {
executed = false;
return false;
}
});
};
})();
interval(function(){watched()},1000,3000);
Explanation of JS:
function interval() -> Alternative to setInterval(), taken from thecodeship.com
function watched() -> AJAX request to file ajax.session.php shown above. If the result is 1000 then it highlights a part of a website using Intro.JS.
interval(function(){watched()},1000,3000); -> repeat watched() every 1000ms, max. number of repetitions is 3000 times.
Note that PHP script (ajax.session.php) is also called by AJAX from another script, also with function interval() every 1000ms.
I am using the interval() every second to count the number of seconds that past in a video player.
Do you have any suggestions on how to prevent CPU overload with the following script?
What server stats do you have? I think the problem is, that you have too much traffic for a weak server. Also of course 1second intervals for ajax calls are tooo often. Check your console, you will see that most of them will get timedout.
Sessions will be server side, so it will use servers resources. If you would convert your script to cookies, then the data will be stored in users browser. Also you could use $.cookie jQuery plugin to easily read the cookies via JS, so no need to ajax call.
Also, I would not recommend to use sessions at all, unless making some highly secure login system. I would recommend to use memcache to store temporary data.
Also, I'm pretty sure your JS could use optimization, because on first look I didn't see that you would check if one ajax call is active already. So it wouldn't ajax call before the last call was finished. Otherwise you can imagine the pointless ajax calls going to the server, where 50% of them get timedout.
While developing a web app where I'm making great use of javascript php and ajax.
I want to call
display_terminal('feedback_viewer','logs/init-raid-log.txt','Init-Raid');
to build my terminal and call feed_terminal() which has its own setTimeout() recursion call
var url='../edit_initRaid.php';
status_text('Initializing raid-array. Please wait a moment...');
var xmldoc=ajaxPHP2(url,2);
a php file that does nothing more that
exec("sudo /usr/bin/./init-raid-drives-web.sh");
and this is where I fail. This next line is not executed until after the exec() in the php file returns to the php file and the php file returns to the javascript. Not that it matters, but I am pretty sure it did not used to be this way, as originally the bash script would execute over a time period of 2 minutes and the javascript would successfully be updating the html with feed_terminal. this is not the case anymore.
alert("javascript has returned from ajax call");
if (xmldoc) {
status_text('Raid-array initialized successfully. System will now restart.You must re-login to FDAS-Web.');
Below is a bunch of code for your questions
Ultimately my question is, how can I run javascript DURING the ajax call?
Or maybe my question should be, how can I have edit_initRaid return an xmldoc, without waiting for the exec() to return, or how can i have the exec() return even without the script completing?
function initRaidArray(){
if (document.getElementById('initRaid_doubleCheck')){
if (document.getElementById('initRaidHideButtonSpot'))
document.getElementById('initRaidHideButtonSpot').innerHTML = '';
var spot=document.getElementById('initRaid_doubleCheck');
spot.innerHTML='';
spot.innerHTML='This may take a few moments. Please wait.';
}
display_terminal('feedback_viewer','logs/init-raid-log.txt','Init-Raid');
var url='../edit_initRaid.php';
status_text('Initializing raid-array. Please wait a moment...');
var xmldoc=ajaxPHP2(url,2);
alert("javascript has returned from ajax call");
if (xmldoc) {
status_text('Raid-array initialized successfully. System will now restart. You must re-login to FDAS-Web.');
}
}
where display_terminal() does two things, builds a table and appends it to the page, and calls feed_terminal(logfile,bigDiv,0)
function feed_terminal(logFile,bigD,lap){
// AJAX
bigD.innerHTML = '';
var url='../view_xml_text.php';
/*
* lap(0)=clear file , lap(1)=do not clear file
*/
url+='?logFile='+logFile+'&lap='+lap;
var XMLdoc=ajaxPHP2(url,2);
var xmlrows = XMLdoc.getElementsByTagName("line");
alert("xmlrows.length=="+xmlrows.length);
// empty file
if (xmlrows.length==0){
var d = document.createElement('div');
var s = document.createElement('span');
s.innerHTML='...';
d.appendChild(s);
bigD.appendChild(d);
} else {
// Parse XML
for (var i=0;i<xmlrows.length;i++){
if (xmlrows[i].childNodes[0]){
if (xmlrows[i].childNodes[0].nodeValue){
var d = document.createElement('div');
var s = document.createElement('span');
s.innerHTML=xmlrows[i].childNodes[0].nodeValue;
d.appendChild(s);
bigD.appendChild(d);
}
}
}
}
setTimeout(function(){feed_terminal(logFile,bigD,1)},2000);
}
where the most important item is the setTimeout() call to continue reaching out to the php file which returns xml of the lines in the file, simply.
function ajaxPHP2(url,key)
{
if (window.XMLHttpRequest) {
xml_HTTP=new XMLHttpRequest();
if (xml_HTTP.overrideMimeType) {xml_HTTP.overrideMimeType('text/xml');}
} else { xml_HTTP=new ActiveXObject("Microsoft.xml_HTTP"); }
xml_HTTP.open("GET",url,false);
xml_HTTP.send(null);
if (key){return xml_HTTP.responseXML;}
}
You need to tell Javascript to do your XHR call asynchronously.
Change
xml_HTTP.open("GET",url,false);
to
xml_HTTP.open("GET",url,true);
But first, you'll need to tell it to do something when the request completes (a callback):
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
alert(xmlhttp.responseText);
}
}
xmlhttp.open("GET",url,true);
xmlhttp.send();
One recommendation: XHR is a pain. It would be a lot easier to use something like jQuery's $.ajax()
You need to set your ajax call to be asynchronous. In the ajaxPHP2 function, the line xml_HTTP.open("GET", url, false); is what is causing the page to pause. The false parameter is telling the ajax call to make everything else wait for it. Change the false to true so it looks like this:
xml_HTTP.open("GET", url, true);
You may also need to attach a function to the onreadystatechange property so that when the ajax call returns it knows what to do. See these links for more information.
I'm using jQuery + PHP on my website and I want to do something like this:
To simplify things I've got a page with 2 buttons () and according to which I click I want to start a script in background (php script) so I do a simple thing with jquery:
$("#button1").click(function(){
$.post("script.php", {val:"but1"}, function(result){
alert(result); // I want something with the result
});
});
$("#button2").click(function(){
$.post("script.php", {val:"but2"}, function(result){
alert(result);
});
});
and in the script.php I've got a simple if statement deciding what I should do.
In the php script I'm downloading a file and I want to create a progress bar of the file download. The php script would return me values (echo percentage; flush();) in some time interval.
And here comes the problem - when I echo those percentage values and flush it refreshes it "just in php" but the jquery waits until the script is finished anyway. Is there a way to get those values as they appear (after flush) or is there a completely other approach to this? I can't think of anything else right now, maybe I shouldn't be using jquery at all.
Thanks for the help.
You can store the progress in a text file or DB while running the script and then have another file get the result via AJAX calls.
JS/HTML
<script>
$(function() {
var id;
var timeoutLength = 1000;
$("#button1").click(function() {
$("#result").html("");
// Create unique identifier
id = (new Date().getTime()) + "-" + Math.floor(Math.random()*100);
$.get("script.php", {id: id}, function(result){
$("#result").html(result);
});
setTimeout(checkProgress, timeoutLength);
});
function checkProgress() {
$.get("script.php", {progress: true, id: id}, function(data) {
prog = parseInt(data);
// Display progress bar
if(prog < 100) {
$("#progress").css({ display: 'block', width: prog });
$("#progress").html(prog + "%");
setTimeout(checkProgress, timeoutLength);
} else {
$("#progress").css('display', 'none');
}
});
}
})
</script>
<button id="button1">Click</button>
<div id="progress" style="background: green"></div>
<div id="result"></div>
script.php
<?php
function getProgress($file) {
return (file_exists($file)) ? file_get_contents($file) : 0;
}
function setProgress($file, $progress) {
file_put_contents($file, $progress);
}
// Remove invalid characters
$id = str_replace('/[^a-zA-Z0-9\-_]/', '', $_GET['id']);
$file = "progress-" . $id . ".txt";
if(isset($_GET['progress'])) {
echo getProgress($file);
} else {
// Do something and update progress
for($i = 10; $i <= 100; $i += 10) {
// Do something
setProgress($file, $i);
sleep(1);
}
unlink($file);
echo "Result: " . rand(1, 100);
}
Edit:
Added support for multiple requests and simple progress bar.
i believe that what all you need is the pecl uploadprogress package
it is not very easy to install and its not sure it works, i have find hard to make it work under certain server configurations, but i think its a good shot
EDIT: sorry i didnt see you mention download so have a look here
Below script will work for the progress-bar.
But, what I would do is, trigger an AJAX call to start the download and trigger another AJAX call to start receiving the input (using How to show file download progress in PHP Shell Scripting?).
PHP:
<?php
echo "wget '$feedURL'\n";
$execute = "wget -O ".$filePath." '$feedURL'\n";
$systemOutput = shell_exec($execute);
$systemOutput = str_replace( "\n", "\n\t", $systemOutput);
echo "\t$systemOutput\n";
?>
GetProgress:
function getProgress(){
GDownloadUrl("getprogress.php?progress_key=<?php echo($unique_id)?>",
function(percent, responseCode) {
document.getElementById("progressinner").style.width = percent+"%";
if (percent < 100){
setTimeout("getProgress()", 100);
}
});
}
Here is nice implementation with the help PHP's APC to get a nice progress-bar during UPLOAD of a file - http://www.haughin.com/2007/10/23/php-upload-progress-with-php-52-apc/
Alternative solution:
You can store the progress of downloading file into $_SESSION array inside PHP.
Besides that, you can write a dedicated PHP to only retrieve this percentage from session. This PHP will be called from your client's AJAX. This way the proccess won't take so much resources from server to calculate or to echo the download's percentage.
Try to avoid I/O from files if you are going to handle high rates of reading/writing onto them. Session variables are less expensive to achieve this functionality.
Provided that your PHP has some way to know the progress percentage, you should do multiple requests for progress updates:
function receiveProgress(data) {
// update progres indicator here
if (parseFloat(data) < 100) {
setTimeout(checkProgress, 100);
} else {
pressedButton = '';
}
}
function checkProgress() {
$.post("script.php", {val:pressedButton}, receiveProgress);
}
var pressedButton = '';
$("#button1").click(function(){
pressedButton = 'but1';
checkProgress();
});
This will ask server for progress updates every 100ms
I have
index.php
<select id="year_list" name="year_list" onchange="check_year_event('year_list', 'event_list');" > . . . </select>
<select id="event_list" name="event_list" onchange="check_year_event('year_list', 'event_list');" > . . . </select>
.
.
.
<?php
function checkYearandEvent($year, $event) {
$year_event = mysql_query("SELECT * FROM year_event WHERE year = '$event' AND event = '$event'")
if (mysql_num_rows($year_event) > 0) {
// do this
}
}
?>
myscripts.js
function check_year_event(year_id, event_id) {
var year = document.getElementById(year_id).value;
var event = document.getElementById(event_id).value;
// call PHP function (but I don't know how): checkYearandEvent(year, event);
}
My question is how do I call the PHP function every time the user changes the value of any of the select element.
You need to use ajax. There is a basic example:
myscripts.js
function AjaxCaller(){
var xmlhttp=false;
try{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}catch(e){
try{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}catch(E){
xmlhttp = false;
}
}
if(!xmlhttp && typeof XMLHttpRequest!='undefined'){
xmlhttp = new XMLHttpRequest();
}
return xmlhttp;
}
function callPage(url, div){
ajax=AjaxCaller();
ajax.open("GET", url, true);
ajax.onreadystatechange=function(){
if(ajax.readyState==4){
if(ajax.status==200){
div.innerHTML = ajax.responseText;
}
}
}
ajax.send(null);
}
function check_year_event(year_id, event_id) {
var year = document.getElementById(year_id).value;
var event = document.getElementById(event_id).value;
callPage('file.php?year='+year+'&'+'event=+'+event,document.getElementById(targetId));
}
file.php
<?php
function checkYearandEvent($year, $event) {
$year_event = mysql_query("SELECT * FROM year_event WHERE year = '$event' AND event = '$event'")
if (mysql_num_rows($year_event) > 0) {
// do this
}
}
echo checkYearandEvent($_GET['year'], $_GET['event']);
?>
You won't be able to do this in the way you might be expeting to. PHP is executed on the server, before the browser receives the HTML. On the other hand, JavaScript runs in the browser and has no knowledge of the PHP (or any other server side language) used to create the HTML.
To "call" a php function, you have to issue a request back to the server (often referred to as AJAX). For example, you could have a checkYear.php script which checks the event and returns some HTML indicating whether the check succeeded. When the HTML fragment gets back to the JavaScript, you inject it into the page.
Hope this helps!
JavaScript is a client side language, PHP is a server side language. Therefore you can't call PHP functions directly from JavaScript code. However, what you can do is post an AJAX request (it calls a PHP file behind the scenes) and use that to run your PHP code and return any data you require back to the JavaScript.
Basically, you are mixing server-side (PHP) and client-side (JS) scripting.
It is however possible - thanks eg. to AJAX. Because you was not specific about what do you exactly need to be done after the select box changes, I can only point you to some resources and propose following:
learn and start using jQuery (jquery.com) - it will help you get started and maintain cross-browser compatibility,
learn how to make AJAX requests (eg. in the function you just were firing when onchange event was fired) - eg. using .post() jQuery function,
learn how to return data from PHP (eg. using json_encode() in PHP, but raw HTML is also ok) and use it in JS,
There may be many ways to do this. The one I prefer, is using MooTools Request object.
For example, you have a script called ajaxCallable.php, which receives thru $_REQUEST variables some parameters, then you do (in the Javascript side):
function check_year_event(year_id, event_id) {
var year = document.getElementById(year_id).value;
var event = document.getElementById(event_id).value;
var myRequest = new Request({method: 'get', url: 'ajaxCallable.php'});
myRequest.send('yearVar=' + year + '&eventVar=' + event);
}
then, your ajaxCallable.php will be able to access the variables: $_REQUEST['yearVar'] and $_REQUEST['eventVar'].
I was working on a project this week and came up with an easy way to call a php script from an onclick(). It goes like this.
I define an onclick() call in this case on a div called "sidebarItem"…
<a><div class="sidebarItem" onclick="populate('#content', 'help', 'open')">Click me for new content</div></a>
Then I made a simple little JS function that loads an external file into the target container…
function populate($container, $page, $item){
$($container).load('cyclorama/includes/populate.php?$page='+$page+'&$item='+$item);}
Then I write a small php file that gets the $page and $item, queries the database and returns the new content.
<?php
$page = $_GET['$page'];
$item = $_GET['$item'];
$getContentQuery = "SELECT content FROM myTable WHERE page='".$page."' AND item='".$item."'";
$content = mysql_query($getContentQuery, $db);
$myContent = mysql_fetch_assoc($content);
echo $myContent['content'];?>
The php script echoes the new content and it's loaded into the container. I think there are a lot of places this could serve. I'd be interested in finding out if there are any obvious reasons NOT to do this. It doesn't use AJAX just javascript and php but it's fast and relatively easy.
I have a question, I'm using uploadify, and every time when a file finishes to upload, the script runs a code which is located in the onComplete statement, and the code from the onComplete statement it's an ajax call to a page, let's call it X , how can I know when the script access the page X for the first time?
Although I'm not familiar with uploadify, if you set a variable in the global scope (outside the onComplete), I'll call it var hasBeenCalled, set it to false at the page load.
When onComplete is called, do:
if (hasBeenCalled)
{
// not the first time
}
else
{
//first time
hasBeenCalled = true;
}
Hope it helps
try with this:
var myFirstEvent = false;
var myFunOnComplete = function()
{
if (!myFirstEvent)
{
// code for fist instance
}
// set finish the first instance
myFirstEvent = true;
// code for ajax call
callAjax();
}
jQuery('#fInput').uploadify({
...
'onComplete': myFunOnComplete,
...
});