TalkPHP

TalkPHP (http://www.talkphp.com/forums.php)
-   Absolute Beginners (http://www.talkphp.com/absolute-beginners/)
-   -   help with php json and javascript (http://www.talkphp.com/absolute-beginners/5654-help-php-json-javascript.html)

lee1963 12-06-2010 08:45 PM

help with php json and javascript
 
right i no this must be simple to achieve but i cnat get my head round it.
What i want to no is after i create my array in php i encode it with "json_encode and echo it out.
it comes out in the right format
but how do i use it in the javascript tags.
Any help would be greatly appreciated

Code below

<?php
mysql_connect("localhost", "root", "password") or die(mysql_error());
mysql_select_db("herefordinfo") or die(mysql_error());

$dbQuery = 'SELECT * FROM companies';
$dbResult = mysql_query($dbQuery) or die ("Could not read data because " . mysql_error());
$RowCount = mysql_numrows($dbResult);

while ($pubs = mysql_fetch_assoc($dbResult))
{
$array[] = array('id'=>$pubs['id'],'companyname'=>$pubs['companyname'],'companyinfo'=>$pubs['companyinfo'],companyimage=>$pubs['companyimage']);

}
//echo '<pre>' . print_r($array,true) . '</pre>';
echo '<pre>' . json_encode($array) . '</pre>';

?>
<html>
<head>

<script type="text/javascript">

</script>

</head>
<body>
</body>
</html>


wGEric 12-06-2010 09:29 PM

You would set the output of the PHP as a variable in the javascript. You then could access the data using the javascript variable/object.

PHP Code:

<html>
<head>

<script type="text/javascript">
<?php
mysql_connect
("localhost""root""password") or die(mysql_error());
mysql_select_db("herefordinfo") or die(mysql_error());

$dbQuery 'SELECT * FROM companies';
$dbResult mysql_query($dbQuery) or die ("Could not read data because " mysql_error());
$RowCount mysql_numrows($dbResult);

while (
$pubs mysql_fetch_assoc($dbResult))
{
$array[] = array('id'=>$pubs['id'],'companyname'=>$pubs['companyname'],'companyinfo'=>$pubs['companyinfo'],companyimage=>$pubs['companyimage']);

}
//echo '<pre>' . print_r($array,true) . '</pre>';
echo 'var data = ' json_encode($array);

?>

alert(data[0].companyname);

// if you have firebug
console.dir(data);

</script>

</head>
<body>
</body>
</html>


lee1963 12-06-2010 10:01 PM

cheers
 
you have just shot straight to th top of my xmas card list, many thx ... lee


All times are GMT. The time now is 09:12 PM.

Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.1.0