what i'm trying to do is get a variable to update every 5 seconds doing this:
setInterval(document.getElementById("listeners").innerHTML =
"<?php include('../includes/shoutcaststuff.php');
echo $dnas_data['CURRENTLISTENERS']; ?>",5000);
but what happens is the inner html is set but doesn't update every 5 seconds like it should.
my guess is that the php only executes once, but i have no idea if that's the case or not.
and i'm aware i should make a function to do the stuff inside setInterval... i'll clean up the code once i figure out how to make it work.
thanks in advance.
ok... ajax was 'the best' answer since no more than 2 people would be logged in at a time here so server requests isn't such a big deal.
here's how i got it to work:
function lCount(){
$.get("../includes/shoutcaststuff.php",{Count: "TRUE"}, function(data){
document.getElementById('listeners').innerHTML = data;
});
}
setInterval(lCount,5000);
and added this to the end of the php:
if(isset($_GET["Count"])){
echo $dnas_data['CURRENTLISTENERS'];
}
now it works fine.
thanks for the suggestions guys :)
<?php include('../includes/shoutcaststuff.php');
echo $dnas_data['CURRENTLISTENERS']; ?>
This code only executes once when the page is built. For the rest of the times this javascript is called whatever is first echoed will be the value.
Instead of using a static value here, you are going to need to use an ajax request (or a websocket if you want to use html5). The request will then hit your server once every 5 seconds. Keep in mind that this can cause undue load on your server.
Ratchet is a commonly used PHP WebSocket implementation that allows for data to be sent to the client using push technology. This is probably more preferable than using your polling approach.
PHP code is run on the server generating the HTML/JS. Use ajax if you need to run php code once the page has loaded.
Take a look at this for example;
Using this:
setInterval(document.getElementById("listeners").innerHTML =
"<?php echo "1";?>",5000);
Will output this to the browser:
setInterval(document.getElementById("listeners").innerHTML =
"1",5000);
Related
I'd like a section of text that is already dynamically changing every 10 minutes to do it without refreshing the page. I was thinking something along the lines of:
<?php
while (1 < 2) {
echo $value;
sleep(60);
}
?>
I realize that's a dumb way to make a while loop run and I would think it would work with just "while(){}" but I just wanted to make sure, that will be corrected when I actually write this thing as long as this isn't terrible to do. If there is a better way I'd love to hear it! thanks!
Edit: I just noticed it would echo the value after the first, any cleaver ways to make it replace it?
Edit2 Here's the php function I already written to retrieve the changing value:
<?php
function getTotal($basePrice){
$dogeValue = file_get_contents("https://www.dogeapi.com/wow/?a=get_current_price");
$postage = .49/$dogeValue;
return round($sellAmount = $basePrice/$dogeValue - $postage - ($basePrice*0.1/$dogeValue));
}
?>
The short answer: yes, that is bad practice.
Reasons include:
You tie up your server (will probably time out)
Unless you play around with the buffering, things will not be reflected at the time you want
You never send the close tag to the browser (or anything else that happens later).
It is tricky to overwrite what was already there, so you end up with the output increasing instead of changing.
Recommendation:
Use client side code (javascript, AJAX) - don't try to do this server side.
You can see an example of periodic AJAX at https://stackoverflow.com/a/6378771/1967396 .
For periodic JavaScript, see many good answers at Is there any way to call a function periodically in JavaScript?
This script will never show you anything, because until processing the php script is not done, web server doesn't send anything to output, considering your infinite loop, it will never happen.
instead of this not-working idea, use Ajax, cron jobs, or even pure javascript, its very simple and more rational certainly.
I'm pretty new to PHP but trying to find my way which has worked quite well up till now.
Problem is the following: I have a website with 2 links. Both should redirect to the same second website but depending on the link clicked, some values should change. I was trying to use a PHP session for this.
Here is the code up to now:
Link 1:
<a href="<? echo $link ?>" class="helsinki" onclick="<? $_SESSION['clicked']= "helsinki"; ?>"^^Helsinki^^</a>
Link 2:
^^Seattle^^
Now if I try to read which link was clicked on the next side like this:
<? if(isset($_SESSION['clicked']))
echo "clicked ". $_SESSION['clicked'];
?>
I always see "Seattle", Helsinki never appears although (I thought) I input Seattle if the Seattle link is clicked. Apparently it's not like that... Can anyone help me here?
This is because PHP code is server side, and thus executed at the time of the page request. So $_SESSION['clicked'] is set to helsinki then reset to seattle at the time your first page loads. You may want to use $_GET variables instead of $_SESSION variables.
Wait wait wait a second: PHP is "server-side", javascript is "client-side". That means you will ALWAYS execute PHP before javascript.
What you are trying to achieve can be simply done with a GET variable:
^^Seattle^^
^^Helsinki^^
And than in the second site you can get the value of our parameter:
$city = $_GET['city'];
Not sure if this is useful, but you could create a "redirector". It takes the user to a server side page that will redirect them to the final page and at the same time change the session.
The page:
...
...
The code for redirector.php:
<?php
session_start();
// determine where to redirect user (could be done with database or array of options)
switch ($_GET['link']) {
case 'helsinki':
header('Location: /link/to/helsinki');
break;
case 'seattle':
header('Location: /link/to/seattle');
break;
default:
return;
}
$_SESSION['clicked'] = $_GET['link'];
You're mixing up Javascript and PHP.
PHP is server side, that means that all PHP code is parsed and executed on the server side, and then is sent to the client.
So if you write
line #1: ^^Helsinki^^
and then
line #2: ^^Seattle^^
the value of $_SESSION['clicked'] is always first "Helsinki" (line #1), but then immediately overwritten by "Seattle" (on line #2).
In order to achieve what you want the script to achieve, is, for example, as follows:
^^Helsinki^^
^^Seattle^^
and then catch the sent variables from the PHP variable $_GET:
if (isset($_GET['location'])) {
if ($_GET['location'] == "helsinki") {
// Whatever
}
elseif ($_GET['location'] == "seattle") {
// You want
}
}
"^^Helsinki^^
"^^Seattle^^
and use $_GET['location'] at the other page to check weather it is helsinki or seattle.
$link should be the same for both links.
Also you can't mix PHP (server-side) with Javascript (client-side). Look it up for why that is.
You cannot write PHP code in the onclick event. If you want to do it like that, you should use Javascript/AJAX. Even if you do it like that, you won't still get the result as you desire, since AJAX request will delay some seconds.
I think the right way to do this kind of thing is like below:
Helsinki"
and this is the change_city.php:
<?php
$_SESSION["clicked"] = $_GET["city"];
?>
if you want to still use the $link, then you just put this above code top of your PHP file.
I need to execute a script within php, i tried almost everything..
http://bulksms.mysmsmantra.com:8080/WebSMS/SMSAPI.jsp?username=user&password=******&sendername=Vfup&mobileno= '.$f.' &message='.$message1.''
I tried java script, but i $f and $message1 are variables, so i cant use echo twice
Is there any function in php, which automatically opens the above link in a new window and i need the remaining part of the php code to execute normally without being affected. Will provide more details if required..
Regards,
PHP executes on the server, so is not capable of opening windows. If you want this to happen on the client side you will have to echo it out as JavaScript that the browser can execute.
If you're trying to get this alternate process to fire, then you might want to just call file_get_contents from your current script:
file_get_contents('http://bulksms.mysmsmantra.com:8080/WebSMS/SMSAPI.jsp?'.
'username=user&password=******&sendername=Vfup&mobileno= '.$f.
'&message='.$message1.'');
When file_get_contents is given a URL, it will load all of the data from that URL into a local string. This means, in this case, that the server will do what you are trying to get the browser to do for you.
If that is not sufficient, then you will need to use the js function window.open and pass it that URL:
<script>window.open("<?php echo $url; ?>");</script>
This is the link to a project i was making http://shout.agilityhoster.com/login.html
Log in with
username: rafa
password: nadal
Now if I log in with another user
username: ana
password: ivanovic
then the website seems to run extraordinarily slowly. Could multiple timed javascript function calls be the reason? It works perfectly using xampp on my PC..
Thanks
you have multiple istances where you should have just one;
you are using inline javascript code where you can just use jquery;
you are using body onLoad where you should use jquery dom ready;
you are using multiple ajax POST where you should have only one and use json;
your first account is probably more faster then the second only cause of browser cache, note that local stuff are always more faster then online server depending on it's speed, and bandwidth.
hope this help
i want help you ;)
you have this:
$("#one").css("visibility","visible");
$("#onein").css("visibility","visible");
$("#closeaa").css("visibility","visible");
$("#onein").css("visibility","visible");
$("#Layer22").css("visibility","visible");
should be:
$(".ClassTheeseAll").css("visibility","visible");
or at least:
$("#Layer22,#onein,#Layer22,#closeaa").css("visibility","visible");
you have
<body onLoad="javascript:window.setInterval('open()', 1000000);checkrow();javascript:window.setInterval('check_newmsg()', 1000000)">
should be
$(function() {
setInterval('initAllMyStuff()', 1000000);
});
function initAllMyStuff() {
open();
checkrow();
check_newmsg();
}
function getmsgs()
{
$.post("getmsg.php",{'name':name_one},function(data){$("#one").html(data);} );
$.post("getmsg.php",{'name':name_two},function(data){$("#two").html(data);} );
$.post("getmsg.php",{'name':name_three},function(data){$("#three").html(data);} );
}
should be:
$.post("getmsg.php", { 'name_one' : name_one , 'name_two' : name_two , 'name_three' : name_three } , function(data) { /* loop json and store where needed */ });
you then have:
function open(){
jQuery(window).bind("beforeunload", function(){$.post("logout.php");})
$.post("online.php",function(data){
$("#Layer6").html(data);
});
unload should just be:
$(window).unload(function() {
$.post("logout.php");
});
to be continue...
You have on this page like 3-5 ajax request's per second, it can by sluggish at times just becouse of that.
Like Curtis pointed out try to use Network panel in firebug.
Have you tried watching the network traffic with Firebug? That would tell you how long each of your network requests takes, and when they happen.
Like Curtis's answer, you'll want to profile the page with firebug and yslow [ https://addons.mozilla.org/en-US/firefox/addon/5369/ ] . If you find that you're waiting for images and the like, you could potentially swap out the onLoad call with jquery's ready method:
http://api.jquery.com/ready/
That could create a perception of performance, even if the other page items aren't loading as quickly.
Terrible Javascript aside, notice that requests to the site, even for the initial login page, are spectacularly slow (for example the login page alone took about 10 seconds to load from here).
Also at some point I received this error from the site:
Web Server: Too many connections!
Check your server side code for performance problems. Make sure your MySQL queries are performant. Make sure the server itself is correctly configured... Of course you have no control of this if you're using shared hosting, and if you're on free hosting you'll just have to live with a terrible slow site.
How do i make PHP work with JS?
I mean more like, i want to check if the user is logged in or not,
and if he is then it will:
$("#message").fadeIn("slow"); ..
How should i do this?
I have an idea maybe have a file that checks it in php, and then it echo out 1 or 0.
And then a script that checks if its getting 1 then do the message fade in.. But im not as so experienced to script that in JS
You cannot directly pass variables from Javascript to PHP because the PHP run on the server before it's sent to the client. But you can 'pass' variables from PHP to Javascript.
For example:
echo('<script type="text/javascript'> var phpvar = '.$variablefromphp.';</script>');
However, you can manipulate what javascript your browser will print. You can first check if the user is logged in in PHP, and based on that, conditionally print the HTML and Javascript.
For example
if($user->logged_in())
{
echo('<script type="text/javascript">$("#message").fadeIn("slow");</script>');
}
else
{
//php function
generateLoginBox();
}
I only javascript to enhance user experience. You should make your application work even when javascript turned off.
With the javascript enabled, you can add an enhanced experience, such as animated page element, AJAX request, etc.
In case of login state, you should have a way to know it in PHP script. Then in the output, you can have a conditional block that only executed if the login state is true. You can put anything you want here.
Javascript can be working in a static HTML page. You can use this to create a simple test for the code that you wrote, to see if it working as you want. Read the documentation in http://www.jquery.com/, there are many links there to many examples.