Hello i am having trouble with passing a php return value to the innerHTML method to change my div’s value on a fixed interval.
this is my code, i inclue the php file containing the method, and then create an object of the class containing the method, then i want to echo the return value to the innerHTML function. but is does not work.
var t = setInterval(function() {
document.getElementById("content").innerHTML = "\
<? include_once("php/functions.php"); \
$cont = new Content(); \
echo ($cont->getPosts()); \
?>";
}, 1000);
However this works so a php value can be echod to the innerHTML function.
var t = setInterval(function() {
document.getElementById("content").innerHTML = "<? echo "Some Text"; ?>";
}, 1000);
there is noting wrong with the <? include_once("php/functions.php"); $cont = new Content(); echo ($cont->getPosts());?> statement, because when i put it outside of the <script> tags it does what it needs to, however it does not refrech every few seconds
thanks in advance
i tried to make the question as clear as possible, if you have questions however, just ask.
I suspect what you mean by “does not work” is that it only puts the same thing out every second. This is because PHP is run on the server-side BEFORE the browser gets any HTML, and this makes the code look something like this when it arrives to the browser:
This means that your browser will just put the static text “whatever php produced” into your div every time the interval fires.
To solve this you will need a slightly different approach. Use AJAX to request an updated version from a PHP script that return just what is suppoesd to be inside the div. jQuery has a function to do this for you if you are not familiar with AJAX yourself.
Also be aware that AJAX is asynchronous, meaning static timing is a bad idea. Instead you should use a on-complete function to fire the next load.
The server-side script can be something like what you originally had:
Reference:
http://api.jquery.com/load/