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

Tutorial : AJAX interface/menu using jQuery/PHP

96 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

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

  1. Talon
    June 7, 2009 at 9:14 am

    Hi All WOW .. that looks very nice .. I have only one question as I am new to this ajax thingy. how do i just call the php page with ajax without using the like a href onclick load this ? .. eg: my page is 700px wide and i have 5 links .. i need .. about .. a lot more in the php. sorry if i am not being to clear on what i want i am new to this :)

    as for a few of the other questions .. to include a lot of content in the main boo.php just include ( ” the_file.php ” ) ; or have php create an array of filenames from a directory. (code available). .. The way i solved the problem of loading everything at once was by using php mysql pagination … load 5 at a time or whatever. Hope this helps

  2. kei
    May 14, 2009 at 9:47 am

    thanks. it’s very easy to understand. i’ll try this right now~!

  3. Armando
    May 7, 2009 at 11:58 pm

    Hello, this example was great, I will use it adding $.localScroll() thanks.

  4. Venkat
    April 30, 2009 at 12:49 pm

    Dear All,

    I am using Ajax Menu. is working fine.But i am not able to send aspx pages in php file(boo.php).In each menu i want to send aspx pages with in div. is it possible? I am using VS.net 2005. I have to use Php file or is there any other way where i can reach the same functionality.Please let me it is very urgent.

    I am waiting for your great response.

    Thanks,
    Venkat

    • Michael
      May 1, 2009 at 9:37 pm

      Hello Venkat,

      Firstly yes you can perform AJAX requests using jQuery to aspx pages. Frankly I am not into asp. But you can easily do the requests as the syntax in jquery will remain similar.
      url : aspx page
      data : name=abc //data to that aspx page

      If you can post the code, I can help you out

      Regards

  5. For Technical Information
    April 27, 2009 at 3:38 pm

    This is really amazing………jquery is really powerful..i
    am trying to change the menu style in this …..help me
    out if u know how you can do this

  6. Robert Reynolds
    April 23, 2009 at 8:56 pm

    Great tutorial. I am trying to create a popup modal box and have it load dynamic data that is already on the page. Magento ecommerce category page with a list of products. An example can be seen here, http://www.ae.com/web/browse/category.jsp?catId=cat10025 , by mouseover a product image to reveal “Quick View” and click to see modal window. Any suggestions how I would go about this? Thanks in advance.

  7. mobilya
    April 20, 2009 at 2:33 am

    different sources on this issue than you show. Thanks

  8. Cathii
    March 26, 2009 at 10:09 am

    MikeonTV :
    Is there any way to make all the PHP run in the index file? No boo.php.

    Yes, but you would have to add to the ajax get request to tell index.php what to do and you would have to avoid outputting any additional headers.

    [code]$.ajax({
    method: "get",url: "index.php",data: "page="+content_show+"&action=get_ajax_pages",

    [/code]

    then at the very top of the index.php:

    $action=$_GET['action'];
    $page=$_GET['page'];
    
    switch($action) {
      case 'get_ajax_pages':
        your_ajax_function($page);
      break;
    
      default:
        your_default_page();
      break;
    }
  9. MikeonTV
    March 26, 2009 at 9:25 am

    Is there any way to make all the PHP run in the index file? No boo.php.

  10. Dumpman
    March 25, 2009 at 5:13 pm

    First of all, thanks Michael for this great tut.

    @kru
    Hi kru, I’m working with code igniter aswell and I’m quite interested how you’ve implemented this into the framework. Could you send me a copy of your code?

  11. Cathii
    March 6, 2009 at 6:08 am

    Thank you. This is exactly what I was looking for.

  12. Alexwebmaster
    March 3, 2009 at 3:17 pm

    Hello webmaster
    I would like to share with you a link to your site
    write me here preonrelt@mail.ru

  13. kru
    January 7, 2009 at 6:52 am

    hey thanks for the great article. really helped me a lot

    i changed a code a bit so now it utilizes code igniter mvc model and some SQL queries. if you are interested just give me a shout and i send you the (quick and dirty) code. maybe somebody would need it…

    regards

  14. miguel
    December 21, 2008 at 7:43 am

    Hi, your example its very cool. I like your approach.

    As for jim’s question, he may allready found a solution but here’s i have done it:

    I would created the links as in the example he found, and would created a function to get the URL from the browser, extract the string #something and convert it in something like…
    “content.php?page=something” and use it in an URL as an AJAX request.

    And its done each time you click a link, you change the URL, and execute a function that will get that url, get the string after ” # ” and use it in an ajax request to the server, and finally update the content.

    Of course the function to extract the URL string, should have a decision structure to check if there is no # in that case is the main page so it should load something for default.

    What do you think?

  15. Allan
    December 4, 2008 at 1:18 pm

    Thanks !!!!!!!!!!!!!
    Thanks a lot !!!!!

  16. Michael
    December 1, 2008 at 8:15 pm

    Thanks Everyone,
    You guys inspire me more.

    @synlag
    I`ll look into it. Thanks for letting me know :)

  17. synlag
    November 30, 2008 at 2:32 pm

    The boo.php in the zipfile is broken or not complete.
    Great tutorial

  18. Lee
    November 27, 2008 at 11:38 pm

    Hi Michael.

    Just fantastic. Fits perfect in to what I wanted.

    Thank you for posting.

  19. joe
    November 22, 2008 at 10:58 pm

    @Michael
    Just tried that, using a contact.php page – it does not work!
    Perhaps yo could give an example that pulls content from different .php files.

  20. Priss
    November 19, 2008 at 8:35 am

    This is great!

  21. Dtech web design
    November 18, 2008 at 8:15 pm

    Very Nice!

    All the same, can’t help but echo Dudemanstan’s comments about being SEO “unfriendly” and with the db aspect as well. Can’t wait for the follow up.

    Cheers.

  22. Reck
    November 11, 2008 at 6:58 pm

    very very very cool

  23. Abdul Kader
    November 9, 2008 at 12:06 pm

    This demo very effective

  24. Rixx
    November 6, 2008 at 6:14 pm

    Nice

  25. Juan Stilller
    November 6, 2008 at 2:51 am

    Hi, i need to load the content locally not loading the content from another server, how can i convert this script to define myself the tab content?

  26. jmadsen
    October 27, 2008 at 6:12 am

    DudeManStan,

    You are assuming a very simple site, with no db lookups. If each tab had to query the database, dynamically build its contents, etc. , your way would end up preloading all of that and make an incredibly long and unnecessary initial load time.

  27. Michael
    October 20, 2008 at 9:11 am

    Hey DudeManStan,

    Thanks for your comment. This is Tutorial is for the newbies on how to create simple AJAX request via jQuery. I have not stressed much on the server side logic. or any SEO techniques. If basically tells how to fetch small amount of content from a remote file. You can use a dbase retrieval function instead of the switch case, make it much SEO friendly as well, But people who are new to AJAX, jQuery will find it a lil difficult to understand in the beginnning.

    But thanks for the suggestion, I`ll definately work and write on a follow up in enchancing and optimizing this application.

    Regards

  28. DudeManStan
    October 20, 2008 at 5:33 am

    This is a good tutorial for what it does, but this isn’t a very smart way to use AJAX. If you are going to have a switch case that has content you might as well put the content directly inside the index.html file and then with jQuery set it as display:none

    This way it is SEO friendly, JS inactive friendly, and can then VERY easily made to work with hashes so the url can be bookmarkable plus no loading time. This is a very, very SEO unfriendly way of doing it and search engines will not find any content on the page but what is on the home page.

    AJAX should be used to pull an actual page or get data from a database or else you are misusing the real reason you should use AJAX. The switch case should be like a hello world tutorial and then you should explain how to get data from a database (MySQL).

  29. creativeMind
    October 5, 2008 at 6:02 pm

    There are possibilities, that I can can run a php function in a php file with jquery? I hope yes.

  30. Igor
    October 5, 2008 at 2:00 am

    Tab is not working correct in firefox 3.0.3. When pushed tab remains as dark as it was.
    As opposed to IE6 active tab is white as (i suppose) it should be

  31. Android
    September 29, 2008 at 5:39 pm

    Thanks for the writeup, just what I needed!

  32. Amol Bhavsar
    September 19, 2008 at 9:43 pm

    Hello Michael, nice tutorial. I got the total idea of how to use AJAX with Jquery and PHP.

    Thanks,
    Amol Bhavsar,
    Software Developer.

  33. thankful
    September 19, 2008 at 9:01 am

    I used your code here:
    http://connateholdings.com/

    Thanks very much. I have to figure out a better way to insert my header and my footer. Under the services page, the text is so long I had to increase the background height from 300 to about 900

    background-color:#FFF; padding:10px; height:300px;

    Maybe I will put something in my page to make it a variable for each page. Thank you very much.

    And if any of you have any tips for what I did, please let me know.

  34. MareceK
    September 18, 2008 at 4:21 am

    Hi.
    If I want ajax link from portfolio to contact its not working. Any idea how to do it? :)

  35. Pragan
    September 16, 2008 at 9:07 pm

    Awesome demo! Really liked it. Will try it out!

  36. Michael
    September 14, 2008 at 9:19 pm

    Hello Moses,

    I was a lil busy, so I culdn`t reply earlier. You can set the default page, by editing the boo.php

    instead of putting the default: for about, you can put it in any of the other cases.

    For example
    case “portfolio”: default: {

    }

    will cause portfolio to be the default page.

    I hope it helps
    Regards

  37. moses
    September 13, 2008 at 6:17 am

    Hai, how can i setup default tab if use method
    method: “get”,url: content_show+”.php”,

  38. moses
    September 12, 2008 at 2:47 am

    How can i set default if use like this method: “get”,url: content_show+”.php”, ?

  39. wes
    September 7, 2008 at 11:45 pm

    good tutorial btw:)

  40. wes
    September 7, 2008 at 11:39 pm

    How come that the content inside the .content div such as the about content doesn’t show in the page-source and isn’t avalaible for the jquery.js

  41. promosyon
    August 14, 2008 at 11:22 pm

    Thank you for your post it is valuable information for me

  42. name
    August 12, 2008 at 6:06 pm

    solved,just insert normal code:(

  43. name
    August 11, 2008 at 12:20 am

    Hallo,Michael
    i struggle to insert a swf,no luck,have you tried to?

  44. Michael
    August 4, 2008 at 7:52 pm

    Hey Ryan,
    Sure you can make a seperate version where it refers to different php files.

    instead of
    method: “get”,url: “boo.php”,data: “page=”+content_show,

    you can use the following code for your need
    method: “get”,url: content_show+”.php”,

    where ‘content_show’ will return value of the title tag in such links like

    About 

    therefore when the about link is clicked, ‘content_show = about’ & thus the above function will call about.php

    Regards.

  45. Michael
    August 4, 2008 at 7:46 pm

    Hey Bucio,
    Thanks for your precious comments.
    Regards

  46. Ryan Rowell
    August 4, 2008 at 3:13 am

    is there a way of doing this but with seperate versions of the boo.php. perhaps have about.php, portfolio.php, and contact.php? and then each one is loaded only when clicked on?

    I am trying to integrate this into a wordpress theme idea I am working on.

  47. Bucio
    August 3, 2008 at 7:35 pm

    ;) good work, me parece muy bueno saludos

  48. Jim
    August 2, 2008 at 1:43 am

    Michael,
    This may be the solution to my question:
    http://stilbuero.de/jquery/history/

    Jim

  49. Michael
    August 1, 2008 at 12:08 am

    Hey Jim,
    Thanks for posting in, well currently we can`t do that, since it is ajax, there is no need for the page to be reloaded or pointed to another page.
    The script inside automatically does that within the single page.

    But I`ll try to find out more about this and get back to you.

    Regards

  50. Jim
    July 31, 2008 at 11:24 pm

    Is there a way to create a unique page address for each of the tab pages? For example, if you wanted to have a site map with links to each of the tabs. Something like …mypage.php?page=portfolio.

    Nice work.

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>