Build a JSON and PHP product gallery

7 January 2010| 14 Comments| Print

As the title describes we’re going to look at making cross domain ajax requests using JSONP I’m also going to show you how to get data from a MySQL database and encode it into a JSON string which can be parsed using JavaScript. JSON stands for JavaScript Object Notation and essentially its a method which allows us to execute cross domain ajax requests without too much fuss. This post really follows on from my article about scraping content from a page but also allows you to send and receive GET variables through the JSON request.

What we’re going to build

To give this tutorial a valid example we’re going to display a selection of product in a gallery as seen in the image below, click here to see the demo page.

product-gallery

The PHP code

First we’re going to run through getting data from our database using a PHP while loop to get a selection of rows limited to 6. In the code below you can see that we’re getting the data and generating an array. After this we simply pass the array variable $rows into the PHP function json_encode() which will format our PHP array for us.

include('connect.php');
	$sql = "SELECT title, image, description FROM json_demo LIMIT 6";
	$result = mysql_query($sql);
		while($row = mysql_fetch_array($result))
		{
			 $rows[] = array(
			"title" => $row['title'],
			"image" => $row['image'],
			"description" => $row['description']);
		}

$json = json_encode($rows);

$callback = $_GET['callback'];
echo $callback.'('. $json . ')';	

What the JSON looks like

Below is the structured output from our json.php file.

[ { "description" : "B&O is a Danish company that designs and manufactures audio products, television sets, and telephones. It was founded in 1925 by Peter Bang and Svend Olufsen",
    "image" : "1.jpg",
    "title" : "B&O 5.1"
  },
  { "description" : "B&O is a Danish company that designs and manufactures audio products, television sets, and telephones. It was founded in 1925 by Peter Bang and Svend Olufsen",
    "image" : "2.jpg",
    "title" : "B&O TV"
  },
  { "description" : "Market leader in the UK. Roberts produce a wide range of DAB digital radios. Roberts is a consumer electronics company producing DAB, analogue and wi-fi ...",
    "image" : "3.jpg",
    "title" : "Roberts Radio"
  },
  { "description" : "Toshiba is a diversified manufacturer and marketer of advanced electronic and electrical products, spanning information & communications equipment and systems",
    "image" : "4.jpg",
    "title" : "Toshiba TV"
  },
  { "description" : "B&O is a Danish company that designs and manufactures audio products, television sets, and telephones. It was founded in 1925 by Peter Bang and Svend Olufsen",
    "image" : "5.jpg",
    "title" : "B&O Audio"
  },
  { "description" : "B&O is a Danish company that designs and manufactures audio products, television sets, and telephones. It was founded in 1925 by Peter Bang and Svend Olufsen",
    "image" : "6.jpg",
    "title" : "B&O Remote"
  }
]

Now we have the JSON format built we just need some JavaScript to parse the file and output our data. generating an ajax request for JSON is pretty straight forward. because what we’re doing is designed to work cross domain you can put an absolute URI in the request. With JSONP we must add a callback parameter which is passed into the beginning of the JSON string.

Once we have the data we’re cycling through the results and appending a div with the results into the page.

$("document").ready(function () {

    $.getJSON('http://papermashup.com/demos/jquery-json-php/json.php?callback=?', function (data) {
        $("#content").html('');
        $.each(data, function (i, item) {

            $("#content").append('<div class="product"><img src="http://papermashup.com/demos/jquery-json-php/images/' + item.image + '" width="135" height="138"/><div class="title">' + item.title + '</div><div class="description">' + item.description + '</div><div class="clear"></div></div>');

        });

    });
    $("#content").fadeIn(2000);
});

demodownload


Share:
  • Print
  • Digg
  • del.icio.us
  • Facebook
  • StumbleUpon
  • Google Bookmarks
  • DZone
  • Reddit
  • Netvibes

14 Comments

  • abcphp.com

    Build a JSON and PHP product gallery | Papermashup.com…

    As the title describes we’re going to look at making cross domain ajax requests using JSONP I’m also going to show you how to get data from a MySQL database and encode it into a JSON string which can be parsed using JavaScript. …

  • uberVU - social comments

    Social comments and analytics for this post…

    This post was mentioned on Twitter by ChoiZ: RT @ashleyford: Build a JSON and PHP product gallery http://L9.fr/BC #PHP #JSON #Papermashup.com…

  • Lorenzo Peña

    I have a question.
    The connect.php class is the common db_connect.php class for MySQL?

  • Ashley

    @Lorenzo, yeah this is a standard MySQL connection script.

  • Gabriel

    Nice Papermashup ! Te la rifas,

  • Jason

    It is faster than HTML output, but it is not so user-friendly, when the client disabled javascript.

  • HotMonitor

    Hi,
    Good script congratulations !
    Do script works with external cross domain data.js ?

    $.getJSON(‘http://domain.com/data.js?callback=?’, function (data) {
    .

  • ITキヲスク | 2009å¹´12/27~2010å¹´1/9の週間ブックマーク

    [...] jsonとPHPでギャラリーサイトを作る方法 [...]

  • Ashley

    @Hotmonitor I can’t see there being a problem using a .js file.

  • VIANTO

    how can i see json data structure after encoded, i’ve already use firebug but got confused with so many parameter…

    one more

    $.each(data, function (i, item)

    is it iterate function ? whats the i variable for ? cause i dont see you use it as an index…

    Great tutorial…
    Thanks,

  • Ashley

    @Vianto yeah to see JSON structured you can visit http://jsonformat.com/ where you can process your code to make it easier to read. hope that helps!

  • JSON and JavaScript formatting | Papermashup.com

    [...] spit it out nicely formated and easy to read. As shown in the JSON code from my earlier post on how to build a JSON product gallery [...]

  • Imbo

    is it possible to load multiple images in .. (e.g. a gallery with every record..)?

  • Parse XML with jQuery | Papermashup.com

    [...] You currently have JavaScript Disabled, we advise you enable it to have the best online experience :) 16 March 2010| No Comment| Print Vertical1244871 = false; ShowAdHereBanner1244871 = false; RepeatAll1244871 = false; BannerStyles1244871 = new Array( "a{display:block;font-size:11px;color:#888;font-family:verdana,sans-serif;margin:0 4px 10px 0;text-align:center;text-decoration:none;overflow:hidden;}", "img{border:0;clear:right;}", "a.adhere{color:#666;font-weight:bold;font-size:12px;border:1px solid #ccc;background:#e7e7e7;text-align:center;}", "a.adhere:hover{border:1px solid #999;background:#ddd;color:#333;}" ); document.write(unescape("%3Cscript src='"+document.location.protocol+"//s3.buysellads.com/1244871/1244871.js?v="+Date.parse(new Date())+"' type='text/javascript'%3E%3C/script%3E")); // end buysell ads placement I recently ran through the technique of parsing JSON with jQuery and thought i’d pick this up and show you how to parse XML. It’s pretty much the same although the big difference with using XML is that this won’t work for xml files that don’t sit outside of your domain as we’re making a standard AJAX request and you can’t make cross domain ajax request unless you’re using JSONP, more of which can be found here. [...]

Leave a comment...

Add your comment below, or trackback from your own site. You can also subscribe to these comments via RSS.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

This is a Gravatar-enabled site. To get your own globally-recognized-avatar, register at Gravatar.

Your Ad Here