How do I use PHP to create a JSON object?

Thread Solved

Join Date: Mar 2008
Posts: 8
Reputation: agrarian is an unknown quantity at this point 
Solved Threads: 0
agrarian agrarian is offline Offline
Newbie Poster

How do I use PHP to create a JSON object?

 
0
  #1
Sep 2nd, 2009
I am trying to use a Dojo (ajax) table on my page that has detail rows in which I want to draw detail tables. The tables have a format event which calls formatDetail. In this event I would like to build a simple table using JSON data.

My problem is how do I use PHP to create the JSON data object so that my formatDetail javascript can use it?

My test code so far is, in the header:
  1. function formatDetail(inWatchId, inRowIndex) {
  2. alert("Length is: " + myJSON.length);
  3. }
And in the body of the page:
  1. $stmt = sqlsrv_query($connection,$query);
  2. while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC))
  3. {
  4. $arr[] = $row;
  5. }
  6. $objJSON = '{"sample":'.json_encode($arr).'}';
  7. echo "<script>var myJSON = $objJSON;</script>";
When I try this, the js alert displays "Length is undefined"

What am I doing wrong?
Reply With Quote Quick reply to this message  
Join Date: Apr 2005
Posts: 1,435
Reputation: ShawnCplus is a glorious beacon of light ShawnCplus is a glorious beacon of light ShawnCplus is a glorious beacon of light ShawnCplus is a glorious beacon of light ShawnCplus is a glorious beacon of light ShawnCplus is a glorious beacon of light 
Solved Threads: 233
Sponsor
ShawnCplus's Avatar
ShawnCplus ShawnCplus is offline Offline
Code Monkey

Re: How do I use PHP to create a JSON object?

 
0
  #2
Sep 2nd, 2009
Don't try to mix creating your own json strings
  1. $objJSON = array('sample' => null);
  2. // whatever
  3. $objJSON['sample'] = $arr;
  4. $objJSON = json_encode($objJSON);
  5. echo '<script type="text/javascript">var myJSON = ' . $objJSON . ';</script>
  6.  
Last edited by ShawnCplus; Sep 2nd, 2009 at 4:13 pm.
GCS d- s+ a-->? C++(++++) UL+++ P+>+++ L+++ E--- W+++
N+ o K w++(---) O? !M- V PS+>++ PE+ Y+ PGP !t- 5? X- R tv+
b+>++ DI+ D G++>+++ e+ h+>++ r y+
PMs asking for help will not be answered, post on the forums. That's what they're there for.
Reply With Quote Quick reply to this message  
Join Date: Mar 2008
Posts: 8
Reputation: agrarian is an unknown quantity at this point 
Solved Threads: 0
agrarian agrarian is offline Offline
Newbie Poster

Re: How do I use PHP to create a JSON object?

 
0
  #3
Sep 2nd, 2009
Thanks! That enabled me to get it working!
Reply With Quote Quick reply to this message  
Reply

This thread has been marked solved.
Perhaps start a new thread instead?
Message:




Views: 484 | Replies: 2
Thread Tools Search this Thread



Tag cloud for PHP
About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC