Case Study : Create Simple Ajax Application (Ajax Tabs) with PHP
Requirements : Webserver Package, already installed.

Step 1 : Make Work Folder Structure

  1. Create a folder named simpleajax in your documentroot.
  2. Save this gif file below in simpleajax folder (save gif with : right-click and save as). This image used for loader animation, that is image that will showed when doing ajax transactions.
  3. Save all this file in this tutorial on this folder.

Step 2 : Create Index File

  1. Type the following script,
    <html>
    <head>
    <title></title>
    <script type="text/javascript" src="ajax.js"></script>
    </head>
    <body>
    <center>
    <h3> Simple AJAX Tabs</h3>
    <div id="tabs">
    <a href="fallback1.php" id="tab1" class="tab" onclick="return handleOnClick(1);"> News 1</a>
    <a href="fallback2.php" id="tab2" class="tab" onclick="return handleOnClick(2);">News 2</a>
    </div>
    <br>
    <div id="content">Klik pada tab untuk mengaktifkannya.</div>
    </center>
    </body>
    </html>
    
  2. Save with name index.php
  3. Explanation : Index.php is the main file in this application. The most important for implementing Ajax is in rows 9-14. Each tab has a link on each – each a value attribute href and the onclick event handler, as in the script below,
    <a href="fallback1.php" id="tab1" class="tab" onclick="return handleOnClick(1);"> News 1</a>

    In this case, AJAX initialized when user activated the tab by clicking on it.
    When successfully executed AJAX transactions = handleOnClick function () returns false so that it will cancel the click event. AJAX and then control the process of updating the document and the href is not followed.
    When the AJAX transaction failed (XMLHttpRequest object can not be diinstansiasi, in other words, the browser does not support AJAX) = handleOnClick Function returns true and the href is followed, navigate the document in a new document pages (ie fallback pages).

    Why application provides each onClick event handler and a href URLs for each tab?

    This is to overcome if the browser of the device that is used does not support AJAX. So if the device supports AJAX, AJAX transaction to display the contents will be done . However, if not support, the news still displayed but with the lead the new web page (fallback page) contains the same news from the pages generated by the transaction AJAX.

Step 3 : Create ajax.js File

  1. Type the following script,
    var req = null;
    // Function to obtain an instance of XMLHttpRequest used in an AJAX request
    function getXHR() {
    if (window.XMLHttpRequest) {
    return new XMLHttpRequest();
    }
    else try {
    return new ActiveXObject('Msxml2.XMLHTTP');
    } catch(e) {
    try {
    return new ActiveXObject("Microsoft.XMLHTTP");
    } catch(e) {
    return null;
    }
    }
    }
    // Use AJAX to update the page content.
    // Returns true if the AJAX request succeeded, or false otherwise.
    function updateContent(url, id) {
    req = getXHR();
    if (req != null) {
    // Create a HTTP get request
    req.open('GET', url);
    // Anonymous callback function to handle state changes for the web request
    req.onreadystatechange = function() {
    // State "4" is response received.
    if (req.readyState == 4) {
    // Check for HTTP 200 - successful response from web server
    if (req.status == 200) {
    document.getElementById(id).innerHTML = req.responseText;
    } else {
    document.getElementById(id).innerHTML = 'Could not retrieve data.';
    }
    }
    // For all other states, show an animated gif indicating that content is loading
    else {
    document.getElementById(id).innerHTML = '<img id="loading" src="flickr-loader.gif"/>'; //result of download step 1
    }
    return false;
    }
    // Start the AJAX transaction
    req.send('');
    } else {
    return false;
    }
    return true;
    }
    // This is the onClick event handler for the tab links
    // index - the zero-based index of the tab that was clicked
    function handleOnClick(index) {
    // Construct the ID of the clicked tab
    var tabId = "tab" + index;
    // Update the style of the active tab.
    document.getElementById(tabId).setAttribute('class', 'activeTab');
    // Update the styles of the inactive tabs. This could also be achieved in a for loop.
    if (index != 1) {
    document.getElementById("tab" + 1).setAttribute('class', 'tab');
    }
    if (index != 2) {
    document.getElementById("tab" + 2).setAttribute('class', 'tab');
    }
    // Use AJAX to update the "content" div.
    // Construct the URL to use to retrieve the updated content
    var url = "http://localhost/helloMobile/getNews"+index+".php";
    // If the AJAX request succeeded, do not follow the original link
    if (updateContent(url, "content")) {
    return false;
    }
    // If we are here, then the AJAX transaction failed.
    // Follow the link and load the static page.
    return true;
    }
    
  2. Save with the name ajax.js
  3. Penjelasan : The primary key of AJAX is the XMLHttpRequest object. The object lies in the browser so that each browser has its own way to create the object. Function getXHR() on ajax.js script above is a function to create an instance of the XMLHttpRequest (XHR), which will be used in AJAX (Note: for IE, ajax support via ActiveX objects, rather than XHR). updateContent function() is a function that will update content of the tab via AJAX, this function will returns true if the AJAX transaction succeeded, and false if it fails.
    After that the function will create a Http get request and check the progress of the update with the onreadystatechange event. onreadystatechange event to run 3 things,

    a. If the asynchronous web request is in progress, then the loading animation will be displayed.
    b. If the AJAX request completed, then the body of the response will be used as web content of the element.
    c. If the AJAX request terminated with an error, the error will be displayed on the user, ie “Could not retrieve data”

    Transactions using the document.getElementById and element.innerHTML AJAX to update the dynamic parts of the document (in this case is the news as a dynamic part of the web).

    Function handleOnClick () is a function of event handler when the tab is clicked. This function uses the parameter index, according to the index of the tab is clicked by the user. This function will update the styling of tabs (to distinguish active tabs and inactive) and update the contents of the div content. The contents of the div content is news files according to the tab the user clicked. Content is obtainable from URL var url = “http://localhost/simpleajax/getNews” + index + “.php”;
    So the script is going to retrieve a page from getNews (index) using AJAX, in accordance with the index of the tab is clicked by the user.

