Home arrow News - Articles arrow Teaching things arrow Kuliah TKI : Ajax - Introduction
 
  XnRnXZvLpO www.danielhp.com
Kuliah TKI : Ajax - Introduction PDF Print E-mail
Written by Administrator   
Friday, 23 May 2008

Ajax dapat membuat aplikasi berbasis web menjadi seperti aplikasi desktop. Dengan ajax, interaksi menjadi lebih user friendly, tidak ada lagi loading seluruh halaman untuk perubahan kecil di halaman web.

Berikut akan diberikan contoh website yang menggunakan ajax secara sederhana, dengan langsung diberikan penjelasan pada sourcodenya agar lebih jelas.

 

My First Ajax

 

Untuk contoh pertama ini, siapkan sebuah file, dapat html dapat pula php disuaatu lokasi pada server local. Sebut saja file utama.php Dengan isi code seperti dibawah:

 

<html>

<head>

<title>Ajax at work</title>

<script language = "javascript">

 

var XMLHttpRequestObject = false;

//initialisasi object XMLHttpRequest beda antara IE dengan FireFox, dan lain-lain

//jika bukan IE

if (window.XMLHttpRequest) {

XMLHttpRequestObject = new XMLHttpRequest();

}

//jika IE

else if (window.ActiveXObject) {

XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP");

}

 

//fungsi untuk mengambil data di datasource dimasukkan ke div dengan id divID

function getData(dataSource, divID)

{

//jalankan jika object httprequest telah terbuat

if(XMLHttpRequestObject) {

//ambil object div

var obj = document.getElementById(divID);

//buka data di datasource

XMLHttpRequestObject.open("GET", dataSource);

//jika ada perubahan state

XMLHttpRequestObject.onreadystatechange = function()

{

//jika sudah complete dan sukses

if (XMLHttpRequestObject.readyState == 4 &&

XMLHttpRequestObject.status == 200) {

//ambil data masukkan dalam div

obj.innerHTML = XMLHttpRequestObject.responseText;

}

}

XMLHttpRequestObject.send(null);

}

}

</script>

 

</head>

<body>

<H1>Fetching data with Ajax</H1>

<form>

<input type = "button" value = "Klik Aku"

onclick = "getData('data.txt','targetDiv')">

Kuliah TK Internet : Ajax Introduction

</form>

<div id="targetDiv">

<p>Data dari ajax akan berada dibawah ini.</p>

</div>

</body>

</html>

 
selain file tadi, siapkan juga file txt dengan nama data.txt dengan isi sembarang tulisan.

 
Jika sudah , panggil halaman web diatas, dan coba klik pada tombol  ‘klik aku’, jika dibawah tulisan 
Data dari ajax akan berada dibawah ini’ muncul text yang ada pada file data.txt, berarti ajax sudah jalan dengan benar.

 
Ajax menggunakan object XMLHttpRequest. Disitu ada fungsi open yang digunakan untuk mengambil data secara langsung jika berupa textfile, dan hasil output php jika dari file php.  Tulisan dari file tadi diambil dan dimasukkan kedalam object div dengan innerHTML. Jadi Ajax mengubah html lewat javascript, tapi dengan data diambil dari server lewat jalan belakang (backdoor). Sehingga tidak diperlukan loading keseluruhan halaman web.

Didalam source diatas terdapat property readystate dan status. 4 berarti proses pembacaan telah complete, sedang 200 berarti OK, tidak ada error. Berikut daftar nilai ready state dan status yang mungkin muncul:

 

0 uninitialized

1 loading

2 loaded

3 interactive

4 complete

 

 200 OK

 201 Created

 204 No Content

 205 Reset Content

 206 Partial Content

 400 Bad Request

 401 Unauthorized

 403 Forbidden

 404 Not Found

 405 Method Not Allowed

 406 Not Acceptable

 407 Proxy Authentication Required

 408 Request Timeout

 411 Length Required

 413 Requested Entity Too Large

 414 Requested URL Too Long

 415 Unsupported Media Type

 500 Internal Server Error

 501Not Implemented

 502 Bad Gateway

 503 Service Unavailable

 504 Gateway Timeout

 505 HTTP Version Not Supported


Mengambil data dari proses PHP

 

Contoh diatas sangat sederhana dan jarang dapat diimplementasikan. Bentuk yang sering diimplementasikan adalah mengambil data dari hasil proses php. Caranya adalah sebagai berikut:

- Ubah code yang terdapat getData yaitu

 

onclick = "getData('data.txt','targetDiv')">

 

menjadi

 

onclick = "getData('data.php','targetDiv')">

 

- buat data.php dengan code yang mengeluarkan sembarang string. Disimpan pada lokasi yang sama dengan file utama.php tadi. contoh

 

<?

   echo “ini tulisan dari php”

?>

 

browse kembali file tadi. Seharusnya setelah diklik tombol akan muncul string hasil dari proses di data.php.

 

 

Proses dari PHP yang berparameter

 

