setTimeout("ambilPesan()",1000);
Kode di atas berarti, eksekusi fungsi ambilPesan() setiap 1000 milisecond. Mari kita lihat konsep untuk membuat aplikasi chatting:
- Kita buat objek ajax yang nantiya bertugas melakukan komunikasi ke server
- User memasukkan nama, yang nantinya kita simpan dalam suatu variabel
- Ketika user selesai mengetik pesan, masukkan ke dalam database melalui ajax
- User, baik kita sendiri atau orang lain, setiap 1 detik akan mengecek ke server, apakah ada pesan baru, jika ada tampilkan.
Berikut adah struktur tabel drzchat di database :
1 | -- |
2 | -- Table structure for table `drzchat` |
3 | -- |
4 | |
5 | CREATE TABLE `drzchat` ( |
6 | `nomor` int(3) NOT NULL auto_increment, |
7 | `nama` varchar(20) NOT NULL, |
8 | `pesan` varchar(200) NOT NULL, |
9 | `waktu` varchar(10) NOT NULL, |
10 | PRIMARY KEY (`nomor`) |
11 | ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; |
view plain | print | ? |
1 | <html> |
2 | <head> |
3 | <title> |
4 | DRZ Chat 1.0 |
5 | </title> |
6 | <script> |
7 | var ajaxku = buatAjax(); |
8 | var tnama = 0; |
9 | var pesanakhir = 0; |
10 | var timer; |
11 | function taruhNama(){ |
12 | if(tnama==0){ |
13 | document.getElementById("nama").disabled = "true"; |
14 | tnama = 1; |
15 | }else{ |
16 | document.getElementById("nama").disabled = ""; |
17 | tnama = 0; |
18 | } |
19 | ambilPesan(); |
20 | } |
21 | function buatAjax(){ |
22 | if(window.XMLHttpRequest){ |
23 | return new XMLHttpRequest(); |
24 | }else if(window.ActiveXObject){ |
25 | return new ActiveXObject("Microsoft.XMLHTTP"); |
26 | } |
27 | } |
28 | |
29 | function ambilPesan(){ |
30 | namaku = document.getElementById("nama").value |
31 | if(ajaxku.readyState == 4 || ajaxku.readyState == 0){ |
32 | ajaxku.open("GET","ambilchat.php?akhir="+pesanakhir+"&nama="+namaku+"&sid="+Math.random(),true); |
33 | ajaxku.onreadystatechange = aturAmbilPesan; |
34 | ajaxku.send(null); |
35 | } |
36 | } |
37 | |
38 | function aturAmbilPesan(){ |
39 | if(ajaxku.readyState == 4){ |
40 | var chat_div = document.getElementById("div_chat"); |
41 | var data = eval("("+ajaxku.responseText+")"); |
42 | for(i=0;i<data.messages.pesan.length;i++){ |
43 | chat_div.innerHTML += "<font color=red>"+data.messages.pesan[i].nama+"</font> "; |
44 | chat_div.innerHTML += "<font size=1>("+data.messages.pesan[i].waktu+")</font> "; |
45 | chat_div.innerHTML += " : "+data.messages.pesan[i].teks+"<br>"; |
46 | chat_div.scrollTop = chat_div.scrollHeight; |
47 | pesanakhir = data.messages.pesan[i].id; |
48 | } |
49 | } |
50 | timer = setTimeout("ambilPesan()",1000); |
51 | } |
52 | |
53 | function kirimPesan(){ |
54 | pesannya = document.getElementById("pesan").value |
55 | namaku = document.getElementById("nama").value |
56 | if(pesannya != "" && document.getElementById("nama").value !=""){ |
57 | ajaxku.open("GET","ambilchat.php?akhir="+pesanakhir+"&nama="+namaku+"&pesan="+pesannya+"&sid="+Math.random(),true); |
58 | ajaxku.onreadystatechange = aturAmbilPesan; |
59 | ajaxku.send(null); |
60 | document.getElementById("pesan").value = ""; |
61 | }else{ |
62 | alert("Nama atau pesan masih kosong"); |
63 | } |
64 | } |
65 | |
66 | function aturKirimPesan(){ |
67 | clearInterval(timer); |
68 | ambilPesan(); |
69 | } |
70 | function blockSubmit() { |
71 | kirimPesan(); |
72 | return false; |
73 | } |
74 | </script> |
75 | </head> |
76 | <body> |
77 | Nama : <input type=text name=nama id=nama> |
78 | <input type=button value=login id=tmbl_login onclick=taruhNama()><p> |
79 | <div id="div_chat" style="height: 300px; width: 500px; overflow: auto; background-color: lightyellow; border: 1px solid #555555;"> |
80 | |
81 | </div> |
82 | <form onSubmit="return blockSubmit();"> |
83 | Pesan : <input type=text name=pesan id=pesan size=50> |
84 | <input type=button value="kirim" onclick="kirimPesan()"> |
85 | </form> |
86 | </body> |
87 | </html> |
view plain | print | ? |
Apabila kita sudah mengetik pesan, javascript akan menjalankan fungsi kirimPesan(). Untuk mengerti apa itu readyState, onreadystatechange silahkan download tutorial pengenalan ajax di sini.
Pada kode di atas objek ajax melakukan request atau komunikasi dengan file php server, yaitu file ambilchat.php. Berikut kodenya :
1 | <?php |
2 | mysql_connect("localhost","root",""); |
3 | mysql_select_db("test"); |
4 | |
5 | $nama = $_GET['nama']; |
6 | $pesan = $_GET['pesan']; |
7 | $waktu = date("H:i"); |
8 | $akhir = $_GET['akhir']; |
9 | |
10 | $json = '{"messages": {'; |
11 | if($akhir==0){ |
12 | $nomor = mysql_query("select nomor from drzchat order by nomor desc limit 1"); |
13 | $n = mysql_fetch_array($nomor); |
14 | $no = $n['nomor'] + 1; |
15 | $json .= '"pesan":[ {'; |
16 | $json .= '"id":"'.$no.'", |
17 | "nama":"Admin", |
18 | "teks":"Selamat datang di chatting room", |
19 | "waktu":"'.$waktu.'" |
20 | }]'; |
21 | $masuk = mysql_query("insert into drzchat values(null,'Admin','$nama bergabung dalam chat','$waktu')"); |
22 | }else{ |
23 | if($pesan){ |
24 | $masuk = mysql_query("insert into drzchat values(null,'$nama','$pesan','$waktu')"); |
25 | |
26 | } |
27 | $query = mysql_query("select * from drzchat where nomor > $akhir"); |
28 | $json .= '"pesan":[ '; |
29 | while($x = mysql_fetch_array($query)){ |
30 | $json .= '{'; |
31 | $json .= '"id":"'.$x['nomor'].'", |
32 | "nama":"'.htmlspecialchars($x['nama']).'", |
33 | "teks":"'.htmlspecialchars($x['pesan']).'", |
34 | "waktu":"'.$x['waktu'].'" |
35 | },'; |
36 | } |
37 | $json = substr($json,0,strlen($json)-1); |
38 | $json .= ']'; |
39 | } |
40 | |
41 | $json .= '}}'; |
42 | echo $json; |
43 | ?> |
view plain | print | ? |
Format data yang dikirim oleh server menggunakan format JSON, silahkan download dan baca tutorial JSON di sini.
Download Source Code
Refrensi
0 Comments:
Post a Comment