Categories
PHP

Menampilkan Data dari Database dengan CodeIgniter + AJAX dalam Template JQuery UI

Studi Kasus : Membaca data dari database, menampilkan dalam JQuery UI Tab dengan AJAX.
Kebutuhan : Webserver package already installed.
File Download: 1. CodeIgniter. 2. JQuery. 3. JQuery UI Kalau belum pernah menggunakan UI ini, download saja tema yang sudah ada tanpa customize dulu. 4. Mic JQuery Template Plugin.
Skill khusus : PHP. Codeigniter.

A. Mempersiapkan Database
1. Buat database dengan nama db_tutorial.
2. Buat tabel dengan nama tb_book, dengan struktur tabel dibawah ini,

3. Insert-kan beberapa sample data dalam tb_book.
4. Buat tabel lagi dengan nama tb_member, dengan struktur tabel dibawah ini,

5. Insert-kan beberapa sample data dalam tb_member.
6. Okay, done with database.

B. Mempersiapkan folder kerja dan file – file yang dibutuhkan.
1. Persiapkan folder dengan nama ci_tutor dalam document root anda.
2. Ekstrak codeigniter dalam folder yang baru saja dibuat (disini file user_guide dalam CI saya hapus), dan atur config nya meliputi base_url, serta konfigurasi database dalam system-application-config-database.php
3. Buat tabel dengan nama cssjs, kemudian taruh file JQuery (file download 2) JQuery UI (hasil download file 3 : saya memilih template flickr), dan file Mic JQuery Template Plugin (file 4) ke dalam folder cssjs.
4. Struktur folder ci_tutor adalah seperti ini,

5. Struktur folder cssjs adalah seperti ini,

C. Model
1. Kita akan membuat model yang akan mengambil seluruh data yang ada dalam tb_book dan tb_member. Ketikkan script dibawah ini,

[sourcecode language=”php”]
<?php
class Book_model extends Model {

public function getBook() {
$query = $this->db->get( ‘tb_book’ );
if( $query->num_rows() > 0 ) {
return $query->result();
} else {
return array();
}
}

public function getMember() {
$query = $this->db->get( ‘tb_member’ );
if( $query->num_rows() > 0 ) {
return $query->result();
} else {
return array();
}
}
}
?>
[/sourcecode]

2. Simpan dengan nama book_model.php dan simpan dalam system-application-models.

D. Controller
1. Ketikkan script dibawah ini,

[sourcecode language=”php”]
<?php
class Book_con extends Controller {
public function __construct() {
parent::__construct();
$this->load->model(‘book_model’);
}
public function index() {
$this->load->view(‘book_view’);
}
public function readBook() {
echo json_encode( $this->book_model->getBook() );
}
public function readMember() {
echo json_encode( $this->book_model->getMember() );
}
}
?>
[/sourcecode]

2. Simpan dengan nama book_con.php dan simpan dalam system-application-controllers.

E. View
1. Ketikkan script dibawah ini,

[sourcecode language=”php”]
<html>
<head>
<title>ITX.WEB.ID</title>
<base href="<?php echo base_url(); ?>" />
<link type="text/css" rel="stylesheet" href="cssjs/flick/jquery-ui-1.8.2.custom.css" />
<link type="text/css" rel="stylesheet" href="cssjs/styles.css" />
</head>
<body>
<center><h2> Book & Member List</h2></center>
<div id="tabs">

<ul>
<li><a href="#read">Book List</a></li>
<li><a href="#read2">Member List</a></li>
</ul>

<div id="read">
<table id="tabel"></table>
</div>

<div id="read2">
<table id="tabel2"></table>
</div>

</div>

<script type="text/javascript" src="cssjs/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="cssjs/jquery-ui-1.8.2.min.js"></script>
<script type="text/javascript" src="cssjs/jquery-templ.js"></script>

<script type="text/template" id="readTemp">
<tr>
<td>${id}</td>
<td>${title}</td>
<td>${author}</td>
</tr>

</script>

<script type="text/template" id="readTemp2">
<tr>
<td>${no}</td>
<td>${name}</td>
<td>${address}</td>
</tr>

</script>

<script type="text/javascript" src="cssjs/all.js"></script>
</body>
</html>
[/sourcecode]

2. Simpan dengan nama book_view.php dan simpan dalam system-application-views.

F. Membuat file Javascript yang akan membaca record tabel dari server dengan AJAX.
1. Ketikkan script dibawah ini,

[sourcecode language=”javascript”]
$( function() {
$( ‘#tabs’ ).tabs({
fx: { height: ‘toggle’, opacity: ‘toggle’ }
});

$.ajax({
url: ‘index.php/book_con/readBook’,
dataType: ‘json’,
success: function( response ) {
$( ‘#readTemp’ ).render( response ).appendTo( "#tabel" );
}
});

$.ajax({
url: ‘index.php/book_con/readMember’,
dataType: ‘json’,
success: function( response ) {
$( ‘#readTemp2’ ).render( response ).appendTo( "#tabel2" );
}
});

});
[/sourcecode]

2. Simpan dengan nama all.js dan simpan dalam folder cssjs.

G. Mengatur tampilan
1. Ketik script berikut ini dan simpan dengan nama style.css

[sourcecode language=”css”]
body {
font-family: Arial, Helvetica, sans-serif;
}

#tabs {
font-size: .9em;
margin: 0 auto;
width: 800px;
}

.ui-widget-content {
font-size: .8em;
}

#tabel, #tabel2 {
font-size: 1.3em;
width: 100%;
}

#tabel tr:nth-child(2n) {
background: #EAEAEA;
}

#tabel tr:hover {
background: #CCCCCC;
}

#tabel td {
padding: 6px;
margin: 8px;
}
[/sourcecode]

H. Testing code
1. Pergi ke browser, dan jalankan http://localhost/ci_tutor/index.php/book_con/
2. Jika sukses, anda akan melihat tampilan di bawah ini.

3. Klik pada tab Member List, maka akan ditampilkan data member dari dalam tb_member

4. Silahkan berkreasi dengan JQuery UI yang lain 😀

Happy coding 😀

Categories
PHP

Tutorial to Create Simple Tabs-AJAX with AJAX and PHP

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,
    [sourcecode language=”php”]
    <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>
    [/sourcecode]
  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,
    [sourcecode language=”php”]<a href="fallback1.php" id="tab1" class="tab" onclick="return handleOnClick(1);"> News 1</a>[/sourcecode]

    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,
    [sourcecode language=”javascript”]
    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;
    }
    [/sourcecode]
  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,
    [sourcecode language=”php”]
    <?php
    sleep(2);
    echo "News 1";
    echo "Ini adalah isi berita 1";
    ?>
    [/sourcecode]
  2. Save with the name getNews1.php
  3. Then type the following script,
    [sourcecode language=”php”]
    <?php
    sleep(2);
    echo "News 2";
    echo "Ini adalah isi berita 2";
    ?>
    [/sourcecode]
  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,
    [sourcecode language=”php”]
    <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>
    [/sourcecode]
  2. Save with the name fallback1.php
  3. Then type the following script,
    [sourcecode language=”php”]
    <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>
    [/sourcecode]
  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 🙂