Load Data dengan AJAX (PHP, MySQL N Javascript)


Artikel berikut adalah artikel yang akan menjelaskan tentang cara mendapatkan data dari database MySQL dengan menggunakan PHP dan Javascript yang memanfaatkan Object XMLHttpRequest. Agar bisa memahami program, user diasumsikan sudah memliki basic PHP, Javascript dan MySQL.

Pertama-tama, kita akan membuat database news dengan menggunakan databaseMySQL. pada database news terdapat 5 field yang berisi news_id, news_date, news_title, news_content dan news_author. berikut adalah scriptnya:

CREATE TABLE news (
news_id int(11) NOT NULL auto_increment,
news_title varchar(255) NOT NULL default ”,
news_content longtext NOT NULL,
news_author varchar(50) NOT NULL,
news_date datetime NOT NULL default ‘0000-00-00 00:00:00’,
PRIMARY KEY  (news_id)
)

langkah selanjutnya adalah anda isikan data kedalam database agar nantinya data tersebut bisa digunakan untuk load AJAX. di sini saya tidak akan menjelaskan cara menginsert/upload data dengan menggunakan AJAX, akan tetapi lebih kepada bagaimana cara mendapatkan data menggunakan AJAX (load data).

sekarang kita buat script php yang akan menghandle data pada serverside. misalkan script yang saya buat saya namakan php-ajax.php

<?

include “config.php”;
include “dbfunctions.php”;
$action = $_GET[“action”];
$id = $_GET[“id”];

if($action==”loadTitle”){
loadTitle();
}else if($action == “viewArticle”){
viewArticle($id);
}

function loadTitle(){
global $t_news;
opendb();
$query=”SELECT news_id, news_title FROM news WHERE news_date LIKE ‘”.date(“Y”).”-“.date(“m”).”%’ ORDER BY news_id DESC”;
$result = querydb($query);
while($data = mysql_fetch_array($result)){?>
&rsaquo; <a class=”content” href=”#<?=$data[‘news_id’]?>” onclick = “getData(‘php-ajax.php?action=view&id=<?=$data[‘news_id’]?>’, ‘contentDiv’)”><?=strip_tags($data[‘news_title’]);?></a><br />    <?

}
closedb();
}

function viewNewsDetail($id){
global $t_news;
opendb();
$query=”SELECT * FROM $t_news WHERE news_id=’$id'”;
$result = querydb($query);
while($data = mysql_fetch_array($result)){
echo $data[‘news_date’] ?><br>
<h3><?=$data[‘news_title’]?></h3><br><a id=”<?=$data[‘news_id’]?>”>
Oleh: <?=$data[‘news_author’]?><br>
<p align=”justify”><?=$data[‘news_content’]?></p><br>
<?
}
viewLatestNews();
closedb();
}

?>

config.php

<?
//    config.php
if(ereg(“config.php”, $PHP_SELF)){
header(“Location: index.php”);
die;
}

//konfigurasi db
$host = “localhost”;
$dbname    = “news”;
$user = “xxxx”;
$pass = “xxx”;

?>

dbfunctions.php

<?php
if(ereg(“dbfunctions.php”, $PHP_SELF)){
header(“Location: index.php”);
die;
}
function opendb(){
global $host, $user, $pass, $dbname, $dbconnect;
$dbconnect = mysql_connect($host, $user, $pass) or die(“Gagal membuka Database: “.mysql_error());
$dbselect = mysql_select_db($dbname);
}
function closedb(){
global $dbconnect;
mysql_close($dbconnect);
}
function querydb($query){
$result = mysql_query($query) or die(“Gagal melakukan query = $query”.mysql_error());
return $result;
}

?>

selanjutnya adalah membuat script php yang berisi script yang akan mengambil data dengan menggunakan object XMLHttpRequest

index.php

<html>
<head>
<title>Ajax at work</title>
<link href=”style/style.css” rel=”stylesheet” type=”text/css”>
<script language = “javascript”>
var XMLHttpRequestObject = false;

if (window.XMLHttpRequest) {
XMLHttpRequestObject = new XMLHttpRequest();
} else if (window.ActiveXObject) {
XMLHttpRequestObject = new ActiveXObject(“Microsoft.XMLHTTP”);
} else{
alert(“Browser tidak mendukung XMLHttpRequestObject”);
}

function getData(dataSource, divID){
if(XMLHttpRequestObject) {
var obj = document.getElementById(divID);
try{
XMLHttpRequestObject.open(“GET”, dataSource);
}catch(err){
alert(err.description);
}
XMLHttpRequestObject.onreadystatechange = function(){
if (XMLHttpRequestObject.readyState == 4 &&    XMLHttpRequestObject.status == 200) {
obj.innerHTML = XMLHttpRequestObject.responseText;
}
}
XMLHttpRequestObject.send(null);
}
}

</script>
</head>
<body onLoad=”getData(‘/ajax/php-function.php?action=viewMainHeadline’, ‘headlineDiv’)”>
<table width=”80%” align=”center” class=”normal” border=”1″ cellpadding=”10″ cellspacing=”0″>
<tr>
<td colspan=”2″ height=”50px”></td>
</tr>
<tr>
<td valign=”top” width=”20%”><H1>Fetching data with Ajax</H1>
<div id=”headlineDiv”>Link</div>
</td>
<td valign=”top”  width=”80%”><div id=”contentDiv”>
<h1>The fetched data will go here.</h1>
</div></td>
</tr>
</table>
</body>
</html>

