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.

3
  • declare your vars between <script> & </script> tags Commented Jun 28, 2012 at 7:33
  • are you using a javascript console in your browser to debug this? is it showing any parsing errors when loading the page? Commented Jun 28, 2012 at 7:36
  • also what is being echoed in the line echo $states[0];? is it valid javascript? Commented Jun 28, 2012 at 7:37

3 Answers 3

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 ; 
Sign up to request clarification or add additional context in comments.

2 Comments

You can try to view source on browser and see what is printed out
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!
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

Comments

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!

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.