Click to find out more about our Work
July 28th, 2008

Tutorial : AJAX interface/menu using jQuery/PHP

89 Comments

Ajax Interface

Hello Guys,

I have been busy with college lately, since this is my last year in college, I need to do a very cool project to get some good marks :) . Anyways that doesn`t mean I won`t be postin tutorials here ;) . Want to present your data using AJAX/PHP/MySQL by just coding few lines ? Well here it is. This tutorial teaches you how to present data using AJAX (using jQuery) with some neat effects. We can use PHP/MySQL to store the data and call it. In this tutorial I`ll teach you how to do so with PHP. So lets begin !

You can check the demo HERE.
You can download these files HERE

Index

  1. Create the HTML page – index.html
  2. Create the PHP File – boo.php

HTML Page

Our HTML file will contain the javascript as well as the CSS styles embedded within it. We can also create the effect by creating individual files for each i.e one for javascript functions and the other for the CSS. Anyways in this tutorial, both of them will be embedded within the html page. Now First fire up your favourite HTML editor (Personally I love Dreamweaver CS3).

We will be using The jQuery Framework – jquery.js. If you want to know how the jQuery Framework works then do visit Exploring Javascript Frameworks : jQuery 1.2.6.

Step 1 – The CSS

Lets add our css first. First create a new HTML file, call it interface.html.
The following is the css code.

<style type="text/css">
body { margin:0 auto 0 auto; color:#000; font-family:Georgia, "Times New Roman", Times, serif; font-size:16px; background-color:#666666; }

.page { margin:100px auto 0 auto; width:750px;}

/*MENU START*/
#menu  { list-style:none; margin:0px; padding:0px;}

#menu li { list-style:none; display:inline; }
li.active a { background-color:#FFF;color:#000; }

#menu li a,#menu li a:link { float:left; background-color:#3c3c3c; margin-right:5px; padding:7px; color:#FFFFFF; text-decoration:none; width:6em; text-align:center;}
#menu li a:visited { }
#menu li a:hover { background-color:#327cc8 }
#menu li a:active { background-color:#FFF;color:#000; }
/* MENU END*/

#outcontent {clear:both; background-color:#FFFFFF; }
.content {background-color:#FFF; padding:10px; height:300px; margin:0px; }

#loading { clear:both; background:url(wait.gif) center top no-repeat; text-align:center;padding:33px 0px 0px 0px; font-size:12px;display:none; font-family:Verdana, Arial, Helvetica, sans-serif; }
</style>

The CSS is pretty straight forward.

  • #page will be assigned to a div, which will hold our menu and other divs
  • #menu is the CSS to display our menu tabs.
  • #loading is the CSS to display the AJAX loading image.
  • #outcontent is the container to contain .content

Put the above code inside the HEAD tag of interface.html. So interface.html will look something like the following.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>interface.html</title>
<style type="text/css">
body { margin:0 auto 0 auto; color:#000; font-family:Georgia, "Times New Roman", Times, serif; font-size:16px; background-color:#666666; }

.page { margin:100px auto 0 auto; width:750px;}

#menu  { list-style:none; margin:0px; padding:0px;}

#menu li { list-style:none; display:inline; }
li.active a { background-color:#FFF;color:#000; }

#menu li a,#menu li a:link { float:left; background-color:#3c3c3c; margin-right:5px; padding:7px; color:#FFFFFF; text-decoration:none; width:6em; text-align:center;}
#menu li a:visited { }
#menu li a:hover { background-color:#327cc8 }
#menu li a:active { background-color:#FFF;color:#000; }

.content {
background-color:#FFF; background:url(ajaxinterface.jpg) bottom right no-repeat; padding:10px; height:300px; margin:0px; }

#loading { clear:both; background:url(wait.gif) center top no-repeat; text-align:center;padding:33px 0px 0px 0px; font-size:12px;display:none; font-family:Verdana, Arial, Helvetica, sans-serif; }

#outcontent {clear:both; background-color:#FFFFFF; }

</style>
</head>

<body>
</body>
</html>

The above is the HTML page interface.html with the CSS defined in it.

Step 2 – The HTML

Ok! Since now we have coded the CSS, lets create the HTML divs inside interface.html.

  1. Inside the BODY tag lets create a div which will contain the menu and the subsequent divs.
  2. <body>
        <div class="page">
        <!-- Menu and other divs go here !-->
        </div>
    </body>
    
  3. Then we`ll create the menu Tabs.
  4. <body>
        <div class="page">
        <ul id="menu">
        <!-- you can add more tabs as you wish !-->
                 <li id="about"	><a href="#" title="about">About</a></li>
                <li id="portfolio"><a href="#" title="portfolio">Portfolio</a></li>
                <li id="contact"><a href="#" title="contact">Contact</a></li>
    	</ul>
    	<br style="clear:both;" />
        </div>
    </body>
    
  5. Now we need a container to display our Loading text and our content, so we`ll create 2 divs and lets put these divs inside another div called outcontent. The following is how it`ll look.
  6. <body>
        <div class="page">
            <div>
                <ul id="menu">
                <!-- you can add more tabs as you wish !-->
                             <li id="about"	><a href="#" title="about">About</a></li>
                            <li id="portfolio"><a href="#" title="portfolio">Portfolio</a></li>
                            <li id="contact"><a href="#" title="contact">Contact</a></li>
                </ul>
            <br style="clear:both;" />
            </div>
            <!-- #outcontent - Overall div containing Loading div &amp;amp; content div !-->
            <div id="outcontent">
               	 <div id="loading">LOADING</div>
                <div class="content"></div>
            </div>
            <!-- #outcontent end !-->
        </div>
    </body>
    

