Reputation: 63
hey guys i have a database and am trying to fetch some result ..and i can succesfully fetch the result with php..What i need is to run the result after 3 seconds ..So i used 'setTimeout()` in js but it didnt worked out..My code
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
@$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$sql = 'SELECT age FROM honey';
mysql_select_db('test');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
echo '<script>
var c = 3000;
setTimeout(function() { '<?php echo $row['age'];'}, c);
</script>';
}
mysql_close($conn);
?>
The error i get is Parse error: syntax error, unexpected '?' in C:\wamp\www\refresh\index.php on line 24
..
how can i properl use js inside this php code..Thanx for the help
Upvotes: 0
Views: 56
Reputation: 17636
Doesn't seem you've understood the difference between client and server.
The simplest way for you to accomplish this is using an xmlhttprequest ( seeing that jquery isn't linked ).
setInterval(function () {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
console.log('ages: ' + xmlhttp.responseText);
}
}
xmlhttp.open("GET", "php_ajax_handler_url_here", true);
xmlhttp.send();
}, 3000);
Now all you need to do is replace "php_ajax_handler_url_here" with the your php file name. And in your php all you need to do is echo your result:
$res = '';
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
$res += $row['age'].' ';
}
echo $res;
So what does this all do? Well the client loads your html file with your js. Your js (3 seconds later) will call your php file that handles ajax responses. It will searchin your db for the information, and echo it all out as one big string.
Update:
Demo without XHMLHttpRequest()
I created a little library for you. I have tested it, so it should work.
So how to use the library? It's really simple.
var a = age('ajax_url_handler_here').load(function(){
console.log('done loading');
});
Then you start it
a.start(function(age){
//do something with age
//The callback is called every 3 seconds and updates age with new age
});
Then to stop
a.stop();
(function () {
var age = function (url) {
if (!(this instanceof age)) {
return new age();
}
if(!(typeof url === 'undefined')){
this.url = url;
}
this.ages = [];
this.counter = 0;
this.setIntervalId = -1;
}
age.fn = age.prototype = {
init: function () {}
};
//load unchainable
age.fn.load = function (callback) {
var xmlhttp = new XMLHttpRequest(),
_this = this;
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
console.log('ages: ' + xmlhttp.responseText);
//creating an array
_this.ages = xmlhttp.responseText.split(' ');
if(!(typeof callback === 'undefined')){
callback();
}
}
};
xmlhttp.open("GET", this.url, true);
xmlhttp.send();
return this;
}
age.fn.start = function (callback) {
this.counter = 0;
if(this.ages.length > 0){
var _this = this;
this.setIntervalId = setInterval(function(){
console.log('age: ' + _this.ages[_this.counter]);
if(!(typeof callback === 'undefined')){
callback(_this.ages[_this.counter]);
}
_this.counter = (_this.counter + 1) % _this.ages.length;
}, 3000);
}
//chainable
return this;
};
age.fn.stop = function(){
if(this.setIntervalId > -1){
clearInterval(this.setIntervalId);
this.setIntervalId = -1;
}
//chainable
return this;
};
window.age = age;
})();
Update # 2:
If for some reason the library did not work, feel free to try this simplified version. All you need to do is replace var url = "url_here"
with the correct url.
Let me know if you are getting any errors.
var url = "url_here",
ages = [],
setAges = function (callback) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
console.log('Response: ' + xmlhttp.responseText);
//creating an array
ages = xmlhttp.responseText.split(' ');
if (!(typeof callback === 'undefined')) {
callback();
}
} else {
console.log('An error occured');
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
};
var siId = -1,
si = function (callback) {
var counter = 0;
siId = setInterval(function () {
if (!(typeof callback === 'undefined')) {
callback(ages[counter]);
}
counter = (counter + 1) % ages.length;
}, 3000);
}
setAges(function(){
console.log('xmlhttprequest finished starting interval');
si(function(age){
//do something with res
console.log('age: ' + age);
});
});
Upvotes: 2
Reputation: 3136
This block:
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
echo '<script>
var c = 3000;
setTimeout(function() { '<?php echo $row['age'];'}, c);
</script>';
}
Will output something like this:
<script>
var c = 3000;
setTimeout(function() { '<?php echo $row['age'];' }, c);
setTimeout(function() { '<?php echo $row['age'];' }, c);
setTimeout(function() { '<?php echo $row['age'];' }, c);
setTimeout(function() { '<?php echo $row['age'];' }, c);
setTimeout(function() { '<?php echo $row['age'];' }, c);
setTimeout(function() { '<?php echo $row['age'];' }, c); // repeats as long as you have rows.
// #JavascriptObviousErrorIsObvious.
</script>
PHP code is interpreted in serverside, you're printing your php code inside javascript and it won't execute. the most you could 'fix it is to type something like this:
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
echo "<script>
var c = 3000;
setTimeout(function() { document.write('".$row['age']."'); }, c);
</script>";
}
Which will output something like:
<script>
var c = 3000;
setTimeout(function() { document.write('18'); }, c);
setTimeout(function() { document.write('26'); }, c);
setTimeout(function() { document.write('47'); }, c);
setTimeout(function() { document.write('23'); }, c);
setTimeout(function() { document.write('32'); }, c);
</script>
Upvotes: -1
Reputation: 70163
You cannot use client-side JS "inside" your server-side PHP. PHP is parsed and run on the server side before your client even gets (and parses and executes) the resulting JS. If you need to set a timer, you either need to do it on the server (yuck) or do it on the client (having the client issue another call to the server).
Upvotes: 1