0

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!

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

About use of $_POST: you can use htmlspecialchars to circumvent XSS attacks, can't you?
Yes, you can, but that won't protect you if you dump the content directly into a <script> tag.
Beautiful! This spits out my values in an array like so: "76.9""21.0""15.6""2.8""2.4""1.9""0.3""0.0" How can I get these values indivdually into each one of those javascript vars?
If you just put var myarray = <?php echo json_encode($array); ?> (assuming the right variable name) the result will be a JavaScript array, which you can then use in any way you like.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.