0

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.

Chibueze Opata
  • 9,856
  • 7
  • 42
  • 65

3 Answers3

4

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 ; 
James
  • 13,571
  • 6
  • 61
  • 83
  • 1
    You can try to view source on browser and see what is printed out – James Jun 28 '12 at 07:34
  • Actually, that was a more recent modification, my original code simply had `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! – Chibueze Opata Jun 28 '12 at 09:57
2

$.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()

See $.parseJSON() API Docs

charlietfl
  • 170,828
  • 13
  • 121
  • 150
0

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!

Community
  • 1
  • 1
Moszeed
  • 1,037
  • 1
  • 10
  • 20