So I am using FLOT to generate some bar graphs and it uses some javascript arrays to allow for the data. I have a query that spits out the correct labels and values as so:
while ($row = mysql_fetch_array($chart_stats)){
printf("Race is: %s Percentage: %s", $row['Race'],$row['Percentage'] ."<br/>");
}
My question is can I get the values of my array from php into the array of Javascript (if that makes sense)
var d1 =[0, 72]; //instead of static value maybe var d1 = [0,<?printf($row['Percentage'])?>];
var d2 =[1,3];
var d3 = [2,40];
Thanks in advance!
Yes, you can echo stuff from PHP wherever you like. When putting it into a block of JavaScript, though, you have to be careful that:
The resulting output is ALWAYS valid code
There is no way for user-generated input to be placed into code and run
The second one is simple: never put anything you got from $_POST into a <script> tag.
As for the first, json_encode is a big help. With it, you can output almost any kind of PHP variable as a valid JavaScript one.
Related
I am successfully executing a query on an SQL database.
$sql = "SELECT id, scdTempC, scdRH, ..., gt1pt0um, reading_time FROM Sensor order by reading_time desc limit 96";
Then, there is this and I don't know, at all, what it is doing.
$scdTempC = json_encode(array_reverse(array_column($sensor_data, 'scdTempC')), JSON_NUMERIC_CHECK);
$scdRH = json_encode(array_reverse(array_column($sensor_data, 'scdRH')), JSON_NUMERIC_CHECK);
It returns a set of 96 values for each column selected. Those go into a HighCharts chart for presentation in a browser.
Then, there is this and I have no idea, at all, what it is called or what it is doing:
var scdTempC = <?php echo $scdTempC; ?>;
var scdRH = <?php echo $scdRH; ?>;
var bmeBP = <?php echo $bmeBP; ?>;
And those vars feed into the HighCharts code:
series:
[{
marker: { symbol: 'dot' }, showInLegend: false,
name: 'SCD41 Temp', data: scdTempC
}],
Is there any way to get to the individual values and do arithmetic on them? Specifically, adjust centigrade temperature to Fahrenheit or Barometric pressure in hPa to inches of Mercury. Yes, I could add another column and feed in °F or inHG, but that seems wasteful if I can adjust the numbers on the fly. The result would need to look like what came from SQL and, as far as I know, that is a CSV string of numeric values. This is being done in a .PHP file. I don't know PHP yet. If this is too crazy or complicated, then just say so and I will go the other way with adding another column of data. Maybe it is SQL that I need, not PHP. Sorry, a bit lost and it shows!
It seems like I would use "foreach" and loop through the original list making up a new list with the same format (CSV?) and adjusted values. Is that even close?
I am a long-time programmer having worked with at least 12 languages but very new to PHP and SQL. Just started working with it inside an existing project a week ago and needing some pointers for modifying it. I have done a lot, already, but got stuck, here. Since I am jumping into the middle of this, it is difficult to even know what to search for. Search hints would be gladly accepted. THANKS for any help!!!
Mike
These lines appear to be the most important for you
$scdTempC = json_encode(array_reverse(array_column($sensor_data, 'scdTempC')), JSON_NUMERIC_CHECK);
$scdRH = json_encode(array_reverse(array_column($sensor_data, 'scdRH')), JSON_NUMERIC_CHECK);
Since you say that the numbers are feeding through to the HighCharts configuration, the above must be working fine.
What the above is doing, is that each line is converting one column of the database query results into a JSON array that can be used in the JavaScript.
Since you say you have little experience in PHP, but you do have experience in SQL, I recommend you stick to what you know and use the SQL for the arithmetic. That way you have one less problem to work on, and you can concentrate on just getting that data to the chart.
What you're asking to do is quite basic, and beyond the scope of a single answer here - the short answer is that you really need to read or watch a PHP tutorial, sorry! But since you say you've used 12 languages, you should find it easy to pick up - PHP is very much like most other C-like languages, so you should not have a problem catching on.
A clue: when you want to know what a PHP function does, just put it after "https://php.net/" in a browser. example: https://php.net/array_column
It’s important to recognize that there are 4 languages in play here: SQL, PHP, HTML, and Javascript.
In a script using best practices, you will see PHP on the top, doing all the logic and data collection/manipulation (SQL calls). Under that, you’ll see a PHP close tag (?>) followed by HTML with embedded Javascript. PHP looping, conditionals, and variable substitution are accomplished as seen here:
<?php
// work with user input
// get sql stuff
// work with sql results
$scdTempC = json_encode(array_reverse(array_column($sensor_data, 'scdTempC')), JSON_NUMERIC_CHECK);
$scdRH = json_encode(array_reverse(array_column($sensor_data, 'scdRH')), JSON_NUMERIC_CHECK);
// send output to browser
?>
<html>
… snip …
<!-- simple looping example; there are other ways to do it -->
<ul>
<?php foreach($rows as $row) { ?>
<li><?php echo $row; ?></li>
<?php } ?>
</ul>
… snip …
<!-- now starts javascript -->
<script>
// note the javascript is not running yet; we are filling in values from PHP
// The javascript will run in the browser after PHP serves it
var scdTempC = <?php echo $scdTempC; ?>;
var scdRH = <?php echo $scdRH; ?>;
var bmeBP = <?php echo $bmeBP; ?>
// more javascript
// your solution is down here somewhere. While iterating through the array,
// make a call to the appropriate javascript converter function to translate
function toFahrenheit(celsius)
{
return celsius * 9 / 5 + 32;
}
function toCelsius(fahrenheit)
{
return (fahrenheit - 32) * 5 / 9;
}
</script>
Here’s the important part for you: the javascript is not executed on the server, it’s executed in the browser after the php has finished and sent its output.
It appears that you are passing an array to javascript, which is then creating the desired output.
The solution then would be to create a function in javascript to convert to the desired unit of measure, as javascript is creating its output.
My advice is to concentrate on the javascript and solve the problem there.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
javascript array converted to a php array?
I have an array in javascript, Now i need to assign javascript array to php array
i am beginner to scripting language,
Can anyone please help me
Thanks in advance.
<script type = text/javascript >
var jsArray = [];
var jsDescArray = [];
for (var i = 0; i <= <?php echo $t_num ?>; i++) {
jsArray.push( "<?php echo $url ?>="+thread[i].id );
jsDescArray.push( thread[i].title );
}
<?php
$str=json_decode('jsArray');
$str1[] = json_decode( 'jsDescArray', true );
?>
</script>
First off, Javascript is evaluated on the client-side, long after the PHP code has been scanned and dealt with on the server-side. Thus, this type of code simply cannot work.
Secondly, there's really no reason for this. Because you are filling an array in Javascript prior to assignment, you should really just pass the variables ($url) directly into $str and $str1[]. If this is something that must be dealt with on the client-side, call and retrieve data from a .php file with AJAX to transfer your Javascript arrays over.
Reference: https://developer.mozilla.org/en-US/docs/AJAX
PHP is run on the server, and the result is sent to the browser. Only then can the JavaScript be run.
To send stuff from JavaScript back to the server, you need to use AJAX or similar. You might want to reconsider your approach to problem-solving, but it really depends on the context of what you are trying to do here.
You could use JSON.stringify(array) to encode your array in JavaScript, and then use $array=json_decode($_POST['jsondata']); in your PHP script to retrieve it.
see url
Pass Javascript Array -> PHP
Firstly, I have search Stack Overflow for the answer, but I have not found a solution that works.
I am using an MVC framework (yii) to generate some views and throw them in an array. Each view is a card, and I have an array of cards ($deck) as well as an array of arrays of cards ($hands, the list of hands for each player). I'm simply trying to set a javascript variable on the front-end to store the hands created in PHP. My view has, it is worth noting, multiple lines. In fact, my current test view consists only of:
test
test
I therefore used json_encode, but it's giving me the following error when I use $.parseJSON():
Uncaught SyntaxError: Unexpected token t
I read elsewhere that it is required (for whatever reason) to use json_encode twice. I have tried this, but it does not help.
With a single json_encode, the output of echoing $hands (followed by an exit) looks pretty healthy:
[["test\ntest","test\ntest","test\ntest","test\ntest", etc...
But when I do not exit, I get a syntax error every time.
Edit: Here is a sample of my code. Note that $cards is an array of HTML normally, but in my simplified case which still errors, includes only the two lines of 'test' as mentioned above.
$deck = array();
foreach ($cards as $card) {
$deck[] = $this->renderPartial('/gamePieces/cardTest',
array('card'=>$card), true);
}
$hands = Cards::handOutCards($deck, $numCards , $numPlayers);
$hands = json_encode($hands);
echo $hands; exit;
With JavaScript, I am doing the following:
var hands = $.parseJSON('<?php echo json_encode($hands); ?>');
It errors on page load.
Any help would be appreciated!
Thanks,
ParagonRG
var hands = $.parseJSON('<?php echo json_encode($hands); ?>');
This will result in something like:
var hands = $.parseJSON('{"foobar":"baz'"}');
If there are ' characters in the encoded string, it'll break the Javascript syntax. Since you're directly outputting the JSON into Javacript, just do:
var hands = <?php echo json_encode($hands); ?>;
JSON is syntactically valid Javascript. You only need to parse it or eval it if you receive it as a string through AJAX for instance. If you're directly generating Javascript source code, just embed it directly.
Looking for a way to setup a server-side datatable using PHP to parse XML json?
Okay, I'm getting the data from wufoo and so I am also able to pull json. How can I get started with the following data?
{"Entries":[{"EntryId":"33","Field71":"","Field41":"John","Field42":"Smith","Field55":"","Field34":"2004","Field375":"Arts, Design, Entertainment, Sports and Media","Field378":"Select One","Field4":"Kayak Outfitter","Field3":"Kayak Tours, Inc","Field7":"123 Main Street","Field8":"","Field9":"New York","Field10":"New York","Field11":"54209","Field12":"United States","Field19":"(555)555-5555","Field23":"contact#email.com","Field46":"http:\/\/www.website.com","Field21":"","Field49":"","Field6":"May>September","Field65":"","Field69":"","Field25":"","Field37":"Its all about Self-Motivation.","Field30":"Yes","Field31":"Yes","Field172":"","Field39":"","DateCreated":"2009-01-30 05:46:02","CreatedBy":"public","DateUpdated":"2010-08-08 22:23:30","UpdatedBy":"User"}]}
As Charles suggests DataTables will currently only accept a JSON input with a specific format. The reason for this is that supporting abstract formats would add a lot of overhead to both the internals and the initialisation (i.e. you'd need to tell it that you want it to use //articles/book#author or whatever).
So one option is to use fnServerData ( http://datatables.net/usage/callbacks#fnServerData ) to make your own Ajax call and get the XML - than transform it into the JSON format that DataTables needs with a simple loop.
Allan
Thanks for the sample data.
You're going to need to convert the data slightly.
DataTables can take a Javascript data structure (JSON), but it has to be an array of arrays.
Your sample data has a root element called Entries, which contains an array. That's great. Unfortunately each element in that array is currently a hash -- a key/value pair.
You need only the values from that pair, not the keys.
This Javascript will convert your Entries array-of-hashes into a plain old array-of-arrays. I'm using the Javascript 1.6 for each ... in syntax here because I had a brainfart and didn't remember that we're talking about a jQuery plugin here, and wrote it without that dependency.
var entries = /* JSON as provided in question */;
var new_array = new Array();
var el = entries['Entries'].length;
for(i = 0; i < el; i++) {
var inner_array = new Array();
for each (var value in entries['Entries'][i]) {
inner_array[ inner_array.length ] = value;
}
new_array[ new_array.length ] = inner_array;
}
You can then pass new_array into the initial options hash's aaData option, as documented in the link I provided above. You will need to work out how to present the column headings yourself, given that you seem to have fallen into the anti-pattern of useless key names.
I've got an associative array in php that I want to stick into a hidden form input so that I can later get the values in javascript. Because of quoting issues, I need to urlencode the json, or htmlentity it. Once I have the object in javascript, though, what's the easiest way to get it back to plain ol' json?
OR is there a better way to approach this issue? AJAX seems like overkill here -- I'd rather pre-populate the data on the page, rather than setting up multiple requests. I suppose I could write the php object to the page inside a php-generated script tag, but that seems a bit messy, and I'm not certain that [scripts] will be parsed in every possible situation where this might be used.
If you stick the data within a field you could use decodeURIComponent to decode the value. Example:
decodeURIComponent("%5b'hello'%2c%20'world'%5d"); // ['hello', 'world']
Another approach might be to embed the JSON object in a <script> element in the PHP output. You could even go as far as to make the JSON object an argument to a function that stores it away somewhere.
<script>setupData(<?= toJSON(['hello', 'world']) ?>)</script>
When the page loads the setupData would be called with the literal ['hello', 'world'].
Oh. I guess I should have tested first. I'm using dojo, and this Just Works:
PHP:
$arr = array('nyc'=>'big apple', 'boss'=>'big banana', 'lion'=>'big cat');
$json = htmlentities(json_encode($arr));
echo '<input type="hidden" id="myHidden" value="' . $json . '" />';
Javascript:
var raw = dojo.byId('myHidden').value;
var arr = dojo.fromJson(raw);
for (var i in arr) {
console.log(i + " => " + arr[i]);
}
[sheepish grin]