Step 4 : Create get News File

  1. Type the following script,
    <?php
    sleep(2);
    echo "News 1";
    echo "Ini adalah isi berita 1";
    ?>
    
  2. Save with the name getNews1.php
  3. Then type the following script,
    <?php
    sleep(2);
    echo "News 2";
    echo "Ini adalah isi berita 2";
    ?>
    
  4. Save with the name getNews2.php
  5. Explanations : Two of these files is the original link (which is executed via AJAX) from the first and second tabs (tab berindex 1 and 2). So getNews1.php and getNews2.php will be executed when the user clicks on the tab index 1 and 2, and the browser used supports AJAX.

Step 5 : Create the fallback File

  1. Type the following script,
    <html>
    <head>
    <title></title>
    <script type="text/javascript" src="ajax.js"></script>
    </head>
    <body>
    <center>
    <h3> Simple AJAX Tabs</h3>
    <div id="tabs">
    <a href="fallback1.php" id="tab1" class="tab" onclick="return handleOnClick(1);"> News 1</a>
    <a href="fallback2.php" id="tab2" class="tab" onclick="return handleOnClick(2);">News 2</a>
    </div>
    <div id="content">
    <?php echo "News 1";
    echo "Ini adalah isi berita 1";
    ?>
    </div>
    </center>
    </body>
    </html>
    
  2. Save with the name fallback1.php
  3. Then type the following script,
    <html>
    <head>
    <title></title>
    <script type="text/javascript" src="ajax2.js"></script>
    </head>
    <body>
    <center>
    <h3> Simple AJAX Tabs</h3>
    <div id="tabs">
    <a href="fallback1.php" id="tab1" class="tab" onclick="return handleOnClick(1);"> News 1</a>
    <a href="fallback2.php" id="tab2" class="tab" onclick="return handleOnClick(2);">News 2</a>
    </div>
    <div id="content">
    <?php echo "News 2";
    echo "Ini adalah isi berita 2";
    ?>
    </div>
    </center>
    </body>
    </html>
    
  4. Save with the name fallback2.php
  5. Explanation : File fallback1.php and fallback2.php a static webpage files that will be executed when user clicks on the tab index 1 and 2, and the browser used does NOT support AJAX. So the news is still displayed but in a different way (not using AJAX).

Step 6 : Testing Code

  1. Go to http://localhost/simpleajax/
  2. Then index.php file will be showed, like the picture below,
  3. Click on one tab, so of the browser supports AJAX, loader animation will be showed. See picture.
  4. After the loading done, maka isi dari tab tersebut akan ditampilkan (dari getNews.php)
  5. Try to turnoff AJAX support in the browser (that is with non-activated javascript browser – For Firefox, it is with tools – options – content – remove the check mark on activated javascript ). See picture below.
  6. Try again with click on another tab.
  7. The news will be showed without loader animation (without AJAX) from fallback.php

