I've got a live updating highchart on a page, index.html, which calls a php script, datatest.php, to parse a CSV file, outputs the result as json and adds it as a new point on the chart:
$.ajax({
url: 'datatest.php',
success: function(point) {
var series = chart.series[0],
shift = series.data.length > 20; // shift if the series is longer than 20
// add the point
chart.series[0].addPoint(eval(point), true, shift);
// call it again after one second
setTimeout(requestData, 1000);
},
cache: false
});
The basic PHP script stores a "line" as a session variable, so that each time the script is called, it parses the next line of the CSV file. The CSV file has two columns, one for "hi" and one for "lo".
I'm trying to add a couple of buttons to my page so that I can dynamically change the column of the CSV file that the php script is returning. The code for these buttons is below:
<form method="post" action ="datatest.php">
<input type="submit" name="HighWind" value="hi"/>
<input type="submit" name="LowWind" value="lo"/>
</form>
The chart runs perfectly and updates just fine with the default (low) values, however when I press either of the above buttons, the chart just stops. This is the PHP code I have:
<?php
$i = 0;
session_start();
$_SESSION['line'] = isset($_SESSION['line']) ? ++$_SESSION['line'] : 0;
$_SESSION['hiorlo'] = isset($_SESSION['hiorlo']) ? $_SESSION['hiorlo'] : "lo";
$handle = fopen('WindSpeed.csv', 'r');
while(($windVals = fgetcsv($handle, 1000, ',')) && $i <= $_SESSION['line']) {
$i++;
}
if(!$windVals) {
$_SESSION['line'] = 0;
}
header("Content-type: text/json");
$x = time() * 1000;
$_SESSION['hiorlo'] = isset($_POST["HighWind"]) ? $_POST["HighWind"] : "Low";
//$hiorlo POST Code
if ($_SESSION['hiorlo'] == "hi") {
$y = (float)$windVals[0];
} else {
$y = (float)$windVals[1];
}
// Create a PHP array and echo it as JSON
$ret = array($x, $y);
echo json_encode($ret);
header("Location: index.html"); // Return to frontend (index.html)
?>
The funny thing is, when I comment out the header("Location: index.html"), I'm redirected to json output of the PHP script as expected, and this is displaying the correct values depending on which button was pressed. However, with the header code left in, the chart just stops after the press.
Any help would be greatly appreciated!
Thanks,
Kevin
You are going somewhat wrong with the approach.You seem to try achieving dynamic chart refresh , for that you need to:
Make ajax call on button click's
Pass the parameter's to a function (line no in this case. Can be stored in javascript as a state variable)
Write a function to remove the previous data/point from the chart and add new point.
That should be the approach that I usually follow for charts and dynamic data pushing.
Related
I'm trying to dynamically add a new ACF repeater field value (course_slug) to the current user in Wordpress. The value to be added is a URL generated from a separate function.
If I use the following code on the original page using a static URL value for course_slug then the new value is added fine.
<?php $field_key = "field_61e9bb8b66765";
$value = get_field($field_key, "user_{$current_user_id}");
echo $value;
$value[] = array("course_slug" => "http://www.exampleurl.com");
update_field( $field_key, $value, "user_{$current_user_id}");
?>
However if I run the code in a separate PHP file using two data values sent from the original page (as per below), then I receive a 500 error.
url: 'http://localhost:8888/wordpress/wp-content/themes/cookable/write-course-to-user.php',data:{"userIDdata":finaluserid, "courseURLdata":tidycourseurlupdate},
success: function(data) {
$('#result3').html(data);
}
});
write-course-to-user.php
<?php
$userIDfinal = isset($_REQUEST['userIDdata'])?$_REQUEST['userIDdata']:"";
$courseURLfinal = isset($_REQUEST['courseURLdata'])?$_REQUEST['courseURLdata']:"";
echo $userIDfinal;
echo $courseURLfinal;
echo "user_{$userIDfinal}";
$field_key = "field_61e9bb8b66765";
$value = get_field($field_key, "user_{$userIDfinal}");
echo $value;
$value[] = array("course_slug" => $courseURLfinal);
update_field( $field_key, $value, "user_{$userIDfinal}");
?>
The three test echos in there display data as expected:
echo $userIDfinal; - displays 1
echo $courseURLfinal; - displays https://calendly.com/tjmdigital/cookable-1-week-1
echo "user_{$userIDfinal}"; displays user_1
Am I missing something daft here as to why the code will run fine in the original file but not in a linked one? Any advice hugely appreciated, thanks.
I want to query a mysql table in my project in every 1 minute. I used javascript setInterval method for timing and ajax for sending request and receives output as html. but there is many problems with it:
1- whole website goes very slow only for performing this action.
2- with this I can't query something else from database.
my code is :
function ajaxGetAllOrders(){
$.ajax('<?php echo url()?>/admin/getAllOrders',{
dataType:'json',
async: true,
success:function(data){
$('#page-content').html(data.content);
}
});
}
and interval method:
$(function(){
setInterval('ajaxGetAllOrders();',60000);
ajaxGetAllOrders();
});
I tried to create another connection to database for this but it wont help anyway.
and the php getAllOrders method:
public function getAllOrders(){
if (!$this->isAdmin()){
return;
}
$fields = DB::connection('mysql2')->table('z_orders')->orderBy('id','desc')->get();
$nFields = DB::connection('mysql2')->table('z_food_orders')->orderBy('id','desc')->get();
$count=0;
$i=1;
if (count($fields)>0){
foreach($fields as $field){
$userid = DB::connection('mysql2')->table('z_users')->whereId($field->user_id)->first();
$data['username']=$userid->name;
$data['address'] = $userid->address;
$orderId = DB::connection('mysql2')->table('z_food_orders')->whereOrderId($field->id)->first();
$foodId = DB::connection('mysql2')->table('z_foods')->whereId($orderId->food_id)->first();
$data['foodname'] =$foodId->title;
$data['foodcount'] = $orderId->foodcount;
$foodPrice = $foodId->price;
$count += $foodPrice * $orderId->foodcount;
$i++;
}
$cid = DB::connection('mysql2')->table('z_users')->whereId($userid->id)->first();
$data['customer_id'] = $cid->cctt;
$data['price']=$count;
$data['fields']=$nFields;
}
return response()->json(['content'=>view('admin.orders',$data)->render()]);
}
the whole idea behind this is user orders something.then in admin panel in orders section admin can see all orders. so i want to able that admin won't reload page and in every minute the list of orders show new orders.
I am working on a webpage that shows the amount of online players on a game server that I am running, that is updated in real time.
The problem is that I can get the amount of players online in the game server to display, but it never updates and always shows the amount of players that were on the server when the page was loaded although people leave and join the server every second.
This is the PHP code that shows the numbers (it's simple, just for testing):
<?php
echo "<a id='a1' href='#' class='online'>Loading...</a>";
?>
What I am doing is to update 'a1' every second with the new amount of online players using javascript, which calls a php function called getplayers():
<script language="JavaScript">
setInterval(function(){
document.getElementById("a1").innerHTML = '<?php echo getplayers()?>';
}, 1000);
</script>
The function getplayers() it's exactly this:
<?php
include "Status.php";
function getplayers() {
$serverb = new Status("mc.spainpvp.com", '25565');
return $serverb->online_players;
}
?>
Lastly, Status.php is a script that gets the amount of players online and more things about the server, which I am sure that works:
<html>
<?php
class Status {
public $server;
public $online, $motd, $online_players, $max_players;
public $error = "OK";
function __construct($url, $port = '25565') {
$this->server = array(
"url" => $url,
"port" => $port
);
if ( $sock = #stream_socket_client('tcp://'.$url.':'.$port, $errno, $errstr, 1) ) {
$this->online = true;
fwrite($sock, "\xfe");
$h = fread($sock, 2048);
$h = str_replace("\x00", '', $h);
$h = substr($h, 2);
$data = explode("\xa7", $h);
unset($h);
fclose($sock);
if (sizeof($data) == 3) {
$this->motd = $data[0];
$this->online_players = (int) $data[1];
$this->max_players = (int) $data[2];
}
else {
$this->error = "Cannot retrieve server info.";
}
}
else {
$this->online = false;
$this->error = "Cannot connect to server.";
}
}
}
?>
</html>
So my question is if someone knows why it always updates with the first number of players instead of putting the new number of players?
You can not call PHP functions by Javascript. PHP is processed on a server in time of request. No piece of PHP code will be visible in response, because it's already processed.
So your javascript code will actually look like:
<script language="JavaScript">
setInterval(function(){
document.getElementById("a1").innerHTML = 'XXXXX';
}, 1000);
</script>
where XXXXX is amount of players in the time of request.
So your code will every second replace elements innerHTML with the static content.
If you want to get new amount of players every second, you need to use Ajax.
You can create request on your own using XMLHttpRequest or you may use some library like jQuery and it's $.ajax method.
You also need a PHP code on a server that will provide such information.
I am facing some trouble in passing a simple variable from a php to javascript file.
I have a form which submits through a php file which basically updates the record at the server end. And if the updation is succesful, I just want to pass the message back to the javascript where I can update it on a certain section of the page.
My codes are:
Javascript code - abc.js
function expand_cards(project, SlNo)
{
name = project['project_name'];
j = "ShowForm-"+SlNo+"";
s = "<div class='edit_project_card'>";
s += "<form method='post' action='Edit_Project.php'><div class='project_form'>
// Form Contents
s += "<div class='Form_button'> <input type='submit'> </div>";
s += "</form></div>";
$("#"+j+"").html(s);
response = $.parseJSON(data);
$("#"+j+"").html(response);
}
PHP file - Edit_Project.php
<?php
//The updation stuff at the server end
if (!mysqli_query($connection,$sqlquery)) {
$response = "'Error in your code: ' . mysqli_error($connection)";
}
else {
$response = "1 record updated";
}
echo json_encode($response);
mysqli_close($connection);
?>
But the problem is the screen is printing $response variable as it is and not exactly passing it back to the javascript function as wished. I know I can use a $.post function which can can receive argument but it's a long form and passing parameters would be difficult in that.
Can anybody help me out here ?
Thanks
Dirty, but it will work:
<script type="text/javascript">
var my_var = <?php echo $some_variable; ?>
// Do something with the new my_var
some_func(my_var);
</script>
I wouldn't do too much detailed stuff with this though, if you can use AJAX that is better.
Note, this can only work on a .php file or one being read as such.
you'll want to do some variable handling in your php side because if the string is empty you'll end up with a
var my_var = ;
which will break the script. so something like:
var my_var = <?php echo "'" . $some_variable . "'";?>
if it's a string or if it's a number:
var my_var = <?php echo (empty($some_variable) ? null : $some_variable);
This is int specific, I'm sure you can come up with a function that will handle it better.
References:
empty function http://php.net/manual/en/function.empty.php
shorthand if http://davidwalsh.name/php-ternary-examples
Since you're submitting the form to the PHP file directly the browser loads the Edit_Project.php file as it would a normal page. If you want a json response to the already loaded page you'll have to use $.post or $.ajax
You can post the whole form simply by using serialize() like this:
$('#form_id').on('submit', function(e) {
// Stop the browser from posting the form
e.preventDefault();
// Post the form via Ajax
$.ajax({
url : 'Edit_Project.php',
type : 'POST',
data : $(this).serialize(),
success : function(response) {
// Here you do the HTML update
$("#"+j+"").html(response.reply);
}
});
});
The Edit_Project.php needs to be changed as well:
//The updation stuff at the server end
if (!mysqli_query($connection,$sqlquery)) {
$response = "'Error in your code: ' . mysqli_error($connection)";
}
else {
$response = "1 record updated";
}
mysqli_close($connection);
/*
* As SuperDJ suggested, you need to tell the browser that it's
* receiving a JSON ojbect although he did use the wrong content type:
*/
header('Content-Type: application/json');
/*
* According to php.net most decoders should handle a simple string as
* json object but to be safe always encode an array or an object since
* you can't know how the decoder will respond.
*/
echo json_encode(array('reply' => $response));
I am using the following to encode the html source of a ckeditor in a web application.
var updateString = app.getValue('wysiwygHomePage');
var encodedString = encodeURIComponent(updateString);
alert(encodedString);
app.httpRequest("www.xxxx.com/techy/savealldata.php", "GET", function(data, error, httpResponse){
alert(data);
},
{
"updateType":"homePage","updateString":encodedString}, "String", {}, {});
}
Then at the PHP end I am using :
<?php
$updateType = $_GET["updateType"];
$updateString = $_GET["updateString"];
$updateString2 = urldecode($updateString);
echo 'success here '.$updateType .' '.$updateString2 ;
?>
I am adding some coloured tex and the html source for this is:
<p>
<span style="color: rgb(255, 140, 0);">123</span><br />
</p>
<p>
This works okay until I cut and paste more than 32 times.
I then just get error returned from the PHP call.
I presume there are to many chars arriving at the PHP end ???
Any ideas why this is happening ?
Mr WARBY.
UPDATED PHP Code.
<?php
include 'dbdata.php';
$updateType = $_POST["updateType"];
$updateString = $_POST["updateString"];
$updateString2 = urldecode($updateString);
//echo 'success here '.$updateType .' '.$updateString2 ;
if($updateType === 'homePage')
{
$query5 = "UPDATE pageText SET HTML= "."'".$updateString2."'"." WHERE ID = 12";
//echo $query5;
echo 'Home Page Updated 2';
mysql_query($query5);
}
if($updateType === 'instructionPage')
{
$query5 = "UPDATE pageText SET HTML= "."'".$updateString2."'"." WHERE ID = 13";
echo 'Instruction Page Updated 2';
mysql_query($query5);
}
if($updateType === 'FAQPage')
{
$query5 = "UPDATE pageText SET HTML= "."'".$updateString2."'"." WHERE ID = 14";
echo 'FAQ Page Updated';
mysql_query($query5);
}
?>
There are a lot of variables in play here. You need to change your debugging strategy. Instead of testing end to end each time try isolating each component.
In Javascript, call "app.getValue('wysiwygHomePage')", encode the string, decode the string, and put it right back in the editor. Do that in a loop until you can determine if the client-side is mangling anything.
If not, try encoding a complicated string in Javascript, sending it to a PHP script that decodes/re-encodes and echos it back. Do that in a loop several times.
If you still haven't found the problem try making a PHP script that takes a complicated string, INSERTS it, SELECTs it, UPDATEs it in a loop to see if you database encoding or escaping is affecting it.
If at any point you find the string changing when it shouldn't you've probably found your problem.