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.
Related
I'm looking to change the content of a div based on a link being clicked on a php page. The link is created through a loop and I need to pass several parameters through the URL. The div is also created through the loop so the id of the div will be variable. I'm having trouble with the AJAX to make this happen.
Below is my php:
<?php
if ($result3->num_rows > 0) {
while($row3 = $result3->fetch_assoc()) {
$tripDestination = $row3["tripDestination"];
$sessionID = $row3["$sessionID"];
$price = $row3["price"];
echo "" . $tripDestination . ' - ' . $price . "";
echo "<br />";
echo "<div id=\"trips\"></div>";
}
}
?>
I need to pass two variables in the URL: sessionID and tripDestination. I was able to load static content, but it needs to be dynamic. Here's my AJAX so far
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$.ajax({url: "sqlUpload.php?sessionID=35&tripDestination=SFO", success: function(result){
$("#div1").html(result);
}});
});
});
</script>
Thanks in advance!
I might think about sending the information from a data attribute on the link:
PHP:
<?php
if ($result3->num_rows > 0) {
while($row3 = $result3->fetch_assoc()) {
$tripDestination = $row3["tripDestination"];
$sessionID = $row3[$sessionID];
$price = $row3["price"];
// Store the organized data
$data = array(
'tripDestination'=>$tripDestination,
'sessionID'=>$sessionID,
'price'=>$price
);
?>
<!-- You can store the array into json on the data attribute -->
<a href="#" class="data-set" data-information='<?php echo json_encode($data) ?>'><?php echo $tripDestination.' - '.$price ?></a>
<br />
<div class="data-response"></div>
<?php
}
}
?>
JavaScript:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
// When user clicks the <a> that has the "data-set" class
$('.data-set').on('click',function(e){
// I like to prevent default here, just incase
e.preventDefault();
// Assign current obj
var getObj = $(this);
// Fetch the json from the attribute
var getData = getObj.data('information');
// Send
$.ajax({
// Just send to the page, no query string
url: "sqlUpload.php",
// I would send POST, personally
type: 'GET',
// This is the data being sent
data: getData,
success: function(response){
// Presumably you want to put the response into the
// accompanying div, then you can just do next()
getObj.next('.data-response').html(response);
}});
});
});
</script>
How to change files so that when you click on the "load more" button the browser dynamically adds the following entries from the database in the list
index.php
<?php
include('pdo.php');
include('item.php');
include('loadMore.php');
?>
<div id="container">
<?php foreach ($items as $item): ?>
<div class="single-item" data-id="<?= $item->id ?>">
<?= $item->show() ?>
</div>
<?php endforeach; ?>
</div>
<button id="loadMore">Загрузить ещё...</button>
<script src="/jquery-1.11.3.min.js"></script>
<script src="/script.js"></script>
item.php
<?php
class Item
{
public $id;
public $text;
function __construct($id = null, $text = null)
{
$this->id = $id;
$this->text = $text;
}
public function show()
{
return $this->text;
}
}
loadmore.php
<?php
$offset = 0;
$limit = 10;
$statement = $pdo->prepare('SELECT * FROM credit LIMIT ?, ?');
$statement->bindValue(1, $offset, PDO::PARAM_INT);
$statement->bindValue(2, $limit, PDO::PARAM_INT);
$statement->execute();
$data = $statement->fetchAll();
$items = [];
foreach ($data as $item)
{
$items[] = new Item($item['id'], $item['tel']);
}
pdo.php
<?php
$host = '127.0.0.1';
$db = 'test';
$user = 'root';
$pass = '';
$charset = 'utf8';
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$opt = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
$pdo = new PDO($dsn, $user, $pass, $opt);
script.js
function getMoreItems() {
var url = "/loadMore.php";
var data = {
//
};
$.ajax({
url: url,
data: data,
type: 'get',
success: function (res) {
//
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
//
}
});
}
How to change files so that when you click on the "load more" button the browser dynamically adds the following entries from the database in the list
I think 2 hours and I can not understand.
Help.(
I understand your confusion, I believe you're wondering why your php code in index.php doesn't work properly after you call loadMore.php using ajax.
There's one distinction you need to understand to be capable of developing for the web. The difference between server-side and client-side code.
PHP is a server-side programming language, which means that it only executes on the server. Your server returns html, or json, or text, or anything to the browser and once the response arrives at the browser, you can forget about php code.
Javascript on the other hand is a client side programming language (at least in your case) It executes on the browser.
You basically have two options:
To send back some json and loop over it using jQuery, which is the preferable choice, but I fear it requires more work.
Send back html and append it to your page, first create a file called async.php
<?php
include('pdo.php');
include('item.php');
include('loadMore.php');
?>
<?php foreach ($items as $item): ?>
<div class="single-item" data-id="<?= $item->id ?>">
<?= $item->show() ?>
</div>
<?php endforeach; ?>
in your js add to your success callback
$.ajax({
url: url,
data: data,
type: 'get',
success: function (res) {
$('#container').append(res);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
//
}
});
don't forget var url = "async.php";
First you need to attach the buttons onclick="" attribute with the ajax-method.
<button ... onclick="getMoreItems">...</button>
Second, your loadmore.php need to require_once the files it depends on:
require_once('pdo.php');
require_once('item.php');
Third, separate your logic for querying the database to a function in the pdo.php file you can call with the limits as parameters, i.e.
function getData($offset = 0, $limit = 10){
//logic
}
You should also always try to use require_once or include_once to be sure files aren't loaded several times.
Now you can call the function getData(...) from index.php before the container div to load up the initial data, remove the include to loadmore.php from index.php, and in loadmore.php write the logic to use the parameters sent from the webpage to get the next chunk of data.
The data:... in your ajax needs to pass along the "page" it wants to get, perhaps simply a counter as to how many times you have loaded more. In the loadmore.php script you then just multiply the page by the limit to get the offset.
Return the data as JSON to the ajax, parse the JSON so you can build a new div for each item, then add each div to the container-div using javascript.
Im not going in detail on all topics here, but you at least will know what tutorials to search for on google :)
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"
}
}
I am trying to share a config.inc.php in php with javascript. It works, but not with ajax... there is always the "error-function" called. Is there any way to share the config file with an working ajax?
I am using it in an apache cordova project, with bootstrap and jQuery.
Here is a part of my index.html file:
<html>
<head>
<title></title>
<link rel="stylesheet" href="lib/bootstrap/3.3.1/css/bootstrap.min.css">
<link rel="stylesheet" href="lib/bootstrap/3.3.1/css/bootstrap-theme.min.css">
<script type="text/javascript" src="js/jquery-2.1.1.min.js"></script>
<script type="text/javascript" src="lib/bootstrap/3.3.1/js/bootstrap.min.js"></script>
<script type="text/javascript" src="config.inc.php"></script>
<script type="text/javascript">
jQuery(document).ready(function(){
console.log(config_url);
jQuery.ajax({
url: config_url,
type: "POST",
dataType: "json",
data: "param=no",
success: function(html){
doSomething();
});
}, error: function(e){
alert(e); //always an alert :/
}
});
});
</script>
</head>
<body></body>
</html>
Here is my config.inc.php:
<?php
global $config;
$config["url"] = "http://192.168.1.Y/fetchdata.php";
$config["db"]["host"] = "localhost";
$config["db"]["database"] = "myDatabase";
$config["db"]["username"] = "root";
$config["db"]["password"] = "";
$config["db"]["port"] = null;
$config["db"]["socket"] = null;
?>
var config_url = <?php echo json_encode($config["url"]); ?>; //if i remove this line, ajax will work and call the "success part".
And finally the last file "fetchdata.php" for database connection:
<?php
// Allow access via php
header('Access-Control-Allow-Origin: *');
// Load configuration
require 'config.inc.php';
global $config;
$sqlconn = mysqli_connect($config["db"]["host"], $config["db"]["username"],
$config["db"]["password"], $config["db"]["database"], $config["db"]["port"],
$config["db"]["socket"]) or die(mysqli_error());
$dataquery = mysqli_query($sqlconn, "SELECT * FROM table_profil");
$arr = array();
while($row = mysqli_fetch_object($dataquery)) {
array_push($arr, array("key" => $row->key, "value" => $row->value));
}
print_r(json_encode($arr));
?>
I used XAMPP for testing. The output is
var config_url =
"http://192.168.1.Y/fetchdata.php";[{"key":"size","value":"150"},{"key":"color","value":"green"}]
Without the ''var [...] .php";'' output, it will work... But I liked to share the config.
you used javascript var in php without <script> tag? How come? use
<script>
var config_url = '<?php echo json_encode($config["url"]); ?>';
</script>
instead of
var config_url = <?php echo json_encode($config["url"]); ?>;
with that way you can pass config_url with javascript but your ajax will not work .. cause ajax not work through servers so you can't use "http://192.168.1.Y/fetchdata.php" in your ajax url .. in your ajax url just use url:'fetchdata.php', and check you link to its path
Thanks mohamed-yousef and Michael, I solved it with a part of your answers. You shown me the error and gave me hints for the solution :).
Ted wrotes the solution in Shared JSON data for php and Javascript/Ajax . I use a "GET"-Param for supporting javascript. Because my "fetchdata.php" won't have any javascript, I use it without the param => no javascript output if not needed.
My index.php includes the config with a "js" parameter; looks like ...
<script type="text/javascript" src="config.inc.php?js"></script>
... and my "config.inc.php" looks like
<?php
global $config;
$config["url"] = "http://192.168.1.Y/fetchdata.php";
....
if (isset($_GET["js"])) {
echo
'
var config = [];
config["url"] = "' . $config["url"] . '";
';
}
?>
No changes in "fetchdata.php".
This solution is working for me. Thanks everybody!
I'm not sure if it's just me or what but this seems really odd. When I click a button I have jquery send out javascript variables to a php site to be handled there. However on the php site they come up as undefined indexes. The weird part, is that they show on the html page through php's echo. NOTE: The html button is an input type="button", not a submit because I don't want to reload the page.
jquery:
var timestampst = $(timestamp).val();
var objNamest = $(objInst).val();
$.post("sendCalc.php", {
postobjNamest:objInst,
posttimestampst:timestamp},
function(data){
$("#divResult").html(data);
});
php:
//used for troubleshooting, returns Array() on the php page and Array ( [posttimestampst] => 1399973296 [postobjNamest] => test2-1
print_r($_POST);
//when the if and else are used it the php page always echos Not Working, meaning that the $_POST is not set somehow. However, the html page shows the echoed variables in the "divResult" as it should.
//when I try the code without the if and else, the php page returns Undefined Index: posttimstamp/postobjNamest. However, the html page still shows the echoed variables.
if(isset($_POST["posttimestampst"])){
$timestamp = $_POST["posttimestampst"];
echo $timestamp;
echo "<br>";
$objName = $_POST["postobjNamest"];
echo $objName;
echo "<br>";
}
else{
echo "Not Working";
}
Any help is greatly appreciated!
EDIT:
//gets selected object from a dropdown menu
selectedObj = document.getElementById("selectObj").value;
//objName in javascript taken from $objName var in php that is and the beginning of the html page.
objName = <?php echo json_encode($objName); ?>;
//objInst takes the value of the dropdown menu and assigns it as the [] in objName array
objInst = objName[selectedObj];
//timestamp is set in php and imported to java
var timestamp = <?php echo $timestamp; ?>;
EDIT 2:
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js""> </script>
</head>
<h3>Optionen und Berechnen</h3>
<form name="myForm" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
<div id="divCalc">
</div>
<input id="addObject" type="button" onclick="addObj()" value="Add Object">
<br>
<br>
<div id="divAddObj" hidden="true">
</div>
<br>
<div id="divCalc">
</div>
<div id="divResult"></div>
</form>
<script type="text/javascript" name="addObject">
var objName;
var selectedObj;
var objInst;
var timestamp = <?php echo $timestamp; ?>;
//Start select dropdown
var select_element = document.createElement("select");
select_element.setAttribute("id", "selectObj");
select_element.setAttribute("name", "selectObject");
options = new Array();
objName = <?php echo json_encode($objName); ?>;
for ( var i = 0; i < (<?php echo $arrayNum; ?>); i++ ){
options.push(new Option(objName[i], i, false, false));
}
options[0].selected = true;
for ( var option in options ){
select_element.appendChild(options[option]);
}
//End select dropdown
//check selected object
selectedObj = document.getElementById("selectObj").value;
objInst = objName[selectedObj];
var timestampst = $(timestamp).val();
var objNamest = $(objInst).val();
$.post("sendCalc.php", {
postobjNamest:objInst,
posttimestampst:timestamp},
function(data){
$("#divResult").html(data);
});
</script>
Change your code to:
objNamest = objInst.value;
timestampst = timestamp.value;
$.post("sendCalc.php", {
postobjNamest: objNamest,
posttimestampst: timestampst },
function(data){
$("#divResult").html(data);
});
You are missing the data parameter of $.post().
From the docs about post():
data
Type: PlainObject or String:
A plain object or string that is sent
to the server with the request.
Your params postobjNamest & posttimestampst do not exist for the $.post() method
It should be
$.post("sendCalc.php", {
// An "on-the-fly" created JavaScript object, which is valid
data: {
postobjNamest: objInst,
posttimestampst: timestamp
},
function(data){
var content = $.parseJSON(data);
window.console.log(content.postobjNamest);
window.console.log(content.posttimestampst);
}
});
From the docs about parseJSON():
Description: Takes a well-formed JSON string and returns the resulting
JavaScript object.
And in the PHP:
$objName = $_POST['postobjNamest'];
$timestamp = $_POST['posttimestampst'];
// Returning your values to client
// Don't echo them in PHP
echo json_encode(array(
'postobjNamest' => $objName,
'posttimestampst' => $timestamp
);
From the docs about json_encode():
json_encode — Returns the JSON representation of a value
The Javascript Object:
// Declaration
var Obj = {
propertyOne: 'value', // string
propertyTwo: 52.3654, // float
methodOne: function () {
// your function code
},
methodTwo: function () {
// your function code
}
}
//Instances
var objOne = new Obj();
objOne.methodOne();
objOne.propertyTwo;
var objTwo = new Obj();
objTwo.methodOne();
objTwo.propertyTwo;