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 :)
Hal yang juga menarik:

Hak Cipta

Semua skrip dan teknik dalam artikel di itx.web.id boleh digunakan sebagaimana kehendakmu tanpa perlu mencantumkan sumber. Kamu tidak boleh mengkopi seluruh artikel, dalam Bahasa Indonesia ataupun diterjemahkan ke dalam bahasa lain.


Related Articles:

Artikel terkait:

: 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

1 Comment

Tinggalkan Balasan

Alamat surel Anda tidak akan dipublikasikan. Ruas yang wajib ditandai *

x( X-( B-) ;-) :wink: :twisted: :roll: :oops: :mrgreen: :lol: :idea: :evil: :cry: :arrow: :D :?: :-| :-x :-o :-P :-D :-? :-)) :-) :-( :-& :) :( :!: 8-O 8-) 8) (Русский) (yahoo) (worship) (woot) (wave) (unsure) (tongue) (thinking) (tears) (taser) (smileydance) (sleeping) (sick) (scenic) (rofl) (rock) (party) (panic) (okok) (nottalking) (ninja) (music) (muscle) (muhaha) (money) (mmm) (lonely) (lol) (lmao) (idiot) (hungry) (highfive) (heart_beat) (heart) (headspin) (hassle) (haha) (gym) (griltongue) (goodluck) (girlkiss) (funkydance) (fish_hit) (eyeroll) (evilsmirk) (evil_grin) (drinking) (doh) (devil) (dance) (cry) (cozy) (coffee) (brokenheart) (bringit) (blush) (bigeyes) (beer) (banana_rock) (banana_ninja) (banana_cool) (applause) (annoyed) (angry) (K) (: