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.
Related
I need to get the items(with selector a[id=test]) from the page that is loaded by ajax. For this I use phantomjs.
In PHP:
$phantom_path = '/usr/bin/phantomjs';
$names = shell_exec("$phantom_path model/phantomscript-names.js $url");
in phantomjs i received items:
var page = require('webpage').create(),
system = require('system'),
url = system.args[1];
page.open(url, function(status) {
page.injectJs('jquery-2.1.4.min.js');
var links = page.evaluate(function() {
return [].map.call(document.querySelectorAll('a[id=test]'), function(link) {
return link.innerText;
});
});
console.log(links.join('\n'));
phantom.exit();
});
the script runs for about a minute for each page.
whether it is possible to reduce this time using phantomjs or i need to use another tool for this?
On some sites I've found this benefits the load time on Phantom JS.
on other sites the images still come up and it makes no difference.
page.settings.loadImages = false;
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.
well the question is enough explained can it be done.
what I am trying to do is to get data from a popup and onclose I want to send the content I retrieved to a php controller for processing.
But I dont want to use jquery library, because it is creating a conflict for me.
Update
window.onbeforeunload = confirmExit;
function confirmExit()
{
var a = document.getElementsByTagName("div");
for (i = 0; i < a.length; i++) {
if(a[i].className == 'Ymacs-frame-content'){
var b = a[i].getElementsByTagName("div").innerHTML;
//alert(b);
}
}
//Ajax should be here
window.onbeforeunload = reloadOpener;
if (top.opener && !top.opener.closed) {
try {
opener.location.reload(1);
}
catch(e) { }
window.close();
}
}
window.ununload=function() {
reloadOpener();
}
You can just use jquery-less AJAX:
var a = new XMLHttpRequest();
a.open("GET","myscript.php?var=foo&othervar=bar",true);
a.onreadystatechange = function() {
if( this.readyState == 4) {
if( this.status == 200) {
// data sent successfully
// response is in this.responseText
}
else alert("HTTP error "+this.status);
}
};
a.send();
Alternatively, you can create an iframe tag and point it to the right page. You can even create a form and post it to the frame if needed.
You can do it in javascript without using jQuery since that is all jQuery does in the background. You will need to look at the different ways IE does it compared to other browsers though.
Yes, XMLHttpRequest, but you'll need to account for differences in browsers, which jQuery does for you.
I just went through this. The only way to use Javascript to pass info to PHP is by using XMLHttpRequest, or at least if there is another way I did not find it. It has to do with the fact that PHP renders on the server side, and Javascript isn't executed until after it is served to the client...unless you use the XHR which is...AJAX.
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 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.