File php seringkali membutuhkan parameter untuk menghasilkan hasil yang berbeda-beda menurut suatu input dari user. Disini akan dicontohkan sementara dengan memanggil file php yang langsung diberi parameter nama. Langkahnya :

 

onclick = "getData('data.php','targetDiv')">

 

diubah menjadi

 

onclick = "getData('data.php?nama=daniel','targetDiv')”

 

 

sedang pada data.php diubah menjadi

 

<?

echo "<br> halo apa kabar ".$_GET['nama'];

?>

 

Jika dijalankan dan klik tombol, maka yang tampil adalah “halo apa kabar daniel”.

 

 

Proses dari PHP yang berparameter dari input user

 

Jika contoh sebelumnya sudah bisa jalan, kita dapat kembangkan tampilan utama.php dengan memberikan kesempatan pada user untuk memberikan input. Input ini kemudian dikirim sebagai parameter ke file php untuk diproses.

 Yang perlu dilakukan adalah menambahkan input pada html :

 

<input type="text" id="nama" name="nama">

 

dan pada bagian getData diganti menjadi :

 

"getData('data.php?nama=' + document.getElementById('nama').value ,'targetDiv');"

 

jalankan dengan cara menginputkan nama pada textbox yang tersedia dan setelah klik tombol akan tampil ‘halo apa kabar ‘ + nama orang yang diinputkan.

 

Contoh lain, outputnya dapat berupa mengeluarkan image. Tentu saja untuk mencobanya, siapkan beberapa file gambar pada folder yang sama dengan file data.php ini. Dan saat memasukkan input, tuliskanlah nama salah satu file gambar tadi. Sebelumnya ubah dahulu

 

echo "<br> halo apa kabar ".$_GET['nama'];

 

diganti menjadi

 

echo "<br><img src='".$_GET['nama'].">";

 

 

 

mem-Filter isi tabel

 

Dengan cara yang hampir sama dengan tadi, input dari user digunakan untuk mem-filter isi tabel yang ditampilkan. Misal pada tabel mahasiswa. Dengan mengisikan contoh kata ‘di’ maka yang tampil adalah mahasiswa-mahasiswa yang nama-nya mengandung kata ‘di’ seperti adi, dian, budiman, dsb..

 

Misal tabel dibuat dalam mysql pada database test di tabel mhs. Maka data php diubah menjadi seperti berikut:

 

mysql_connect("localhost","root","root");

mysql_select_db("test");

$rs=mysql_query("select * from mhs where nama like '%".$_GET[nama]."%'");

while($r=mysql_fetch_assoc($rs))

{

  echo $r['nama'].'<br>';

}

 

dan untuk lebih bagusnya, filter ini langsung berlaku saat ada perubahan pada isi textbox. Yang perlu ditambahkan adalah onKeyUp pada textbox.

 

<input type="text" id="nama" name="nama"  onKeyUp="getData('data.php?nama=' + document.getElementById('nama').value ,'targetDiv');">

Comments
Search
ada ajax lanjutannya ga pak??
Rahadian Bisma (125.164.0.xxx) 2008-12-01 22:33:08

pak ada ajax lanjutan nggak pak??oh iya pak minta topik TA donk pak.. belum
punya ide nich... makasih pak

nb: pak kemaren kenapa web ini ga bisa dibuka
pak?
to Rahadian
Daniel (202.154.22.xxx) 2008-12-04 05:39:18

Iya nih.. belum bikin contoh2 implementasi praktisnya.

Untuk TA coba bikin
website photo warehouse yang dilengkapi dengan searching berdasar komposisi
warna. Misal user ingin gambar dengan komposisi bagian kiri hijau, bagian kanan
merah. Nah nanti tampil gambar2 yang sesuai dengan prosentasi kesesuaian
masing2.

Website ini sempat mati, soale aku diusir dari hosting-ku )
haha... bisa aja pak diusir
rahadian bisma (125.164.5.xxx) 2009-01-27 12:12:08

wah bisa aja pak kok diusir... bikin hosting aja sendiri pak...

saya kemarin
punya ide untuk bikin website pariwisata dengan bantuan google API dan mashup
pak... jadi user bisa menyimpan kenangan area libuarannya dan koordinatnya
sehingga bisa dilihat user lain.. gimana pak...

yang dari pak daniel masih
binun pak..

pak selamat kuliah lagi... hehe...

ada YM pa??
to Rahadian
Daniel (202.154.22.xxx) 2009-01-29 05:38:04

Tentang Google API kemaren dah dipake buat lokasi2 sama cendra yamin. kalo kamu
mau, ambil yg dulu punya dewi maria. google api digunakan untuk pemetaan hasil
pemilu/pilkada.

