I want to perform javascript functions on a page after I retrieve some values from a local database. However once the PHP code is in my javascript the javascript function won't even run in the first place. If I separate the PHP code out and run the PHP code alone, it works fine, as well as the javascript code too. Here's my code:
<?
mysql_connect("127.0.0.1:3307", "username", "password") or die ("Error fetching value from database.");
mysql_select_db("ccmalumni");
$result = mysql_query("SELECT DISTINCT value FROM ccm_bp_xprofile_data WHERE field_id = 16") or die ("What da heck");
$states = db_result_array_values($result);
echo $states[0];
mysql_close();
function db_result_array_values($result) {
for ($array = array(); $row = mysql_fetch_row($result); isset($row[1]) ? $array[$row[1]] = $row[0] : $array[] = $row[0]);
return $array; }
?>
var present = <? echo json_encode($states); ?>;
Please, what am I doing wrong? You can see the full code here.
Thanks.
3 Answers 3
json_encode will out put json string in the form that javascript can understand so basically fix like below;
var darr = <? echo json_encode($states); ?>; //Already readable JSON
var present = darr ;
2 Comments
var present = <? echo json_encode($states); ?> (who wants to do extra coding). I solved the problem by viewing the source, I discovered all my PHP code was not being processed. The problem was because I started my code with <? instead of <? php. Thanks for your help!$.parseJSON() parses a string to javascript object. var darr is already an object , is not a string, and therefore should not be passed to $.parseJSON()
Comments
if you want to get data from server to client, i think the best way is to do a ajax request.
Because you dont have to mix server with client side
(makes your code more readable, easy to understand etc.)
here you get a short description how to do it with jQuery: https://stackoverflow.com/a/415894/1067061
hope it helps, good luck!
<script>&</script>tagsecho $states[0];? is it valid javascript?