i have this function that gives me an output of a number. (the number is my total amount of downloads from my iphone themes.)
because the code has to make so many requests, it loads the page very slowly.
what would be the best way for me to go about the code loading into a variable and than calling it on the second page refresh. so it dosnt take so long to load?
or any other method will do. i just want it to not take so long to load!
also this isnt on my server so i cant use $.ajax
<?php
function all_downloads() {
$allThemes = array(
'com.modmyi.batterytheme',
'com.modmyi.connectiontheme',
'com.modmyi.icontheme',
'com.modmyi.percenttheme',
'com.modmyi.statusnotifiertheme',
'com.modmyi.cnote',
'com.modmyi.iaccescnotekb',
'com.modmyi.cnotelite',
'com.modmyi.multibrowsericon',
'com.modmyi.changeappstoreiconwithinstallous'
);
$total = 0;
foreach($allThemes as $com_modmyi){
$theme = file_get_contents( "http://modmyi.com/cstats/index.php?package=".$com_modmyi.'&output=number');
$theme = str_replace(",","", $theme);
$almost_done += $theme;
$rock_your_phone = 301; //From c-note and Multi Lock Screen Theme on Rock Your Phone
$total = ($almost_done + $rock_your_phone);
}
echo number_format($total);
}
?>
call the function with AJAX !
Th basic idea of using ajax is to to help make web applications function more like desktop applications
most actions that an end-user takes in his or her browser send a request back to the web server. The server then processes that request, perhaps sends out further requests, and eventually responds with whatever the user requested. <--whats your problem is ** **(slow !)
with AJAX you can call a PHP function with out reloading a page
please go though this tutorial which is really simple
Related
im experimenting with JSON Api's with PHP.
Im using a free Bitcoin price ticker api from Blockchain.
Its working but to refresh the data i need to refresh the page.
Would it be possible to auto-update the data without refreshing the page?
This is what i got now (its working)
<?php
$json = file_get_contents('https://blockchain.info/ticker');
$data = json_decode($json,true);
$priceUSD = $data['USD']['last'];
echo $priceUSD;
Thanks in advance, have a nice day!
King regards,
L Kenselaar
In order to refresh the data in your PHP array, you'll have to run a new HTTP request against your API from within the PHP code.
Without refreshing the page where your PHP renders, you would need to keep the connection open (which will only last for as long as your php.ini max_execution_time is and PHP can't edit data it has already sent, so the closest you could get is a news ticker that appends new lines at the bottom)
If all you want is a self-refreshing website, you'll have to use JavaScript (that can run infinitely and request new data from your PHP backend in regular intervals). Look for AJAX or XMLHttpRequests in general.
If you must stick to PHP you might want to run an independent process in background (checkout nohup or disown on Linux/Unix).
Your script would do something like:
<?php
while(true){
try {
$json = file_get_contents('https://blockchain.info/ticker');
$data = json_decode($json,true);
$priceUSD = $data['USD']['last'];
// Do the internal handling
// update your database, etc
}
catch (Exception $e) {
echo 'Error: ' . $e->getMessage() . "\n";
}
// wait for 5 seconds
sleep(5);
}
Keep in mind that PHP code runs in a blocking thread and this means that this process has to run aside of your web server.
However, if you wanted to both tasks at the same time (fetching and serving requests), you would have to consider alternatives like NodeJS.
I managed to display the status of a server using FSOCKOPEN.
<?php
$ip = "0.0.0.0";
$port = "1337";
$online = '<font class="online" title="Server Online!">ONLINE</font>';
$offline = '<font class="offline" title="Server Offline!">OFFLINE</font>';
if (! $sock=#fsockopen($ip, $port, $num, $error, 0.25))
{echo "$offline";}
else
{echo "$online";}
?>
If the server with the IP "0.0.0.0" sends an error or does not respond within 1/4th of a second after the page has been loaded the Output will return OFFLINE, else it will return ONLINE.
The server status will update when the user refreshes the page.
Now I want to make it to update in real time (less than 7 seconds delay)
I know there is a very easy method to do that using <meta http-equiv=”refresh” content=”5" /> in the head tag.
But its pretty annoying that the COMPLETE page have to refresh and load everything again and its causing some unnecessary traffic.
Is there an easier way to do it?
You can use ajax and javascript in the client to open the PHP Script in the background and then update the element in the page with the result based on success/failure.
Take a look at jQuery and other library to do this easily.
Another option would be a simple <iframe /> to open another website as an element on the website.
Dont use ajax or any direct polling mechanism that will put more load on your server in terms of traffic.
What you can use is websockets to push data to a stream and read it in frontend
https://socket.io/
This can be done near realtime and your page will not be reuired to get updated every min.
Put PHP script in cron to run at required interval and end of it just push the output to sockets and catch them on frontend.
I have a JavaScript functions which calls a PHP function through AJAX.
The PHP function has a set_time_limit(0) for its purposes.
Is there any way to stop that function when I want, for example with an HTML button event?
I want to explain better the situation:
I have a php file which uses a stream_copy_to_stream($src, $dest) php function to retrieve a stream in my local network. The function has to work until I want: I can stop it at the end of the stream or when I want. So I can use a button to start and a button to stop. The problem is the new instance created by the ajax call, in fact I can't work on it because it is not the function that is recording but it is another instance. I tried MireSVK's suggest but it doesn't worked!
Depending on the function. If it is a while loop checking for certain condition every time, then you could add a condition that is modifiable from outside the script (e.g. make it check for a file, and create / delete that file as required)
It looks like a bad idea, however. Why you want to do it?
var running = true;
function doSomething(){
//do something........
}
setInterval(function(){if(running){doSomething()}},2000); ///this runs do something every 2 seconds
on button click simply set running = false;
Your code looks like:
set_time_limit(0);
while(true==true){//infinite loop
doSomething(); //your code
}
Let's upgrade it
set_time_limit(0);
session_start();
$_SESSION['do_a_loop'] = true;
function should_i_stop_loop(){
#session_start();
if( $_SESSION['do_a_loop'] == false ) {
//let's stop a loop
exit();
}
session_write_close();
}
while(true==true){
doSomething();
should_i_stop_loop(); //your new function
}
Create new file stopit.php
session_start();
$_SESSION['do_a_loop'] = false;
All you have to do now is create a request on stopit.php file (with ajax or something)
Edit code according to your needs, this is point. One of many solutions.
Sorry for my English
Sadly this isn't possible (sort of).
Each time you make an AJAX call to a PHP script the script spawns a new instance of itself. Thus anything you send to it will be sent to a new operation, not the operation you had previously started.
There are a number of workarounds.
Use readystate 3 in AJAX to create a non closing connection to the PHP script, however that isn't supported cross browser and probably won't work in IE (not sure about IE 10).
Look into socket programming in PHP, which allows you to create a script with one instance that you can connect to multiple times.
Have PHP check a third party. I.E have one script running in a loop checking a file or a database, then connect to another script to modify that file or database. The original script can be remotely controlled by what you write to the file/database.
Try another programming language (this is a silly option, but I'm a fan of node). Node.js does this sort of thing very very easily.
I'm using an Ajax function with a call to itself to update the information continuously. But I let the script run for a while and then the server blocked my IP because it thought I was flooding it or something like that, I don't know. Anyway, I wonder if there's another way to do this more properly. Here's my code:
Ajax function:
function update_cart()
{
if (window.XMLHttpRequest)
var http = new XMLHttpRequest();
else
var http = new ActiveXObject('Microsoft.XMLHTTP');
http.onreadystatechange=function()
{
if ((http.readyState == 4) && (http.status == 200))
{
id('cart_quantity').innerHTML = parseInt(http.responseText);
setTimeout('update_cart()', 1000);
}
}
http.open('GET', actual_path+'fetch_cart_quantity.php', true);
http.setRequestHeader("X-Requested-With", "XMLHttpRequest");
http.send();
}
PHP script:
<?php
if($_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest')
{
header('Location: ./');
exit();
}
session_start();
include '../include/config.php';
include '../include/db_handler.php';
include '../include/cart_handler.php';
$cart = get_cart_quantity($_SESSION['cart_id']);
if ($cart == NULL) $cart = 0;
echo $cart;
?>
Thanks in advance for your help. Sorry that my English is not very good.
You have a couple of options here as I stated in my comment.
Basically the first is to chill out with the querying. You don't need to long poll such a thing. Turn down the querying to once every 5 mins or just whenever there is an action.
You can also build a simple comet server to do a push pull type thing when ever updates are "pushed" down from the server. There is a pre-built one called APE: http://www.ape-project.org/
Also node.js can handle this sort of thing for you.
Also you should probably look into your server setup, sounds kinda weird that your sever is blocking it's own IP address/domain...
Probaly, but i seriously think that querying your server every second is totally innecesary and also a waste of resources (unless you have very compulsive customers), making your script to query your server every minute or so is better and may work even better in the long term if you have several customers using this application from the same server.
If you really think is necessary to have this feature, a good approach will be using Push notifications, more info can be found here: PHP - Push Notifications, here: Push notification to the client browser and here: Push notifications from server to user with PHP/JavaScript.
Why don't you just update the cart when the user performs an action.
Such as 'Add item to shopping cart'?
That way you'd only call the server when it's actually needed.
Well, i was trying to reach a solution and i thought this might work:
On the PHP file:
$liguem = getdate();
$liguemoff = $_COOKIE['liguemoff'];
$liguemon = $_COOKIE['liguemon'];
if(empty($liguemoff)){
setcookie('liguemoff',$liguem[0],time() + (50000));
}
setcookie('liguemon',$liguem[0],time() + (20000));
$body->assign("COOKIE2", $liguemoff);
$body->assign("COOKIE3", $liguemon);
This has some body assign because I'm working with XTemplate, but the PHP is just PHP.
Now on the index file, some JavaScript:
var cookie2 = {COOKIE2};
var cookie3 = {COOKIE3};
if( cookie3-cookie2 > 60){
alert('alerta');
};
Truth is that it works! People might not be navigating, but it is what i want, the pop up will only open after the visitor sees at least 2 pages (Server-side thing).
The main problem is, that i CAN'T make the function popup(); to trigger where i have the ALERT displaying. The ALERT is working alright though.... Any hints?
PS:
This is the popthat(); function:
function popthat(){
$("#darkside").css('opacity','0.3').fadeIn('slow');
$("#darkside").click(function () {
$(this).css('opacity','1').fadeIn('fast');
$("#liguem").hide();
});
$("#liguem").corner();
$("#liguem").hide();
$("#liguem").delay(200).css('visibility','visible');
$("#liguem").fadeIn('fast');
}
You can set a timeout to display your popup after a specified amount of time. This amount of time can be dicated by your PHP since the server-side code will be able to track the amount of time on the site through page-views. This way the popup can display after 60 seconds on the site even if the user is not navigating to another page.
Something like:
setTimeout(popthat, <?php echo $_COOKIE[...]; ?>);
Your PHP would echo the number of milliseconds until the popup should display.
A note: when you replace your alert() with the popthat() function the DOM may not be ready and popthat() won't be able to work because it won't find any elements that match your selectors. Try running your code on document.ready ($(function() {});).
Browsers automatically block popups initialized on page load, because nobody likes these sorts of popups.
When you do an alert(), execution of your script stops. alert() is a blocking function, and nothing will happen until it has moved on.
I don't know if you just made a typo, but your function is called popthat(), and in your statement you said you called the function popup(). You need to change popup(); to popthat(); for this to work, unless as I said that was a mistake.