I am trying to reload a page and retrieve data automatically after 10 seconds or preferably less than that. Please i tried so many codes and it didn't work.
Here is what i am using now...
// script //
<script>
$(document).ready(function(){
// setInterval(function() {
// $("#load_msgs").load("load.php");
// }, 10000);
//var updateInterval = setInterval(function() {
//$('#load_msgs').load('load.php?p=<?php echo $username; ?>');
//},1000);
//});
var autoLoad = setInterval(
function ()
{
$('#load_msgs').load('load.php').fadeIn("slow");
}, 10000);
});
</script>
// php / html div id panel
<div class = 'container me' id = "load_msgs"> </div>
// php load.php file
<?php
include('config.php');
include('func.php');
//$username = $_GET['q'];
$o = "--DATABASE QUERY--";
$z = mysql_query($o) or die(mysql_error());
while ($roow = mysql_fetch_array($z)) {
$date = $roow['date'];
echo $roow['message']. " <span class = 'lil'>" . time_elapsed_string($date)."</span> \n <br />";
}
?>
I'm assuming from your comments that you can navigate directly to load.php and the data is echo'd. If that is the case, here's how I would set it up:
(It's not clear if you trying to load a file every X seconds, or just once after X seconds, Here is an example of both)
index.php:
<?php
$username='someUser'
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Load From PHP</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
var username = encodeURI( <?php echo isset($username) ? "'".$username."'" : ''; ?> );
$(function(){
var url='load.php?username='+username;
// load once after 2 seconds
setTimeout(function(){ $.get(url, function(response){ $('#load_msgs').html(response); } ); }, 2000);
// load every 2 seconds
setInterval(function(){ $.get(url, function(response){ $('#load_msgs_repeat').append(response+'<br>'); } ); }, 2000);
});
</script>
</head>
<body>
<h4>Div loaded once</h4>
<div id="load_msgs"></div>
<br>
<h4>Div loaded every 2 seconds</h4>
<div id="load_msgs_repeat"></div>
</body>
</html>
load.php:
<?php
$username= isset($_GET['username']) ? $_GET['username'] : null;
echo $username ? 'here is some data loaded from load.php for user: '.$username : 'here is some data loaded from load.php, but no user was provided' ;
?>
Here is a functioning example
The problem may be in config.php or func.php. Are you connecting to the database before running your query?
Add these two lines to the start of load.php:
ini_set("display_errors", "On");
error_reporting(E_ALL);
Then visit load.php in your browser. You should get some helpful error messages.
window.setTimeout(function(){window.location.replace("page.php")},5000);
Related
I have searched it on google, and I have found some examples.
I have tried to do my code based on this example here
I'm trying to generate a random number between 0 and 100 by clicking a button,
then hide the button and show it again after 24h.
For my example, I have inserted 5 secs for testing purposes,
But I'm getting an error from the var variable.
I have just edited it, but the button is hidden and no random number is shown.
and is not showing again
What I'm missing here?
<html>
<input type="submit" value="Submit" onclick="validate();" name="windaily" id="windaily">
<?php $randn = rand(0,100);?>
<?php echo($randn); ?>
<script>
function validate() {
var windaily= document.getElementById('windaily');
windaily.style.visibility='hidden';
setTimeout (function(){
windaily.style.visibility ='visible';
},5000);
return false;
}
</script>
</html>
I think this is what you need.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<?php
require_once 'hide-button.php'; // to reset button when 24 hours has expired
if(empty($_SESSION['hide_button'])) {
?><input type="submit" value="Submit" onclick="validate();" name="windaily" id="windaily"><?php
}
$randn = rand(0,100);
?>
<div id="display-number"></div>
<script>
function validate() {
let windaily = document.getElementById('windaily');
windaily.style.visibility='hidden';
document.getElementById("display-number").textContent = '<?php echo $randn ?>';
$.ajax({
method: "GET",
url: "/hide-button.php", //to use php session to hide button for 24 hours
}).done(function( msg ) {
});
return false;
}
</script>
</body>
</html>
Then inside hide-button.php
<?php
if(!session_id()) {
session_start();
}
$expire = 86400; // 1 day
if(empty($_SESSION['timestamp'])) {
$_SESSION['timestamp'] = time();
$_SESSION['hide_button'] = true;
} else {
if(time() > ($_SESSION['timestamp'] + $expire)) {
unset($_SESSION['timestamp']);
unset($_SESSION['hide_button']);
}
}
?>
You can't use php tags to override scripts.. Use the script tag and then you can place your php variables
Substitute <? Php to
I know that this might be answered already by someone, but all the answers I could find, are intended for people who already know what they are doing and they paste thousands of lines of code, so I want something more on a begginer's side.
I have a value that I want to update ever 15 seconds to show the most updated information from a mysql db. I managed to show the latest result every once you reload the webpage.
The code is the following (everything is on the same file index.php):
PHP part:
<?php
$link = mysql_connect('localhost', 'root', '');
$LastUpdate = mysql_query('SELECT dateTime FROM LastUpdate where id=1');
if (!$LastUpdate) {
die('Could not query:' . mysql_error());
}
HTML part:
<small id="result">Last Update: <?php echo mysql_result($LastUpdate, 0); ?></small>
Jscript part:
<script>
setInterval(function() {
var date='Last update: '+'<?php echo mysql_result($LastUpdate, 0); ?>';
document.getElementById("result").innerHTML = date;
}, 1000);
The script part is supposed to refresh the "result" div every 1000 milliseconds. The problem is that once the script is performed one time the value gotten from the query doesn't change, having to reload the page in order for it to refresh.
First off all. Client asks Server for Webpage -> The Server build your Page -> The Browser get the response and render your HTML page. So far so good. Your <?php echo mysql_result($LastUpdate, 0); ?> always has the same value. You have to make an AJAX call and please don't use mysql functions anymore. There are deprecated (https://secure.php.net/manual/de/function.mysql-connect.php). Use PDO instead and always escape your statements to prevent sql injections or use an ORM. Here is a quick and dirty solution:
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>test</title>
<script src="https://code.jquery.com/jquery-3.0.0.min.js" integrity="sha256-JmvOoLtYsmqlsWxa7mDSLMwa6dZ9rrIdtrrVYRnDRH0=" crossorigin="anonymous"></script>
<script>
function ajaxCall() {
$.ajax({
url: "ajax.php",
dataType: "json"
}).done(function (data) {
$(this).addClass("done");
var date = 'Last update: ' + data.firstData.dateTime + ' - count: '+ data.secondData.count;
document.getElementById("result").innerHTML = date;
});
}
$(function () {
ajaxCall();
setInterval(ajaxCall, 1000);
});
</script>
</head>
<body>
<small id="result"></small>
</body>
</html>
ajax.php
<?php
$link = mysql_connect('localhost', 'root', '');
mysql_select_db('testdatabase', $link);
$LastUpdate = mysql_query('SELECT dateTime FROM LastUpdate where id=1') or die(mysql_error());
$firstData = mysql_fetch_assoc($LastUpdate);
$count = mysql_query('SELECT COUNT(Name) AS count FROM users, LastUpdate WHERE lastConnection = dateTime') or die(mysql_error());
$secondData = mysql_fetch_assoc($count);
$returnValues = array(
'firstData' => $firstData,
'secondData' => $secondData
);
echo json_encode($returnValues);
response example (JSON)
{
"firstData": {
"dateTime": "2016-06-16 00:00:00"
},
"secondData": {
"count": "1"
}
}
My script:
<?php
//header("refresh: 7;");
include 'theme.php';
ceklogin();
css();
echo '<script type="text/javascript"
src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script>
$(document).ready(
function() {
setInterval(function() {
var randomnumber = Math.floor(Math.random() * 100);
$("#show").text(
"I am getting refreshed every 3 seconds..! Random Number ==> "
+ randomnumber);
}, 3000);
});
</script>';
exec('/www/openvpn_wget_status.sh');
echo '<br>';
echo file_get_contents( "/www/openvpn_status.txt" );
echo '<div id="show">';
//include 'wget.log';
//echo "<br><textarea name=\"text-info\" id=\"scores\" rows=\"30\" cols=\"90\" readonly style=\"font-family: Arial;font-size: 7pt;\" >";
//$datalines = file ("wget.log");
//foreach ($datalines as $zz) {
//echo $zz; }
echo '</div>';
//echo "</textarea><br></div>";
echo '<script type="text/javascript">
var textarea = document.getElementById("scores");
textarea.scrollTop = textarea.scrollHeight;
</script>';
foot();
echo '
</div>
</body>
</div>
</html>';
?>
it works perfectly but what if I want the variable from a log file in my webserver, let's say the name of the log file is wget.log and I want to refresh it every 3 seconds since wget.log keeps changing as I run wget to download files?
Script to read file (readFile.php)
<?php
//in this script, read any file(or do something else)
//whatever you output, it will be processed in ajax request from below script
echo "<pre>".file_get_contents( "/www/openvpn_status.txt" )."</pre>"; //used <pre> to keep linebreaks in file.
?>
HTML (another file)
<script type="text/javascript"
src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script>
$(document).ready(
function() {
setInterval(function() {
$("#show").load("readFile.php"); //it will make ajax call to readFile.php and get output from that script and load to #show div
}, 3000);
});
</script>
<div id="show">
This will be refreshed every 3 seconds.
</div>
I have assigned two variables that are equal to a PHP variable that can change at any time. I am trying to update a div every 5 seconds; for example, to update the number. I am assuming this doesn't work because the PHP doesn't run again once the page has loaded. What is the best way to get around this? I don't mind linking to another page if necessary. Here's my code:
$(document).ready(function() {
var buyprice = <?php echo $coinTicker->price($coin2[1] , 'buy'); ?>;
var sellprice = <?php echo $coinTicker->price($coin2[1] , 'sell'); ?>;
$('#currentbuyprice').html(buyprice);
$('#currentsellprice').html(sellprice);
setInterval(function() {
var buyprice = <?php echo $coinTicker->price($coin2[1] , 'buy'); ?>;
var sellprice = <?php echo $coinTicker->price($coin2[1] , 'sell'); ?>;
$('#currentbuyprice').html(buyprice);
$('#currentsellprice').html(sellprice);
}, 5000);
});
Yeah - that won't work as you know.
setInterval(function() {
var buyprice = <?php echo $coinTicker->price($coin2[1] , 'buy'); ?>;
var sellprice = <?php echo $coinTicker->price($coin2[1] , 'sell'); ?>;
$('#currentbuyprice').html(buyprice);
$('#currentsellprice').html(sellprice);
}, 5000);
That is a javascript + php. The browser runs javascript and php runs on the server. They run at different times and are mutually exclusive. The work apart from each other.
What you want to do (probably) if you are trying to update realtime is to use an ajax call.
http://api.jquery.com/jquery.ajax/
I find the api documentation good for reference but bad for example.
var jqXHR = $.ajax({
url: "target.aspx",
type: "GET",
dataType: "html",
}).done(function (data, status, jqXHR) {
$("#container").html(data);
alert("Promise success callback.");
}).fail(function (jqXHR,status,err) {
alert("Promise error callback.");
}).always(function () {
alert("Promise completion callback.");
})
That makes a pretty good example. Google "jqXHR" for other working examples
$(document).ready(function() {
var buyprice = <?php echo $coinTicker->price($coin2[1] , 'buy'); ?>;
var sellprice = <?php echo $coinTicker->price($coin2[1] , 'sell'); ?>;
$('#currentbuyprice').html(buyprice);
$('#currentsellprice').html(sellprice);
setInterval(function() {
$.get('/get_prices.php', function( data ) {
buyprice = data.buy;
sellprice = data.sell;
$('#currentbuyprice').html(buyprice);
$('#currentsellprice').html(sellprice);
}, "json" );
}, 5000);
});
And in your backend (/get_prices.php in this example, change it!)
<?php
$buy = 1;
$sell = 1;
echo json_encode(array(
'buy' => $buy,
'sell' => $sell,
));
exit;
You can make a simple ajax get request to a seperate php file that returns the data as json:
setInterval(function() {
$.get('/prices.php', function(data){
$('#currentbuyprice').html(data.buyprice);
$('#currentsellprice').html(data.sellprice);
});
}, 5000);
prices.php:
//code that creates $cointTicker and $coin vars goes here
header('Content-Type: application/json');
echo json_encode(
[
'buyprice' => $coinTicker->price($coin2[1] , 'buy'),
'sellprice' => $coinTicker->price($coin2[1] , 'sell')
]
);
You can't update static PHP variables, because the PHP-script gets an request, works and answers to the client, so the session is closed. The are two ways to handle that.
Way 1:
You have to connect your PHP to an Database. So you will send a request to a PHP-file, which updates the numbers in the database, so the values will be safed, also for the next request.
Way2:
You can make PHP Sessions php.net link. So you will save your values temporary in a session. That session will deleted after a while, and maybe that is not that, what you need. sessions are similar to cookies.
Both ways work through an AJAX-Request. So you need an Javascript-Function, that will send your request to that PHP-file, which will update the Database or the Session. You should also have a function to get that values from the Database or the Session.
Using the same approach (making a polling) you can make an ajax query
<!DOCTYPE html>
<html>
<head>
<title>
</title>
<meta charset="utf-8" />
<meta name="description" content="">
<meta name="keywords" content="">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.3.min.js" charset="UTF-8"></script>
</head>
<body>
<script>
function send(){
$.ajax({
url: "a.php/",
type: 'GET',
success: function(res) {
var myVars = JSON.parse(res);
console.log(myVars[0].buyprice);
$('#currentbuyprice').html(myVars[0].buyprice);
$('#currentsellprice').html(myVars[0].sellprice);
}
});
}
setInterval(function(){ send() }, 3000);
</script>
currentsellprice:
<div id="currentbuyprice">
</div>
currentsellprice:
<div id="currentsellprice">
</div>
</body>
here the minimal part of the server
<?php
$out = "[";
$out .= '{"buyprice":"'. time(). '",';
$out .= '"sellprice":"'. time()/2 . '"}';
$out .="]";
echo $out;
?>
You can find a lot of information related with this topics (ajax and json) in internet.
Im trying to get my PHP script called from AJAX (that is in my main php file).
Here's an example of what it is supposed to do: http://jsfiddle.net/xfuddzen/
The HTML source code shows only desk_box DIV being created (which is in my main.php). station_info DIV (being created in the display_station.php) is not there. How can I fix this? thanks in advance
Problem: DIVs from my display_stationinfo.php are not being created by using the AJAX call.
main.php with JQuery/AJAX part:
<div id="map_size" align="center">
<?php
//didsplay Desk stations in the map
while($row = mysqli_fetch_assoc($desk_coord_result)){
//naming X,Y values
$id = $row['coordinate_id'];
$x_pos = $row['x_coord'];
$y_pos = $row['y_coord'];
//draw a box with a DIV at its X,Y coord
echo "<div class='desk_box' data='".$id."' style='position:absolute;left:".$x_pos."px;top:".$y_pos."px;'>id:".$id."</div>";
} //end while loop for desk_coord_result
?>
<script type="text/javascript">
//Display station information in a hidden DIV that is toggled
//And call the php script that queries and returns the results LIVE
$(document).ready(function() {
$('.desk_box').each((function(){(this).click(function() {
var id = $(this).attr("data")
$("#station_info_"+id).toggle();
$.ajax({
url: 'station_info.php',
data: { 'id': id },
type: 'POST',
dataType: 'json',
success: function(json) {
$("#station_info_"+id).css({'left':json.x_pos ,'top': json.y_pos}).append('<p>Hello the id is:'+ json.id +'</br>Section:'+ json.sec_name +'</p>');
}//end success
});//end ajax
});//end click
});//end ready
</script>
</div> <!-- end map_size -->
display_station.php (script that I want to call):
<?php
include 'db_conn.php';
//query to show workstation/desks information from DB for the DESKS
$station_sql = "SELECT coordinate_id, x_coord, y_coord, section_name FROM coordinates";
$station_result = mysqli_query($conn,$station_sql);
//see if query is good
if ($station_result === false) {
die(mysqli_error());
}
//Display workstations information in a hidden DIV that is toggled
$html = '';
if($station_result->num_rows > 0){
while($row = $station_result->fetch_object()) {
$id = $row->coordinate_id;
$html .= "<div class='station_info_' id='station_info_$id' style='position:absolute;left:{$row->x_coord}px;top:{$row->y_coord}px;'>Hello the id is:$id</br>Section:{$row->section_name}</br></div>";
}
}
else{
// no results - may want to do something with $html
$html = "no result given";
}
$station_result->free();
$conn->close();
echo $html;
?>
Why dont you filter the coordinate in the query? Like this:
$station_sql = "SELECT coordinate_id, x_coord, y_coord, section_name FROM coordinates WHERE coordinate_id = " . $_GET['coordinate_id'];
And in jquery code:
url: 'display_stationinfo.php?coordinate_id=' + id,
Let's start with your database connection, which should be on a separate secure page.
connect.php:
<?php
function db(){
return new mysqli('host', 'username', 'password', 'database');
}
?>
Obviously, your host will not be 'host'.
Now main.php:
<?php
// only use for PHP on this page for initial page load - target other pages with AJAX
?>
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
<head>
<meta http-equiv='content-type' content='text/html;charset=utf-8' />
<title>This is Where Your Title Goes</title>
<script type='text/javascript' src='//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js'></script>
<script type='text/javascript' src='main.js'></script>
<link rel='stylesheet' type='text/css' href='main.css' />
</head>
<body>
<div id='map_container'>
<div id='map_size'>
</div>
</div>
</body>
</html>
Now for main.js:
//<![CDATA[
$(function(){
var ms = $('#map_size');
$.post('main_init.php', {init:'1'}, function(d){
for(var i in d){
var di = d[i], x = di.x, y = di.y;
var sti = $("<div class='station_info_' id='station_info_"+i+"'></div>").css({
left:x,
top:y
});
// HTML id, class, and name attributes cannot start with a number
$("<div class='desk_box' data='"+i+"'>id:"+i+'</div>').css({
left:x,
top:y
}).appendTo(ms).append(sti).click(function(){
var info = $(this).next();
$.post('live_info.php', {station_id:info.attr('id').replace(/^station_info_/, '')}, function(r){
// do stuff with r
info.html('love:'+r.love+'<br />hate:'+r.hate).toggle();
}, 'json');
});
}
}, 'json');
});
// use CSS to do `.desk_box,.station_info_{position:absolute;}`
//]]>
Now for main_init.php:
<?php
if(isset($_POST['init']) && $_POST['init'] === '1'){
include_once 'connect.php'; $db = db(); $json = array();
$q = $db->query("SELECT * FROM table WHERE"); // example only
if($q->num_rows > 0){
while($r = $q->fetch_object()){
$json[strval($r->coordinate_id)] = array('x' => $r->x_coord, 'y' => $r->y_coord);
}
}
else{
// no results
}
$q->free(); $db->close();
echo json_encode($json);
}
else{
// could be a hack
}
?>
Here's what live_info.php might look like:
<?php
if(isset($_POST['station_id'])){
include_once 'connect.php'; $db = db(); $json = array();
// example only - you will only get one `$row` if query is done specific, so while loop is not needed
$q = $db->query("SELECT love,hate FROM some_table WHERE id='{$_POST['station_id']}'");
if($q->num_rows > 0){
$row = $q->fetch_object();
// it's okay to overwrite array in this case
$json = array('love' => $row->love, 'hate' => $row->hate);
}
else{
// no results
}
$q->free(); $db->close();
echo json_encode($json);
}
else{
// may be a hack
}
?>