Introduction to Dynamic Content Swapping
How you doing everybody? I've had a lot of people ask lately how to use jQuery's Ajax mechanisms to communicate with PHP to swap out data on a page dynamically. So that's what we're going to be showing you how to do in this lesson. We're going to use jQuery's Ajax mechanisms to post a variable to a PHP script and get content back according to what that variable is.
That way we can set up links like this on a page where the page doesn't refresh or reload, but it communicates to PHP each time a link is clicked to bring new data into this page area. And I even show how to make that little loader GIF, that loader animation that you see there that's popping up. I show how to make that in Fireworks during this lesson as well towards the end. Okay.
Setting Up the HTML and jQuery
We're going to show you how to build this application from the ground up and you'll see I have index.html open, which is the homepage of my website. It could be any page of my website. And within that folder which is my website I have my index page here and jQuery 1.5.1. If you just Google jQuery, you'll go to the jQuery site and you can download the files easily. Download, it's right there on the homepage, and you can save it as a Javascript file and name it whatever you want, put it on your server.
So back in our index page, first thing we're going to do is go into the head tag and we're going to include that Javascript file, jQuery 1.5.1.js.
Building the Page Structure
That way anything I do within this index.html page, I can apply jQuery to it.
Now the next thing I want to do is go into the body tag for the page and I'm going to put in a div, then I'm going to close the div tag. Within it, I'm just going to type in 'my default content' just for now. I can change that up.
I'm going to put three links right above that div. Now we're going to leave that pound sign in the href.
Creating Links with JavaScript Events
I'm going to put a space here and I'm going to put in the onclick event and the value for the onclick event is going to be return false; so that means nothing will happen when they click this link. If you leave it just like this nothing would happen when they click this link. I'm going to use the onmousedown event to communicate with JavaScript. So I'm going to put another space here and for that link we have an onmousedown event now.
So, onmousedown of this link, when somebody clicks down on it, JavaScript is going to fire off a function called swapContent and the value that we're sending to that function is con1. And here you just put whatever you want your link to say. So I'm going to put 'Content One'. So that's what the link will display as to the user, a little blue link on the page.
Building the swapContent JavaScript Function
So since this link is now set up to run a JavaScript function called swapContent, that means on this page up here we have to put that JavaScript function in. And we have to make sure it's ready to accept one parameter because we're sending one parameter to it, one variable. Now let's duplicate that twice just so we have three to show you guys a good example. This one is going to be 'content two', this one 'three'. Here we're going to place con2, con3. Okay.
So now we're going to go up into the head tag right underneath where we applied the include for the jQuery file, we're going to apply a JavaScript function that's sitting right here on the page. Now I'm going to explain this function to you real in-depth and you can see swapContent is the function that we assign to fire off when any of these links are clicked down.
Handling Variables and Inserting the Loader
And we're sending variables that we designate to that function. All right, so here we have function swapContent and it lies dormant, just sitting here on the page, waiting until somebody clicks down on one of those links. And when they do click down, they send that variable for whichever link they're clicking to that function and you pick it up right here. Here is where you scoop that variable up. You see this little variable called cv that takes on the value of whatever you send. So if I put the word 'poopoo' right here and I click this link, it's going to fire off the function swapContent and the value of 'poopoo', the word 'poopoo', will be fed to this function and it will be housed within this variable called cv. So cv would be equal to 'poopoo'. But if I click this link, cv is equal to con1. This link, cv is equal to con2. If I click this link, cv is going to be equal to con3. That's how it works.
Now the first thing we do when that function is executed, when it's told to run, is we want to show like a little animated GIF, maybe a little fan loader that's animated or a little loader bar, and I'll show you how you can get some GIF animations made real quick and easy. So you use a jQuery selector here to target that div called #myDiv, which is sitting right here in the page. Let me say .html(, open parenthesis and then close parenthesis here and then in between double quotes you can put any type of HTML data you wish there. So what we're going to do is put a GIF animated image tag there. So we'll have an image tag with an animated GIF in it. That way we show a cool animation while things are loading so people know that something's loading on the page and they won't have any question about what's going on. And then you just say .show() and this is all jQuery functionality.
Using jQuery's .post() Method for AJAX
So you're using jQuery to target that div and put some HTML in it. It's that simple. The next line is we create a variable called url and that's going to be equal to whatever PHP script you want to use for this little application. And we're going to custom code that in just a second. Mine is going to be called 'myphpscript.php' and it's going to be living in the same folder as my index file here. If you want yours in a different folder you just put in my-folder/ and it'll pick up that PHP file in any folder.
Now the next line is jQuery's post mechanism which uses Ajax and they've made the post mechanism oh so easy in jQuery. Okay so the post mechanism or the post function can take three parameters, the first parameter being the URL which I just told you what my URL is going to be and that you place right here as the first parameter. The second parameter is any string of variables that you want to put in there. If you want to put multiple variables in there you just do the same thing I did to send this variable but you separate by commas and you can add more right there as many as you want. Just separate each one by comma and don't have a comma on the last one. It's very simple. So it's key-value pairs. So the key is contentVar and the value is cv, which that will be dynamically changing according to what people are pressing. That could be either equal to con1, con2, or con3 in our case here. But the PHP script is going to be looking for a variable named contentVar and we're going to scoop that up in the PHP file.
And the third parameter is the return data function which enables us to get data back from whichever script that the post mechanism is communicating to. So post occurs, the script is communicated with, and while it's communicated with it might take a second or two for things to occur in some cases. So that's why we show the animated GIF. And then right when the PHP file is echoing data back to this post mechanism, that's when it displays within #myDiv whichever data we're calling to display. And that will be dependent upon con1, con2, and con3. The PHP file is going to be able to distinguish between those three variables and give different content depending on which one it is. So basically you're sending a posted variable to the PHP file using jQuery's Ajax mechanism. PHP file is going to say, 'Oh, I see which variable you're sending to me and I'm going to give you this specific content because you sent that specific variable'. So when the post mechanism is finished, it puts the HTML data that's coming back from the PHP file into your div and then that replaces the animated GIF that you have there, so that won't be showing anymore. It's very simple.
Creating the PHP Backend Script
Now all we need is a PHP file. Let's go to File, New, PHP. So if you're in Notepad++ you just create a new PHP file in that, or if you're in Dreamweaver you could just do like I did. And I'm going to remove all of that data because this is going to be a PHP file with just PHP scripting in it. So let's save this into the same folder where we have our jQuery and our index file. And I'm going to name it myphpscript and it'll have a PHP extension.
So the first thing I'll do is put in a PHP block or PHP tags, opening and closing tags. On line two there we're going to scoop up the contentVar variable coming from index.html. When this swapContent function runs, right here in the post mechanism you have a variable called contentVar sent to PHP with the value of cv, whatever cv represents. In our case it's either con1, con2, or con3. So we're going to pick up the posted variable of contentVar. Then we're going to have simple if-else condition statements. So we say if the contentVar is equal to a value of con1, close parenthesis, open the curly brace and close curly brace a couple of lines down. You just want to echo out here whatever your default content is. So let's check on our index page. We had a default content of this. So let's copy that, put it right there. Very simple. else if... Actually, you can just copy this if condition all the way down to the closing bracket for it and replace this if here, or basically just put else space paste. Then do it one more time. else space paste. In the second if conditions you want to type in con2 here and con3 here, and then change the content for those. So now I have different data when I echo for con2, con3 and con1 here. Let's change this one to 'this'. That way it makes more sense. And so back in the index page, we have to have our page initially loading with that same exact content. All right, that's it. That's the basics of it.
Testing, Styling, and Finalizing the Page
You can use most any jQuery version for this, as long as it's relatively up to date. Just make sure you have your jQuery file, this JavaScript function, and then inside of your links or buttons—this can also be placed on buttons, the onmousedown—just make sure you call that JavaScript function called swapContent and feed it whatever variable that you need for that link.
All right. Now down here between each one of my links I'm going to put a couple of spaces and a bullet. So I'll have a bullet point and a couple of spaces between each link. That way they're not all crowded on each other when we go to test it out. So I'm going to load this up to my PHP-enabled server to test things out because if you're not on a PHP-enabled server, you won't see any results that you want to see. Okay, so this is what I have so far. I have three links on top separated by bullet points and then a div that holds my information. So let's click 'Content Two' and you see for a split second, it said 'put animated gift here'. That's where we're going to put an animated loader. Now let's click 'Content Three'. 'Content for the third click is now loaded any HTML or text you wish'. 'Content Two'... 'This is content that I want to load when the second link or button is clicked'. And 'Content One' is 'my default content for this page element when the page initially loads or if it's refreshed'. So say I'm on 'Content Three' and I refresh the page, it's going to automatically load 'Content One' by default, unless you put special programming for it to remember which content section it was on upon refresh, which is a whole another lesson, a whole another ballgame.
All right, I'm going to go into my HTML page and right below the script tag, still within the head tag of the document, I'm going to add some style. And that style is going to affect myDiv, whatever CSS styling that you want to add to it. And that gives us this.
How to Create an Animated Loader GIF
Now we want to make sure we have an animated GIF. So let's show you how to do that real quick.
Okay, here I am in Fireworks CS4. And I'm going to create a new Fireworks document maybe 44 by 10. We'll see if that's big enough. It looks good to me. Now I'm just going to put in a rectangle to match the size of that. You can zoom in by holding control and the mouse wheel. So there I have a rectangle that's that size. You can get the stroke and the fill to be colored any way you want. And then I'm going to put in a couple of ellipse right inside there. I'm going to make sure they have no stroke and a fill color of whatever I want. I'm going to use that orange right low now. So I'm just going to go through there, press control-Z, control-V, and copy that little guy. Maybe give him a little more space. There we go. Highlight both of them by pressing select while I highlight them. Press control-C, control-V. There we go. May looks like one more can fit. Let's add that. There we go, that worked out perfectly. Okay, so normal size, that's what it looks like.
And on the first scene of this animation, I want it to be... let's see, let's make these all alpha down. Let's go Alpha, and you can change the colors of them. You can be as creative as you want when you're making these things. There. Now the first one I want Alpha all the way up for the first frame of my animation. And to make this picture that you just created an animation, you just simply go to States, add a new state. So on state two, you just take all the elements from state one, control C, highlight them, press control C, go to state two, press control V. On this one you just put the alpha back down to 48. On this one you put it back up to 100. So you'll have an animation that starts on frame one with it bright on the first dot. And then the second frame it's bright on the second dot. And we're going to do that five times.
So as you can see, I did that five times. So I have my dot moving across. Oops, I got to make sure I get this one back down to 48 right here. So you just make sure that your dot moves along like it should through your five, or however many frames you want to put in your animation. You can even make yours go back and forth like Knight Rider's little red light. Remember how Night Rider's little red light, or KITT rather, KITT's little red light used to go back and forth? You can make your animation do that very easily by adding more frames. But if I press play on mine, you'll see what I have. That's all I need for this simple demonstration.
So I'm going to go to File, Export Wizard, continue, continue as animated GIF. Make sure it says animated GIF. Then you can check out your speeds and everything by clicking play there. Then you export, and you export to wherever your site is. So you call it loader.gif. Save.
Integrating the Loader and Final Demo
Now when we go back into the HTML file instead of showing the words 'animated gif here' we actually put the image tag in. Down in your HTML, if you're in Dreamweaver you can go up here to the image, just click loader. Let's make that say 'loader' for the alternate text. Okay, and then there's your image tag for your loader. Press control-X, take it out of the HTML, put it up here within the JavaScript. Bing boom. And let's make sure we put single quotes around this HTML, around that HTML data. We're going to change that from double quotes to single quotes. That way we can have double quotes within our HTML, no problem. So now let's see what we have when we check it out online.
Okay, I'm just going to refresh the page, press 'Content Two', you see my little loader for a second there. You can have any kind of animation you wish to have there, and it will jump into place right when the person selects new data to come into that page section.
Conclusion and Further Possibilities
And it all happens without refreshing and reloading all your other page content. So if you had a big giant web page with all kinds of stuff on it, you could have these links or little buttons or whatever you want next to some kind of little container that you have that you want to swap data for. This data can also actually be images. It'd be very easy to create an image gallery using this kind of functionality.
And also keep in mind jQuery gives you the ability to easily animate things. So even though I'm saying .show() here I can say . whatever animation jQuery has to offer me. So it can be a cool transition that you throw in there. So you just use your imagination and have a good time. Get creative with it and just know that you can animate things real easily with jQuery.
Okay so that shows you how to swap data out using jQuery, Ajax, and PHP. Okay buh-bye, talk to you real soon.