Okay, be creative with AJAX :) Happy AJAX-ing :)
Others that might interesting too:

Copyright

All scripts and techniques demonstrated on itx.web.id can be used in whatever manner you wish without attribution. You cannot copy whole tutorials, either in English or translated to another language.

This post is also available in: Indonesian

: PHP

About the author

obviously, a girl. with sweet smile, off course. turning her 21 years trapped on Informatics departement and just started to having some crush with it lately. she uses wordpress. she loves php. she lo

36 Comments

  • Mr. Elliott,
    Letters via USPS sounds so novel in the internet age regardless of whether it is an individual letter produced for many, but it doesn’t sound like a pen-pal relationship. Can just one write back again towards the author from the letter?

  • Does the actual fact that Carney repeated himself so generally indicate that many White House Press Corps reporters pressed him for the problem? And if there have been that numerous concerns, could it signify the Corps blinders are coming off? It would be nice if we are reaching the bottom from the white-wash bucket, but I doubt it.

  • I think this internet site contains some real excellent info for everyone. “He who has not looked on Sorrow will never see Joy.” by Kahlil Gibran.

  • Damien Brill says:

    mobile phones and WIFI and most electronic applianes emit hardcore RADIATION (think Xray beam… microwave rays)

  • Thanks for your post here. One thing I’d like to say is that most professional domains consider the Bachelor’s Degree just as the entry level requirement for an online college diploma. Even though Associate Qualifications are a great way to begin, completing a person’s Bachelors reveals many entrances to various employment opportunities, there are numerous internet Bachelor Course Programs available through institutions like The University of Phoenix, Intercontinental University Online and Kaplan. Another thing is that many brick and mortar institutions present Online variations of their college diplomas but generally for a considerably higher fee than the firms that specialize in online degree programs.

  • There is clearly a lot to realize about this. I consider you made certain nice points in features also.

  • salope says:

    I also believe that mesothelioma cancer is a extraordinary form of melanoma that is typically found in people previously exposed to asbestos. Cancerous tissues form from the mesothelium, which is a protecting lining that covers many of the body’s internal organs. These cells typically form inside the lining of your lungs, stomach, or the sac which encircles the heart. Thanks for expressing your ideas. jdei726ya

  • The truth of it is that balanced cooking techniques need to satisfy simply THREE basic and simple conditions the food you eat should not have surplus amount of fat and salt i.e. should not be high in calories, it should retain their nutrients i.e. it shouldn’t be empty calories and above all, it should taste good. excellent Read, Terrific to find another person into their food

  • tax rebate says:

    F*ckin’ amazing things here. I’m very happy to look your article. Thank you so much and i am having a look forward to contact you. Will you please drop me a e-mail?

  • I was just searching for this info for a while. After 6 hours of continuous Googleing, at last I got it in your site. I wonder what’s the lack of Google strategy that don’t rank this type of informative sites in top of the list. Normally the top websites are full of garbage.

  • muscle x says:

    Hey! This is kind of off topic but I need some guidance from an established blog. Is it hard to set up your own blog? I’m not very techincal but I can figure things out pretty fast. I’m thinking about creating my own but I’m not sure where to start. Do you have any tips or suggestions? Many thanks

  • Got here via Bing. Nice stuff, enlightening and amusing! Liking it

  • We are a gaggle of volunteers and starting a new scheme in our community. Your site provided us with valuable information to work on. You have performed a formidable activity and our entire neighborhood will be grateful to you.

  • yeah,this is great and I like it.I will bookmark it and share on my facebook.

  • top solo ads says:

    I like what you guys are up also. Such intelligent work and reporting! Carry on the superb works guys I’ve incorporated you guys to my blogroll. I think it will improve the value of my website :) .

  • I’m not sure exactly why but this site is loading incredibly slow for me. Is anyone else having this problem or is it a problem on my end? I’ll check back later on and see if the problem still exists.

  • Lizeth Tye says:

    Great article! I loved it, I can not wait for the next one. I look forward to the next!

  • You can certainly see your expertise within the work you write. The arena hopes for more passionate writers such as you who aren’t afraid to mention how they believe. Always go after your heart. “Until you walk a mile in another man’s moccasins you can’t imagine the smell.” by Robert Byrne.

  • Thanks for giving your ideas. I would also like to say that video games have been actually evolving. Modern technology and enhancements have aided create authentic and fun games. These types of entertainment games were not actually sensible when the actual concept was first of all being experimented with. Just like other forms of technologies, video games also have had to advance by way of many years. This is testimony for the fast continuing development of video games.

  • http://foro2010-760432773.us-east-1.elb.amazonaws.com/foro2010/wiki_foro/index.php/Usuario:MakeFreewebsite says:

    I am really loving the theme/design of your weblog. Do you ever run into any web browser compatibility problems? A few of my blog visitors have complained about my website not operating correctly in Explorer but looks great in Firefox. Do you have any suggestions to help fix this problem?

  • I sorry not speak good English.Wow, fantastic blog layout! How long have you been blogging for? you make blogging look easy. The overall look of your website is fantastic, let alone the content!

  • I sorry not speak good English.I was just looking for this information for a while. After six hours of continuous Googling, at last I got it in your site. I wonder what is the lack of Google strategy that don’t rank this type of informative web sites in top of the list. Generally the top websites are full of garbage.

  • click here says:

    Thank you for the good writeup. It in fact was once a entertainment account it. Glance complex to more brought agreeable from you! However, how could we keep up a correspondence?

  • I go t see everyda som websites and wbstes tο rad artile or rνiws, but thi weblog offers feature primarily based rticles.

  • Keep up the wonderful piece of work, I read few blog posts on this website and I think that your site is really interesting and has sets of superb information.

  • hcg drops says:

    Hello there! This article couldn’t be written much better! Looking through this article reminds me of my previous roommate! He continually kept preaching about this. I most certainly will send this post to him. Pretty sure he will have a very good read. Thanks for sharing!

  • click here says:

    I am ordinarily to blogging and that i genuinely appreciate your web page content. This good write-up has genuinely peaks my interest. I am going to bookmark your net website and maintain checking for initially time information.

  • cited says:

    I collectively with my pals occurred to be reading by the best tips out of your internet blog whilst all of a sudden developed a terrible feeling I had not expressed respect towards the blog owner for those tactics. These young men are already for that cause joyful to study all of them and have now sincerely been loving them. We appreciate you genuinely really thoughtful and after that for selecting these kinds of decent subject matter a lot of people are genuinely eager to learn. Our sincere regret for not expressing appreciation to you sooner.

  • travaux says:

    Thank you, I’ve lately been looking for info about this topic for ages and yours would be the best I’ve located so far.

  • One thing I have actually noticed is the fact there are plenty of myths regarding the banking institutions intentions any time talking about property foreclosure. One delusion in particular is the fact that the bank desires your house. The lender wants your hard earned cash, not your home. They want the funds they loaned you having interest. Steering clear of the bank will only draw a new foreclosed final result. Thanks for your write-up.

  • dental seo says:

    Good aftie. i am a blogger too. and i can see which you really are a good blogger too”

  • Pharmacy says:

    This consistently amazes me exactly how bloggers for instance yourself can find some time and also the dedication to carry on creating fantastic blogposts. Your blog isgood and one of my own ought to read weblogs. I just wanted to thank you.

  • This Asian ladyboy Webcams weblog keep updated with cost-free asian ladyboy cam sexual intercourse, horny ladyboy webcam dwell chat, alluring asian ts and transsexual live sex demonstrate. If you’re looking for some beautiful asian shemale are living on cam, then its the choice of the day.

  • It’s a pity you don’t have a donate button! I’d certainly donate to this superb blog! I guess for now i’ll settle for book-marking and adding your RSS feed to my Google account. I look forward to brand new updates and will talk about this website with my Facebook group. Talk soon!

  • Things i have usually told men and women is that while searching for a good online electronics store, there are a few aspects that you have to remember to consider. First and foremost, you should make sure to find a reputable and also reliable store that has got great evaluations and rankings from other buyers and business world analysts. This will make sure that you are dealing with a well-known store that can offer good assistance and aid to its patrons. Many thanks for sharing your notions on this weblog.

Leave a Reply

Your email address will not be published. Required fields are marked *

*