ym-id : dakunil
wah keduluan... :((
djiebrats (125.164.1.xxx) 2009-01-31 15:24:57

wah keduluan... pemetaan hasil pemilu/pilkada berbasis web ya pak...
trus gimana cara kerjanya??misal inputannya.. dan apa outputnya??
bandi (114.57.168.xxx) 2009-05-14 12:22:07

pak..klo menggunakan ajax loading page di halaman web joomla gmana yah...??ajax
nya tempatin dimana..??thnkx..??
Anonymous (122.139.62.xxx) 2009-05-27 01:42:45

cheap wow power leveling cheapest wow power leveling my wow gold buy wow gold replica replica rolex CHEAP wow power level BUY power leveling replica rolex replica CHEAPEST power leveling MY wow power level
cheap rs gold
good BUY wow gold
replica rolex
CHEAPEST wow gold
cheap lotro gold
buy wow gold
my wow gold
cheapest wow gold
CHEAP wow gold zmc
Nice
Xth (118.137.110.xxx) 2009-06-02 08:07:50

Nice tutor bro..

it's useful
Women
Buy Ugg Boots (125.78.240.xxx) 2010-02-27 07:39:30

With all the
boots [url=http://www.zhjugg.com/new-product-ugg-bailey- 

button-58
03-grey-boots-p-]UGG Bailey Button Grey[/url] included in Ugg


Australia’s Classic Collection range the Bailey
chenwei
Button
is lined ugg cardy

oatmeal with twin faced Grade A sheepskin.
Also there is the

UGG Bailey Button traditional

suede heel guard to ensure that not only

is this area
protected but offers this part of the boot support.

Ugg Cardy Boots Plus within the

boots you find each pair has sock liners

that are
made from sheepskin PU foam so increasing the level of

Ugg Cardy comfort a person feels

when wearing them.
激安 ユニフォ&
激安 ユ| (220.161.165.xxx) 2010-02-27 09:03:24

LCZ 
読売巨人軍は 、ビ
;ジターゲ&# 12540;ムで着用&
#12377;  427;夏季限定のӎ 0;|
69;マービジタ ーユニホ
;ーム&# 12301;を 採用しま
2377;。ユニフォーム...このユニ

ホӦ 0; ムの
発表会見&# 12364;12日(&#
26376;A 289;、東京・大৔ 3;ஹ
0;の球団事務 所で開か
れ、&# 12481;ームを代表  
375;て 坂本勇人選手&# ...
Paul Smith (220.161.165.xxx) 2010-02-27 09:21:09

Our store offer the cheap paul smith for you,sale new Paul Smith Shoes,and we will give my best server to you.Come on, more order will get more
discount.You can not miss them!rlh
MBT Shoes
mbt uk (220.161.165.xxx) 2010-02-27 10:16:29

When you purchase Mbt shoes you achieve shoes that appeal mbt shoes to your sense of style while insuring a shoe that does not cause pain and
discomfort after a day mbt trainers shoes of being on your feet. And after your purchase you know you have shoes
that are going to outlast shoes found in most stores. Created for
comfort and long lasting, MBT shoes utilize the highest quality
leather and materials. If you experience mbt uk discomfort from your foot perspiring during the day MBT Shoes applies a
sock lining in the lining of the shoe where you foot rests. mbt shoe This allows your feet to stay dry during the most challenging active
days.hlm
nike-shox (125.78.242.xxx) 2010-02-27 16:40:08

rr
Today, the nike shox basketball shoes

are popular around the world. wholesale nike shox shoes

started out as an American company, but have since expanded around the
globe. They're now available in 120 countries. shox r4

with an emphasis on walking shoes, the engineers at New Balance know
the importance of a proper fit and offer a wide range of widths
and sizes. Often recommended by podiatrists, nike running shoes

take an "endorsed by no one" stance, preferring to let their
technology and comfort sell their shoes instead of paying a
celebrity athlete to do it for them. Additionally, nike shox monster

are available in a variety of styles, each designed for different
needs-motion control, extra support, off road, use etc. New Balance
makes running, walking, tennis, cross-training and basketball shoes
for men and women, and also offers a line of kids' ...
timberland (220.161.165.xxx) 2010-02-27 17:04:23

mm Apparently, 21,000 boots imported by Timberland from Thailand have lead paint on the insole, violating federal lead paint
rules. I'm guessing this paint was used for printing of the
logo inside the boot. Please note Dear Readers, these are Timberland waterproof and children are particularly sensitive to the effects of lead and lead
poisoning. Avoid a lead paint accident that could injure or hurt
your child.
When I first saw this I thought, "How do you make Timberland work boots? Where's the risk of accident or injury?" Then I read further and saw,
"lead paint." The headline reads:"Timberland Recalls Timberland for kids Due to Violation of Lead Paint Standard"The U.S. Consumer Product
Safety Commission announced a voluntary recall of these boots.
Consumers should stop using recalled products immediately.
Only registered users can write comments!

3.26 Copyright (C) 2008 Compojoom.com / Copyright (C) 2007 Alain Georgette / Copyright (C) 2006 Frantisek Hliva. All rights reserved."

Last Updated ( Friday, 23 May 2008 )
 
< Prev   Next >
 
 
(C) 2010 daniel hary prasetyo
Free Joomla Template designed by funky-visions.de
 

articles (a-z order)