SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Zealot
    Join Date
    Aug 2011
    Location
    Trinidad and Tobago
    Posts
    194
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Php Json Web service Error

    I am having an issue with a JSON web service I created with php. Keep getting garbage within my JSON when I include the line echo $_GET['jsoncallback'].'('.json_encode($posts).')'; added to that am getting an error unidentified index on line (some number) but its the line that echo $_GET['jsoncallback'].'('.json_encode($posts).')'; appears.

    If i leave that line out I get JSON but end up with an error of invalid label

    how can I solve this issue? My code is below

    Code:
    <?php
    $link = mysql_connect('localhost','root','') or die('Cannot connect to the DB');
      mysql_select_db('music_db',$link) or die('Cannot select the DB');
    
      /* grab the posts from the db */
      $query = "SELECT track.track_id, track.track_name, artist.artist_name, genre.genre_name FROM artist INNER JOIN (genre INNER JOIN track ON genre.genre_id = track.genre_id) ON artist.artist_id = track.artist_id";
      $result = mysql_query($query,$link) or die('Errant query:  '.$query);
    
      /* create one master array of the records */
      $posts = array();
      if(mysql_num_rows($result)) {
        while($post = mysql_fetch_assoc($result)) {
          $posts[] = array('post'=>$post);
        }
      }
    
      /* output in necessary format */
      header('Content-type: application/json');
      echo $_GET['jsoncallback'];
      echo "(" . json_encode($posts) . ")";
    @mysql_close($link);
    ?>

  2. #2
    SitePoint Zealot
    Join Date
    Jun 2011
    Location
    Kolding, Denmark
    Posts
    108
    Mentioned
    6 Post(s)
    Tagged
    0 Thread(s)
    Seems that you aren't passing to your script, you should call it like this script.php?jsoncallback=mycallback
    also, you can check if callback value is passed via url and if not return plain JSON:
    PHP Code:
    if(isset($_GET['jsoncallback']) && $_GET['jsoncallback']) {
        echo 
    $_GET['jsoncallback']."(".json_encode($posts).")";
    } else {
        echo 
    json_encode($posts);



Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •