Use your left/right keys to browse tutorials
Build a JSON and PHP product gallery

Build a JSON and PHP product gallery

1 Star2 Stars3 Stars4 Stars5 Stars
Posted on January 7, 2010

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



More tutorials from Papermashup
Comments
21 discussions around Build a JSON and PHP product gallery
Older Comments
  1. matth says:

    how print json ?

  2. Asterix says:

    I tried to replace jQuery 1.3.2 with jQuery 1.7.1, but it didn’t work. Do you have any idea why? Is there a way to use only jQuery 1.7.1 with this app?

  3. jhon3rick says:

    Increíble ya estamos en 24/mayo/2012 y e buscado como loco desde hace 20 dias un ejemplo de la realización y consumo de un servicio con Json….
    mil gcs

  4. Edmilson says:

    Muito útil, obrigado por compartilhar!

  5. Cahit EROZ says:

    Hello ashley.

    I’m looking for a long time an application. Thanks for sharing.

    I would like your permission to use on my site.

    However, I would like to indicate that a lack of lack of pagination. I’d like your help on what to do for paging ..

    Thank you again.

  6. joel says:

    Thanks you, you save my current job!

  7. Hello ,

    Will check out the demo ,
    useful tutorial.

    Please guide , about how we can add page numbers , if our product number increases a specific and convenient methods to deal with a situation like that.

    Can you calso provide a few tips in regards to formating it with CSS.

    Thanks

  8. Pingback: Parse XML with jQuery | Papermashup.com

Older Comments




Never miss an update from Papermashup

Get notified about the latest tutorials and downloads.

Subscribe by Email

Get alerts directly into your inbox after each post and stay updated.
Subscribe
OR

Subscribe by RSS

Add our RSS to your feedreader to get regular updates from us.
Subscribe

Get in contact

Please use the form below to get in contact. If your question is related to a free script download, please use the comments on the article page as community members are more likely to respond quicker than I can personally.

About Me

I'm Ashley Ford, Co-founder and Technical Director at Harkable.com London, UK. Previously I worked at InMobi, Spotify and MySpace. My interests include photography and making short videos I'm also an avid F1 fan. I'm always working on side projects. Here are a few: Easy Poll, We Deliver.



What do you specialise in?

I spend a lot of time coding in PHP and MySQL, as well as front end XHTML and CSS. I also specialise in javascript and the jQuery framework as well as being an avid designer. You can find me on dribbble

Interested in advertising?

If you'd like to advertise on Papermashup.com please get in touch via the contact link below for advertising opportunities.

How do I contact you

You can contact me here. and I'm available for consultation, freelance, programming book reviews.

Get on the mailing list

Join over 3000 people who have subscribed to the Papermashup inbox message, and be the first to find out about tutorial, competitions and giveaways.