Referencing php in javascript

十年热恋 提交于 2019-12-11 17:47:59

问题


I am trying to call a php code which retrieves data from mysql table and populate it to an array and accessing it in the javascript. But screen shows nothing I know for sure there is no problem with php in populating the data, and referencing the php variable in javascript I have included the file and the file is in my Eclipse (juno) project only. But still why I get this problem?

Any suggestions please?

sample.jsp:

<div id="placeholder" style="width:600px;height:300px;"></div>
<script type="text/javascript" >
$(function () {
include("db.php");
var dataset1 = "<?php echo json_encode($dataset1); ?>";
$.plot($("#placeholder"), [ dataset1 ]);
});     

db.php:

<?php header('Content-type: text/javascript'); 
$server = "localhost";
    $user="harish";
    $password="password";  
    $database = "db";
    $connection = mysql_connect($server,$user,$password);
    $db = mysql_select_db($database,$connection);
    $query = "SELECT xval,yval FROM flottable";
    $result = mysql_query($query);        
    while($row = mysql_fetch_assoc($result))
    {
        $dataset1[] = array($row['xval'],$row['yval']);
    }
?>

Reference: http://www.javascriptkit.com/javatutors/externalphp.shtml

I also googled and found out that if I add this to an .htaccess file it would work. I tried this as well but nothing works.

Any idea what the problem is?

AddType application/x-httpd-php .js
AddHandler x-httpd-php5 .js
<FilesMatch "\.(js|php)$">
SetHandler application/x-httpd-php
</FilesMatch>

回答1:


Seems you forgot to set include("db.php"); between php opening brackets.

<?php include("db.php");?> 

should do the trick




回答2:


Your include() command should be in <?php ... ?> tags, and with json_encode you don't need quotes around it (in fact using quotes will severely break your JavaScript). Correct these two errors and your code should work.



来源:https://stackoverflow.com/questions/13215286/referencing-php-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!