I'm trying to rewrite some existing code to simplify it a bit and am running into a problem passing values. I'm pulling a record from a mySQL DB and putting it into an associative array which is then json_encoded so I can manipulate the values using javascript. The code I have below is a test example so I can get the method and syntax down before coding the whole page.
I have several places on my page where I need to display either values from the database or input values from a form that are used in more than one place.
The code below works fine if I comment out the "document.getElementById" statement. The array is created and the alert works, but I can't get the value from the array to display in the div.
I'm just learning how to do this. What am I missing?
Code:
<?php
mysql_connect("mydbip", "username", "password") or
die("Could not connect: " . mysql_error());
mysql_select_db("mydb");
$result = mysql_query("SELECT * FROM sometable WHERE id='1'");
$row = mysql_fetch_array($result, MYSQL_ASSOC);
$myarr = json_encode($row);
mysql_free_result($result);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script id="source" language="javascript" type="text/javascript">
var ar = new Object();
ar= <?php echo $myarr;?>;
if(ar["variable1"] > 0)
{
alert(ar["variable1"]);
document.getElementById("ar1").innerHTML = ar["variable1"];
}
</script>
</head>
<body>
<div id="ar1">0</div>
</body>
</html>