terakhir, adalah membuat script untuk di load di script index.php (inget, kan kita manggil file php-function.php saat onload).

php-function.php

<?
include “config.php”;
include “dbfunctions.php”;
$action = $_GET[“action”];
$id = $_GET[“id”];
$keyword = trim($_GET[“q”]);

if($action==”search” && !empty($keyword)){
searchResult($keyword);
}else if($action == “view”){
viewNewsDetail($id);
}else if($action == “viewMainHeadline”){
viewMarqueeHeadLine();
}else{
viewHeadLine();
}

function viewNewsDetail($id){
global $t_news;
opendb();
$query=”SELECT * FROM $t_news WHERE news_id=’$id'”;
$result = querydb($query);
while($data = mysql_fetch_array($result)){

echo getDateFormat($data[‘news_date’])?><br>
<h3><?=$data[‘news_title’]?></h3><br><a id=”<?=$data[‘news_id’]?>”>
Oleh: <?=$data[‘news_author’]?><br>
<img src=”<?=$data[‘news_image’]?>”><br><p align=”justify”><?=$data[‘news_content’]?></p><br><script language=”javascript”>document.title = “‘<?=$data[‘news_title’]?>'”;</script>
<?
}

closedb();
}

function viewHeadLine(){
global $t_news;
opendb();
$query=”SELECT * FROM $t_news ORDER BY news_id DESC LIMIT 0, 10″;
$result = querydb($query);
while($data = mysql_fetch_array($result)){?>
<span class=”h3-title”>&raquo; <?=$data[‘news_title’]?></span><br><?=getDateFormat($data[‘news_date’])?> | <?=$data[‘news_author’]?><br /><br />
<a class=”content” href=”javascript:void(0)” onclick=”getData(‘/ajax/php-function.php?action=view&id=<?=$data[‘news_id’]?>’, ‘contentDiv’);document.title='<?=$data[‘news_title’]?>'”><?=strip_tags(substrWord($data[‘news_content’], 0, 50)).” …”;?></a><br><br />
<?     }
closedb();   ?>
<div align=”right”><a class=”content” href=”<?=$PHP_SELF?>?action=view_all”>… More &raquo;</a><div>
<br>
<?
}

function viewMarqueeHeadLine($sep, $viewBy){
global $t_news;
opendb();
$query=”SELECT news_id, news_title FROM news WHERE news_date LIKE ‘”.date(“Y”).”-“.date(“m”).”%’ ORDER BY news_id DESC”;
$result = querydb($query);
//echo “<ul style=’cellpadding:0px;cellspacing:0px’ type=’square’>”;
while($data = mysql_fetch_array($result)){?>
&rsaquo; <a class=”content” href=”#<?=$data[‘news_id’]?>” onclick = “getData(‘/ajax/php-function.php?action=view&id=<?=$data[‘news_id’]?>’, ‘contentDiv’)”><?=strip_tags($data[‘news_title’]);?></a><br /><? //$sep?>
<?     }
//echo “</ul>”;
closedb();

}
function searchResult($key){
global $t_news;
opendb();
$query=”SELECT * FROM news WHERE news_title LIKE ‘%”.$key.”%'”;
$result = querydb($query);

if(mysql_num_rows($result)== 0){
?><h3>No Data Found For “<?=$key?>” </h3><?
}else{
echo “<h3>Search Result For ‘”.$key.”‘: </h3><br />”;
while($data = mysql_fetch_array($result)){?>
&rsaquo; <a class=”content” href=”javascript:void(0)” onclick = “getData(‘/ajax/php-function.php?action=view&id=<?=$data[‘news_id’]?>’, ‘contentDiv’);document.title='<?=$data[‘news_title’]?>'”><?=strip_tags($data[‘news_title’]);?></a><br /><? //$sep?>
<?     }
}
closedb();
}

function getDateFormat($date){
$bln = array(“Januari”, “Februari”, “Maret”, “April”, “Mei”, “Juni”, “Juli”, “Agustus”, “September”, “Oktober”, “Nopember”, “Desember”);
$yy = substr($date, 0, 4);
$mm = substr($date, 5, -3);
$dd = substr($date, 8, -9);
$time = substr($date, 10);

$df = $dd.” “.$bln[$mm-1].” “.$yy.” – “.$time;
return $df;
}

function substrWord($string, $start=false, $end=false, $delimiter=false){
$result = ”;
$delimiter = ((!$delimiter)?chr(32):$delimiter);
$tmp = explode($delimiter, $string); //convert string to array
$end = (($end<0)?(count($tmp)+($end-1)):$end); //if minus, re-calc them
foreach ($tmp as $current => $value){
if (($current >= $start) &&    ($current <= $end)) $result.=$value.$delimiter;
}
return substr($result, 0, strlen($delimiter)*-1);
}

?>

selesai. anda dapat mencoba script diatas..

peace😀

7 comments

Tinggalkan Balasan

Isikan data di bawah atau klik salah satu ikon untuk log in:

Logo WordPress.com

You are commenting using your WordPress.com account. Logout / Ubah )

Gambar Twitter

You are commenting using your Twitter account. Logout / Ubah )

Foto Facebook

You are commenting using your Facebook account. Logout / Ubah )

Foto Google+

You are commenting using your Google+ account. Logout / Ubah )

Connecting to %s