interface.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>interface.html</title>
<style type="text/css">
body { margin:0 auto 0 auto; color:#000; font-family:Georgia, "Times New Roman", Times, serif; font-size:16px; background-color:#666666; }

.page { margin:100px auto 0 auto; width:750px;}

#menu  { list-style:none; margin:0px; padding:0px;}

#menu li { list-style:none; display:inline; }
li.active a { background-color:#FFF;color:#000; }

#menu li a,#menu li a:link { float:left; background-color:#3c3c3c; margin-right:5px; padding:7px; color:#FFFFFF; text-decoration:none; width:6em; text-align:center;}
#menu li a:visited { }
#menu li a:hover { background-color:#327cc8 }
#menu li a:active { background-color:#FFF;color:#000; }

.content {
background-color:#FFF; padding:10px; height:300px; margin:0px; }

#loading { clear:both; background:url(wait.gif) center top no-repeat; text-align:center;padding:33px 0px 0px 0px; font-size:12px;display:none; font-family:Verdana, Arial, Helvetica, sans-serif; }

#outcontent {clear:both; background-color:#FFFFFF; }

</style>
</head>

<body>
<div class="page">
<div>
<ul id="menu">
             <li id="about"	><a href="#" title="about">About</a></li>
            <li id="portfolio"><a href="#" title="portfolio">Portfolio</a></li>
            <li id="contact"><a href="#" title="contact">Contact</a></li>
</ul>
<br style="clear:both;" />
</div>
<div id="outcontent">
<div id="loading">LOADING</div>
<div class="content"></div>
</div>
</div>
</body>
</html>

The page should look something like the following

empty Interface.html

Step 3 – Add the Javascript Magic !

This page would do for static pages, but we are making an AJAX powered page ! Its time to add the magic.
First if you have read the Exploring Javascript Frameworks : jQuery 1.2.6 post, it should not be a problem.

  1. First lets link to the jquery library
  2. <script src="jquery.min.js" type="text/javascript"></script>
    
  3. Next lets open the script tag again and add the following code. The following code is pretty explainatory. I have added a lot of comments to show what each and every line does.
  4. <script>
      // When the document loads do everything inside here ...
         $(document).ready(function(){
    	 $('.content').load('boo.php');	//by default initally load text from boo.php
             $('#menu a').click(function() { //start function when any link is clicked
    		 				$(".content").slideUp("slow");
    						 var content_show = $(this).attr("title"); //retrieve title of link so we can compare with php file
    							$.ajax({
    							method: "get",url: "boo.php",data: "page="+content_show,
    							beforeSend: function(){$("#loading").show("fast");}, //show loading just when link is clicked
    							complete: function(){ $("#loading").hide("fast");}, //stop showing loading when the process is complete
    							success: function(html){ //so, if data is retrieved, store it in html
    							$(".content").show("slow"); //animation
    							$(".content").html(html); //show the html inside .content div
    					 }
    				 }); //close $.ajax(
             }); //close click(
    	 }); //close $(
    </script>
    

Voila ! thats it.

Our Final interface.html page

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>interface.html</title>
<script src="jquery.min.js" type="text/javascript"></script>
 <script>
  // When the document loads do everything inside here ...
     $(document).ready(function(){
	 $('.content').load('boo.php');	//by default initally load text from boo.php
         $('#menu a').click(function() { //start function when any link is clicked
		 				$(".content").slideUp("slow");
						 var content_show = $(this).attr("title"); //retrieve title of link so we can compare with php file
							$.ajax({
							method: "get",url: "boo.php",data: "page="+content_show,
							beforeSend: function(){$("#loading").show("fast");}, //show loading just when link is clicked
							complete: function(){ $("#loading").hide("fast");}, //stop showing loading when the process is complete
							success: function(html){ //so, if data is retrieved, store it in html
							$(".content").show("slow"); //animation
							$(".content").html(html); //show the html inside .content div
					 }
				 }); //close $.ajax(
         }); //close click(
	 }); //close $(
</script>
<style type="text/css">
body { margin:0 auto 0 auto; color:#000; font-family:Georgia, "Times New Roman", Times, serif; font-size:16px; background-color:#666666; }

.page { margin:100px auto 0 auto; width:750px;}

#menu  { list-style:none; margin:0px; padding:0px;}

#menu li { list-style:none; display:inline; }
li.active a { background-color:#FFF;color:#000; }

#menu li a,#menu li a:link { float:left; background-color:#3c3c3c; margin-right:5px; padding:7px; color:#FFFFFF; text-decoration:none; width:6em; text-align:center;}
#menu li a:visited { }
#menu li a:hover { background-color:#327cc8 }
#menu li a:active { background-color:#FFF;color:#000; }

.content {
background-color:#FFF; padding:10px; height:300px; margin:0px; }

#loading { clear:both; background:url(wait.gif) center top no-repeat; text-align:center;padding:33px 0px 0px 0px; font-size:12px;display:none; font-family:Verdana, Arial, Helvetica, sans-serif; }

#outcontent {clear:both; background-color:#FFFFFF; }

</style>
</head>

<body>
<div class="page">
<div>
<ul id="menu">
             <li id="about"	><a href="#" title="about">About</a></li>
            <li id="portfolio"><a href="#" title="portfolio">Portfolio</a></li>
            <li id="contact"><a href="#" title="contact">Contact</a></li>
</ul>
<br style="clear:both;" />
</div>
<div id="outcontent">
<div id="loading">LOADING</div>
<div class="content"></div>
</div>
</div>
</body>
</html>
Pages : 1 2

This website uses IntenseDebate comments, but they are not currently loaded because either your browser doesn't support JavaScript, or they didn't load fast enough.

89 Responses to “Tutorial : AJAX interface/menu using jQuery/PHP”

  1. web dizayn
    July 3, 2010 at 7:45 pm

    hi there
    your tutorial is so explainy. thanks for your works..

  2. Massimo Agostini
    June 21, 2010 at 9:47 am

    It is possible insert a vertical scroller page in each table?

  3. Herbert Seba
    May 30, 2010 at 9:51 pm

    Siteniz çok güzel bilgiler için tesekkürler.

  4. Lars
    April 6, 2010 at 10:41 pm

    very cool!

  5. mini4
    March 23, 2010 at 6:37 am

    Great work on FF. But can you also add support for IE? It looks messy on IE8.

  6. gbtrabzon
    March 15, 2010 at 10:52 am

    i can't use lightbox image gallery,how can i use it?
    i change the boo.php for my links like #include "index.php";
    help me about lightbox please

    • rocketman1223
      April 18, 2010 at 1:14 pm

      best i can understand, you have to (re)initialize lightbox after the dynamic content is loaded. unfortunately, I don't know how to do that (and that's how i ended up here – searching for solutions to that issue).

  7. Siam
    March 15, 2010 at 8:39 am

    COOL TUTORIAL BUDDY…m/..m/…

  8. phpsnake
    February 6, 2010 at 5:15 pm

    This really helped me, i was in search of this type of tutorial, thankx alot

  9. ahmed
    January 22, 2010 at 1:38 pm

    thanks

  10. Paul
    January 9, 2010 at 1:04 am

    thanks!!!!!

  11. Jonathan
    January 2, 2010 at 3:29 am

    This tutorial is good. I'll use in a future proyect.

  12. go4webapps
    December 15, 2009 at 4:19 pm

    nice buddy… but if u inserts any simple data it’s look great na….

  13. Slavi
    December 14, 2009 at 3:00 pm

    Hi,
    nice work!
    Maybe it can cache the content of each tab in future versions ?

  14. javi
    December 2, 2009 at 6:41 am

    This is great! Thanks a lot. =)
    Just one question, I have my project and I had a menu, but I worked with iframes. Now I'd love to use this menu, but when I include the files in the boo.php file (depending on the option selected) and a submit is called from the iframe the whole page is charged I guess, and doesn't work well.

    Thanks in advance for the expert who can help me out ASAP

    • TPDesigns
      December 10, 2009 at 8:06 pm

      javi:
      I haven't used iFrames in some time myself (IE5.5/Netscape days), but if I remember correctly it was exceedingly difficult to work a subframe (or sub-sub frame, etc) or even a parent frame via Javascript. Now, I'm aware things have changed in the front-end world lately (I became an almost strictly PHP developer until recently), but from what I'm reading in this tutorial it's meant to refresh the innerHTML element of a div tag on the page, rather then refresh the entire page.

      I'd have to check W3C to see whether iFrames ended up becoming depreciated, but I would personally say that dropping the iframes from the page and using the divs as "pseudo-iframes" as it were (coupled of course with some form of AJAX to run the requests, as we're no longer doing a page refresh) would be immensely beneficial.

      If iFrames are still required, then I can only suggest (without writing something myself based on your description) that you make sure your divs that are being used are IN the iFrame page's code, rather then the base page code.

  15. babu
    November 25, 2009 at 2:46 pm

    hai,
    thank you for providing this details. this is very useful for me.
    regards
    http://www.srisoftwarez.com

  16. jogiraju
    November 24, 2009 at 10:00 am

    I'm not getting the output as shown in the demo. Instead I get the output as shown below:
    Enter text right here!My PortfolioThis could be a portfolio page !
    '; break; case "contact": echo 'Perhaps a contact page ?
    '; break; case "about": default: echo 'Default Page, About page
    '; break; } ?>

    php file is not being executed instead it is show as it is. Please help me out.

    • TPDesigns
      December 10, 2009 at 8:00 pm

      jogiraju:
      The reason you're getting the content of the php file rather then having the file parsed and executed, is for one of two reasons.
      1) You don't have the PHP server installed, in which case the PHP file is reading as plain text.
      2) You don't have the PHP server set up correctly, in which case the PHP is unable to be parsed.

  17. fabian rios
    November 19, 2009 at 11:34 pm

    i can´t make it work why? http://www.delantiguadeldarien.net/archivo/delaan...

  18. osl
    November 5, 2009 at 3:40 pm

    Thanks for the tutorial. I will be developing something with a similar idea.

  19. John
    October 10, 2009 at 1:10 pm

    Good Approach…..
    keep it up……

  20. Pat
    October 9, 2009 at 7:09 pm

    This will not work in IE8? or is in me :(

  21. ngohieutp
    September 29, 2009 at 8:20 am

    Great, thank you very much

  22. Jay
    September 19, 2009 at 1:48 am

    Hi. Great script. Thanks for sharing.
    Is it possible to have images (with two rollover states/active and inactive) instead of the text in the tabs?

    Thanks again.

  23. bobv
    September 12, 2009 at 2:07 am

    Hey Micheal~
    Can I borrow the excellent work of art? I’m afraid you’ll kill me if you see similar one coming onto the internet.

    Great job! You’re a genius!!

  24. dznocturn
    August 19, 2009 at 4:24 am

    thank’s we can do a great dynamic page with that one of the best and simple jqery plug

  25. kthxbai2u
    July 16, 2009 at 8:07 pm

    It should be like that already… From my understanding of things, the HREF attribute is set statically in the HTML/PHP page, and the JavaScript (if executed) will remove the HREF tags and use them to send the user to the right page with the ajax OnClick request. Therefore those static addresses should still exist. You can still use index.php?page=links but instead of loading the main page it should load the links page… All the ajax should still work.

    It looks as though this has been updated, I may re-implement this.

    The question still stands though, How do we keep a PHP session alive if the user is left to use this nice ajax system for an undefined amount of time?

  26. Flamur
    July 16, 2009 at 1:16 pm

    Dear Michael,

    I am trying to utilize this template you made into a school project that I have, but I am facing a couple of problems and since I know nothing about jQuery and Ajax yet I’d say its better if I ask you here :)

    My web application also has other links which are posted within the content of the pages called from the Menu tabs and I want those other links to be displayed within the content container as well.

    How do I fix this problem?

    Hoping to hear from you soon.

    Please let me know.

    • kthxbai2u
      July 16, 2009 at 8:23 pm

      Sorry for the double post, the author hasn’t been around for a long time…

      Mr Flamur:
      Open the JS code, and copy the code that removes the links and adds the OnClick event. Paste it right below the old code. Now change (‘nav ul li’) to point to the content div (‘content a’) and it should work…

      If you need help just reply back and I will make a quick tutorial for you. I have already done this.

      There is one MASSIVE flaw with this system. I am trying to find a work around for it. The flaw is that you cannot keep a PHP session open with the Ajax requests… If anyone knows a easy way around this please let me know.

      With the user being left to play with this nice Ajax site for an undefined time, the session is likley to time out…

  27. kthxbai2u
    June 15, 2009 at 11:38 pm

    Ignore the last sentance, thats a question for JQuery

    • Flamur
      July 20, 2009 at 12:36 pm

      If you could make a short step by step tutorial then I would be greatly happy :)

      Thanks.

  28. kthxbai2u
    June 15, 2009 at 11:36 pm

    Ok, so this isn’t search engine friendly?

    Is it because only the default page will be looked at by GoogleBot and other bots, but none of the rest because the bots lack javascript execution?

    Can I use this library to update the MySQL database and page in real time?

Leave a Reply

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