开发者

use php into javascript to insert value from mysql

i want to use google chart map which is a piece of javascript code that take some data and display them on a map.

the chart data value are inside the javascript.

i need to retrive values from a mysql DB an insert them into the JS can i do this with php inside a js?

google.load('visualization', '1', {packages: ['geochart']});

function drawVisualization() {
  var data = new google.visualization.DataTable();
  data.addRows(6);
  data.addColumn('string', 'Country');
  data.addColumn('number', 'Minds');
  data.setValue(0, 0, 'Germany');
  data.setValue(0, 1, 200);
 开发者_StackOverflow data.setValue(1, 0, 'United States');

i need to take the instruction: data.setValue(0,0,'germany')

and change in something like, data.setValue()

can i do this?

i can create a .php page, first connect to the DB then store the data write the js with echo and put the variable there?

thank you for your suggestion,

regards.


Simple answer: Yes!

PHP scripts are parsed by the web server before being sent out. This means that all database queries are done before any data leaves the server.

Javascript is a client side language, which means that you could simply copy+paste your javascript into a .php files, and change

setValue(0, 1, 200) 

to something like:

setValue(<?= $val1 ?>, <?= $val2 ?>, '<?= $val3 ?>');


If you want it to be static:

data.setValue(0, 0, '<? echo 'Germany'; ?>');

Else if you want it dynamic you must make an ajax request to a page that is hosting the php file that grabs the information you need.


Yes, you can embed PHP code into a javascript block and have the PHP output become part of the JS code. Note that you have to be VERY careful doing so, as it is VERY easy to introduce JS syntax errors, which kills the entire script.

<?php

$x = 1;
$y = 0
$z = 'United States';

?>

<script type="text/javascript">

data.setValue(<?php echo $x ?>, <?php echo $y ?>, <?php echo json_encode($z) ?>);

</script>

Note the use of json_encode - Anytime you're using PHP to insert string data into a JS code block, you should use JSON to ensure that whatever PHP outputs becomes syntactically valid JS.


The answer is yes, you can. JavaScript is just a part of the page content. PHP can put any variable you want anywhere on the page content. Whether it's inside the JavaScript or anywhere else makes no difference. All that matters is that's valid JavaScript or HTML or whatever else it is, just as if you were entering the data into the page content without PHP.

With all due respect, you could have just tried it. :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