So who is this JSON fella and whats he doing fooling around in my PHP. Well first thing my English Chap is lets get the tools very clear here. Firstly, if you are going to be making an AJAX application chances are you want to use JSON to transfer the data in between requests.
So for lets not reinvent the wheel and end up with a square. I mean thousands of years of evolution and the wheel is still round. So lets get it right with our tools to help us debug and get writing some sexy AJAX using JSON. First ensure you are using Google Chrome as your browser. The debugging in Chrome is extremely fantastic, sure you can get FireFox and then get FireBug plugin, I find most people who do that than get Chrome also enjoy dicks in their arse. Just sayin'.
Now we want to use jQuery as our JavaScript "framework" the reason for this is jQuery is polished and wants to do everything it can to make our lives sexier. Simply using jQuery day to day will increase your chances of getting laid (not verified.) Now what we want to do is basically an AJAX post/get to a PHP which returns some useful information that we then display on the page.
So lets clear up what JSON is and why we are not using the AJAX XML. JSON stands for JavaScript Object Nipples. The important bit is Object. JSON works with JavaScript Objects, so you can serialise a form into an object or if you use a PHP framework like CodeIgniter chances are you are already using objects in your code. Well I hope you are.
So lets come up with some example that we can use JSON for Erm Should of done this before hey? Why not get a random insult display thing? I like that idea. We will make a button that triggers a JSON request to pull back an insult. Or something, lets see what happens.
First lets make a basic index page, something fun maybe. Tell ya what lets shake this up and make the index page HTML, so make an index.html file. Be sure to reference jQuery in your header as well, just get it from Google than dicking around with downloads for now. Here is my code.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>Damn Girl - I Like The Way You Move</title>
<style>
* {font:14px verdana;padding:0;margin:0;color:purple;}
body {text-align:center;margin-top:50px;}
h1,h2 {font-size:18px;margin-bottom:7px;}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
</head>
<body>
<!-- We will play around with these! -->
<h1 id="header"></h1>
<h2 id="subheader"></h2>
<!-- Better have a button or something -->
<a href="http://www.amateurprotagonist.com" onClick="OnShitBusta(); return false;">
There Are So Many Things I Like About You
</a>
<!-- Feel free to delete the next bit, if you don't mind me hunting you down, game on bitches -->
<p>I stole from AmateurProtagonist.com because I am a cheapskate.</p>
<!-- Yeah I am putting script stuff here, deal with it -->
<script type="text/javascript">
// This means when the page has finished loading do this
$(function() {
OnShitBusta();
});
// This is a JavaScript function, you knew that right?
function OnShitBusta() {
}
</script>
</body>
</html>
As you see here I have some JavaScript setup already. Now basically I am going to call the function we want on page load. So not only do you learn about your friend JSON but you learn about loading elements of a page after the page has finished loading. This may save your life on day. (Note it may not, but is helpful.)
Note in my code the A tag that links to my site which has an onClick event. This call the same JavaScript function as the document ready. Also it has return false after it. Try clicking the link and nothing will happen. The return false stops it from working as a link, yet still activates the JavaScript function.
Lets start by editing OhShitBusta to make a get request to a PHP file (which we will write in a mo.)
function OnShitBusta() {
$.getJSON("WhoMe.php", function(data) {
$('#header').html(data.headline);
$('#subheader').html(data.lovethemsubs);
});
}
So he is a break down. getJSON is a jQuery function that takes a number of parameters. We have no need to send data so we will simply get data back. By using getJSON we are saying we are expecting a JSON postback from the PHP we are calling. This means we don't need to do any decoding or anything unexpected. We then take the data (postback from the script) and fill them suckas in. Now reloading the page does nothing but give you errors. You should get a 404 error in your network tab. If not you must be off track or some kind of God. I say off track.
Now then, lets create this sexy PHP page. I will comment some of it so you understand it. Be sure to pay attention as lots of people get lost at this point. (PHP file is called WhoMe.php)
<?php
// We store stuff in the array
$result = array();
// The key is how we reference it on the other end, remember what we were calling from data postback
$result['headline'] = 'But Most Of All';
$result['lovethemsubs'] = 'But YEAH Most Of All';
// Encode it like you have never encoded before
echo json_encode($result);
?>
Now this is pretty easy, so after you complete the page save it and then rerun your index.html file. Nothing happens, then the page finishes loading and BAM. Code bitches. Have a look at the network tab and you can see the data coming back from the request. Now in situations where you have tones of data or information that is hidden unless requested then using this method of loading (maybe even on click than page load) can save you seconds when it comes to showing the user what they really want. Save the extras unless they need them.
Now this is pretty unimpressive. You see how easy it is to use JSON in the JavaScript, it is already an object so JavaScript loves it. Let's make the PHP more interesting so when you click the link something happens.
<?php
// We store stuff in the array
$result = array();
// Make this random
$random = array(
'Bitch Please',
'I Like The Way Your Friend Moves',
'I Hate So Many Things About You',
'I Hate The Way You Smell So Strong',
'I Like The Way You Cant Dance',
'I Like The Way You',
'YEAH Most Of All',
'But Most Of All',
'I LIKE THE WAY YOU MOVE',
'I Wish You Didnt Put Your Hands In The Air',
'I Wish You Didnt Stare So Much'
);
// Get a random element for each line
$headLine = array_rand($random);
$subLine = array_rand($random);
// The key is how we reference it on the other end, remember what we were calling from data postback
$result['headline'] = $random[$headLine];
$result['lovethemsubs'] = $random[$subLine];
// Encode it like you have never encoded before
echo json_encode($result);
?>
Nothing to be scared of here, just creating a random array which we then select an element (key/index) from and then call that element for each line, I find this combination of lines is pretty funny what comes up.
So load up the page and see the random message. Then click the link and it will change! Keep an eye on the network tab to get an idea of what is happening and what the magic happen.

I may have been listening to this.
My personal favourite that came up was:
Bitch Please
I Wish You Didnt Put Your Hands In The Air
Hehe, anyway I hope this was a fun and different intro to using JSON in your PHP projects to load elements of a page after the page has been loaded as well as basic jQuery usage. No need to thank me, just give me all of your money.