1

I need to pass the value of a php json object to javascript. This is how I am doing it;

  <script type="text/javascript"> var msg_top = <?php echo searchResults('windows');?>;
  </script>

This is php SearchResults function that returns json:

   function searchResults($q) {

      $host = "http://search.twitter.com/search.atom?q=" . urlencode( $q ) . "&rpp=100";
      $ch = curl_init();
      curl_setopt($ch, CURLOPT_URL, $host);
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);

    //Raw xml
      $result = curl_exec($ch);
      curl_close($ch);
      $xml = simplexml_load_string($result);
      return json_encode($xml);
      } 

There is no error in error console but there is no value received. It outputs like array(0) { } for var_dump($_POST); EDIT I added a test alert after success function and it prints out failure

This is the the script

  <head>
  <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js">
  </script>
  </head>
  <body>
  <script type="text/javascript"> var msg_top = <?php echo searchResults('windows');?>;
  </script>
  <script type="text/javascript">
    $(document).ready(function() 
    {
       $.ajax({
       url: "script.php",
       type: "POST",
       dataType: "json",
       data: "msg_top",
       success: function(msg){
       alert("success");
     }
   });
   alert("failure");
  });
  </script>
  </body>
  </html>

this is json from twitter

    <script type="text/javascript"> var test_json = {\"id\":\"tag:search.twitter.com,2005:search\\/#DIYSe_F\",\"link\":[{\"@attributes\":{\"type\":\"text\\/html\",\"href\":\"http:\\/\\/search.twitter.com\\/search?q=%23DIYSe_F\",\"rel\":\"alternate\"}},{\"@attributes\":{\"type\":\"application\\/atom+xml\",\"href\":\"http:\\/\\/search.twitter.com\\/search.atom?q=%23DIYSe_F&rpp=100\",\"rel\":\"self\"}},{\"@attributes\":{\"type\":\"application\\/opensearchdescription+xml\",\"href\":\"http:\\/\\/search.twitter.com\\/opensearch.xml\",\"rel\":\"search\"}},{\"@attributes\":{\"type\":\"application\\/atom+xml\",\"href\":\"http:\\/\\/search.twitter.com\\/search.atom?q=%23DIYSe_F&rpp=100&since_id=7750301532557312\",\"rel\":\"refresh\"}}],\"title\":\"#DIYSe_F - Twitter Search\",\"updated\":\"2010-11-24T22:20:44Z\",\"entry\":[{\"id\":\"tag:search.twitter.com,2005:7559269595488256\",\"published\":\"2010-11-24T22:20:44Z\",\"link\":[{\"@attributes\":{\"type\":\"text\\/html\",\"href\":\"http:\\/\\/twitter.com\\/_smir\\/statuses\\/7559269595488256\",\"rel\":\"alternate\"}},{\"@attributes\":{\"type\":\"image\\/png\",\"href\":\"http:\\/\\/s.twimg.com\\/a\\/1289849896\\/images\\/default_profile_5_normal.png\",\"rel\":
    \":\"image\"}}],\"title\":\"#DIYse_F HIE_STRUCT: HIERARCHICAL STRUCTURE: hierarchical structure to display \\nmessages of Functions and Qualities types\",\"content\":\"<a href=\\\"http:\\/\\/search.twitter.com\\/search?q=%23DIYse_F\\\" onclick=\\\"pageTracker._setCustomVar(2, \'result_type\', \'recent\', 3);pageTracker._trackPageview(\'\\/intra\\/hashtag\\/#DIYse_F\');\\\"><b>#DIYse_F<\\/b><\\/a> HIE_STRUCT: HIERARCHICAL STRUCTURE: hierarchical structure to display \\nmessages of Functions and Qualities types\",\"updated\":\"2010-11-24T22:20:44Z\",\"author\":{\"name\":\"_smir (Smeer)\",\"uri\":\"http:\\/\\/twitter.com\\/_smir\"}},{\"id\":\"tag:search.twitter.com,2005:7552659368189952\",\"published\":\"2010-11-24T21:54:28Z\",\"link\":[{\"@attributes\":{\"type\":\"text\\/html\",\"href\":\"http:\\/\\/twitter.com\\/_smir\\/statuses\\/7552659368189952\",\"rel\":\"alternate\"}},{\"@attributes\":{\"type\":\"image\\/png\",\"href\":\"http:\\/\\/s.twimg.com\\/a\\/1289849896\\/images\\/default_profile_5_normal.png\",\"rel\":\"image\"}}],\"title\":\"#DIYse_F SEND_MSG: users can send messages of four types i.e.  \\n\\nFunction,Quality,Solution, and delivery\",\"content\":\"<a href=\\\"http:\\/\\/search.twitter.com\\/search?q=%23DIYse_F\\\" onclick=\\\"pageTracker._setCustomVar(2, \'result_type\', \'recent\', 3);pageTracker._trackPageview(\'\\/intra
\\/hashtag\\/#DIYse_F\');\\\"><b>#DIYse_F<\\/b><\\/a> SEND_MSG: users can send messages of four types i.e.  \\n\\nFunction,Quality,Solution, and delivery\",\"updated\":\"2010-11-24T21:54:28Z\",\"author\":{\"name\":\"_smir (Smeer)\",\"uri\":\"http:\\/\\/twitter.com\\/_smir\"}},{\"id\":\"tag:search.twitter.com,2005:7548895705956352\",\"published\":\"2010-11-24T21:39:31Z\",\"link\":[{\"@attributes\":{\"type\":\"text\\/html\",\"href\":\"http:\\/\\/twitter.com\\/Babar_Shahzad\\/statuses\\/7548895705956352\",\"rel\":\"alternate\"}},{\"@attributes\":{\"type\":\"image\\/png\",\"href\":\"http:\\/\\/a1.twimg.com\\/profile_images\\/1090185625\\/29465_391454998679_533808679_3864564_6071800_n_normal.jpg\",\"rel\":\"image\"}}],\"title\":\"#DIYse_F READ_MSG: Users can read messages of all four types in  \\n\\ndifferent windows\",\"content\":\"<a href=\\\"http:\\/\\/search.twitter.com\\/search?q=%23DIYse_F\\\" onclick=\\\"pageTracker._setCustomVar(2, \'result_type\', \'recent\', 3);pageTracker._trackPageview(\'\\/intra\\/hashtag\\/#DIYse_F\');\\\"><b>#DIYse_F<\\/b><\\/a> READ_MSG: Users can read messages of all four types in  \\n\\ndifferent windows\",\"updated\":\"2010-11-24T21:39:31Z\",\"author\":{\"name\":\"Babar_Shahzad (Babar Shahzad Ch)\",\"uri\":\"http:\\/\\/twitter.com\\/Babar_Shahzad\"}}]};
XCeptable
  • 1,247
  • 6
  • 25
  • 49
  • This needs basic debugging. Does the curl request work out? What does `$xml` contain? – Pekka Nov 25 '10 at 11:22
  • @Pekka, yes, I have had added little test block of php before ajax & checked it that curl return results and also verified from http://www.jsonlint.com/ that returned json is valid. The xml contain tweets data like messages, message id, author->name etc. – XCeptable Nov 25 '10 at 11:36
  • I would save the result of what is being passed to JSON.parse() in a var. and debug that var's value using firebug and jsonlink. so something like var testJson = ""; debug; var msg_top = JSON.parse(testJson) ; – Jags Nov 25 '10 at 11:41
  • @james, what to do after that for firbug & jsonlink test once I saved value in testJson. I have already value in var msg_top. – XCeptable Nov 25 '10 at 11:47

2 Answers2

4

If you use json_encode to encode the data as JSON, the output will already be a valid JavaScript expression. So you don’t need to put it into quotes.

In fact, applying addslashes on it will turn the valid JavaScript expression into a string containing that JavaScript expression:

$json = json_encode(array('foo'=>'bar'));
var_export($json);  // '{"foo":"bar"}'
$string = addslashes($json);
var_export($str);   // '{\\"foo\\":\\"bar\\"}'

When using these values in JavaScript, $json will contain a valid object expression while $str will contain a string expression:

var json = <?php echo $json; ?>,
    str = "<?php echo $str; ?>";

This will become:

var json = {"foo":"bar"},
    str = "{\"foo\":\"bar\"}";

So just use json_encode without applying any further encoding/escaping. In your case (as searchResults does already return a JSON string):

var test_json = <?php echo searchResults('windows'); ?>;
Gumbo
  • 643,351
  • 109
  • 780
  • 844
  • @XCeptable : please check again, you can not pass a PHP simplexml object into javascript without transform it into javascript format first (JSON in this case) – ajreal Nov 25 '10 at 12:54
  • @ajreal: `json_encode` would turn that object into a string (`toString` method) first. But I’m not sure what that output looks like. – Gumbo Nov 25 '10 at 12:58
  • @ajreal, the php function returns it as json like return json_encode($xml); – XCeptable Nov 25 '10 at 13:10
  • @XCeptable: So it does return a string containing the HTML/XML code? – Gumbo Nov 25 '10 at 13:13
  • @Gumbo, actually I added addslashes to remove 'missing ) before argument' error on php assigment line – XCeptable Nov 25 '10 at 13:22
  • @Gumbo, if you ask that searchResult function returns results then yes, as I tested that by adding a little test php block & alos returned json is verified from jsonlint.com – XCeptable Nov 25 '10 at 13:25
  • @Gumbo,I added the json output from searchResult – XCeptable Nov 26 '10 at 08:26
1

If the searchResults function doesn't already return JSON, then json_encode() would be easier, e.g.

<script type="text/javascript"> 
    var msg_top = <?php echo json_encode(searchResults('windows'));?>;
</script>

If the searchResults function already returns proper JSON, you should just be able to assign the output directly, e.g.

<script type="text/javascript"> 
    var msg_top = <?php echo searchResults('windows');?>;
</script>
El Yobo
  • 14,823
  • 5
  • 60
  • 78
  • See the second part of my answer. If you _really_ have json already, then you shouldn't need to do much to get in in there. Perhaps you could post an example of what searchResults() is returning? – El Yobo Nov 25 '10 at 12:22
  • Actually, that still doesn't help, as it still doesn't show us what searchResults() is outputting. You've got to walk before you run; testing stuff in javascript is a waste of time if we don't even know what the stuff being passed from PHP to JS is. Show us the output of searchResults(). – El Yobo Nov 25 '10 at 12:45
  • How do you want to see the out put? I get two outputs from it using a loop.i.e. Like "foreach ($xml->entry as $status) { $status->author->name.''.$status->content; } $status->author->name output a name like 'El Yobo' $status->content outputs text of a tweet. – XCeptable Nov 25 '10 at 12:50
  • I added now actual input that console highlights by replacing php search function line with this when raising invalid property id error – XCeptable Nov 25 '10 at 13:03
  • 1
    See gumbo's response, he explains the same as my original post in more detail. – El Yobo Nov 25 '10 at 21:42
  • @El Yobo, yes & if you see my edited code, its like that. I added a failure block too now after success & it outputs failure. But no console errors. I have updates code – XCeptable Nov 26 '10 at 07:52