943,576 Members | Top Members by Rank

Ad:
  • PHP Discussion Thread
  • Marked Solved
  • Views: 1338
  • PHP RSS
Sep 2nd, 2009
0

How do I use PHP to create a JSON object?

Expand Post »
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:
javascript Syntax (Toggle Plain Text)
  1. function formatDetail(inWatchId, inRowIndex) {
  2. alert("Length is: " + myJSON.length);
  3. }
And in the body of the page:
php Syntax (Toggle Plain Text)
  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?
Similar Threads
Reputation Points: 10
Solved Threads: 0
Newbie Poster
agrarian is offline Offline
19 posts
since Mar 2008
Sep 2nd, 2009
0

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

Don't try to mix creating your own json strings
php Syntax (Toggle Plain Text)
  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.
Sponsor
Reputation Points: 520
Solved Threads: 268
Code Monkey
ShawnCplus is offline Offline
1,564 posts
since Apr 2005
Sep 2nd, 2009
0

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

Thanks! That enabled me to get it working!
Reputation Points: 10
Solved Threads: 0
Newbie Poster
agrarian is offline Offline
19 posts
since Mar 2008

This thread is solved

Either the thread starter or a moderator has marked this thread as solved. You can most likely trust the responses and answers given. There is most likely no reason for any further responses to be posted here. If you have a related question, please start a new thread in this forum instead.

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in PHP Forum Timeline: uploading to web server
Next Thread in PHP Forum Timeline: PHP Table Pagination without Database





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC