Difference between revisions of "Pengenalan AJAX untuk komunikasi asynchronous"
		
		
		
		
		
		Jump to navigation
		Jump to search
		
				
		
		
	
Onnowpurbo (talk | contribs)  (Created page with "Berikut adalah **Modul Pengenalan AJAX** untuk kuliah **Web Programming**, lengkap dengan contoh dan cara menjalankan di **Ubuntu 24.04** tanpa menggunakan Visual Studio Code....")  | 
				Onnowpurbo (talk | contribs)   | 
				||
| Line 1: | Line 1: | ||
| − | + | ==Modul: Pengenalan AJAX (Asynchronous JavaScript and XML)==  | |
| − | -  | + | ==Tujuan Pembelajaran==  | 
| + | * Mahasiswa memahami konsep komunikasi '''asynchronous''' antara '''frontend dan backend'''.  | ||
| + | * Mahasiswa dapat mengirim permintaan (request) ke server tanpa me-refresh halaman.  | ||
| + | * Mahasiswa mampu menjalankan dan menguji AJAX di Ubuntu menggunakan '''tools bawaan'''.  | ||
| − | + | ==1. 🧠 Apa Itu AJAX?==  | |
| − | + | '''AJAX''' memungkinkan halaman web untuk:  | |
| − | + | * Mengambil/mengirim data dari/ke server secara '''asynchronous'''.  | |
| − | + | * Tidak perlu '''reload seluruh halaman'''.  | |
| − | + | * Sangat berguna untuk membuat '''web interaktif dan cepat''' (misalnya search suggestion, live form check, dsb).  | |
| − | + | ==2. 🔧 Tools di Ubuntu 24.04==  | |
| − | + | '''Text Editor'''  | |
| + | * '''Gedit''': GUI editor bawaan.  | ||
| + | * '''Nano''': Terminal-based editor.  | ||
| − | *  | + | '''Server Lokal'''  | 
| − | + | * '''Python 3 HTTP server''' (bawaan Ubuntu):  | |
| − | + | ||
| − | -   | + |  cd nama_folder  | 
| + |  python3 -m http.server 8000  | ||
| − | |||
| − | + | ==3. 📦 Struktur File Contoh==  | |
| − | + |  /ajax-demo  | |
| − | + |  │  | |
| − | + |  ├── index.html         ← halaman utama  | |
| + |  ├── data.json          ← file dummy dari “server”  | ||
| + |  └── server.py          ← contoh server Python (opsional)  | ||
| − | + | ==4. 📄 Contoh AJAX Sederhana (GET data dari file JSON)==  | |
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | + | '''`data.json`'''  | |
| − | + |  {  | |
| + |    "nama": "Dzaq Rayhan",  | ||
| + |    "status": "Mahasiswa Web Programming"  | ||
| + |  }  | ||
| − | `  | + | '''`index.html`'''  | 
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | -  | + |  <!DOCTYPE html>  | 
| + |  <html>  | ||
| + |  <head>  | ||
| + |    <title>AJAX Demo</title>  | ||
| + |  </head>  | ||
| + |  <body>  | ||
| + |    <h1>AJAX Demo - Ambil Data</h1>  | ||
| + |    <button onclick="ambilData()">Ambil Data</button>  | ||
| + |    <p id="output"></p>  | ||
| + | |||
| + |    <script>  | ||
| + |      function ambilData() {  | ||
| + |        const xhr = new XMLHttpRequest();  | ||
| + |        xhr.open("GET", "data.json", true);  | ||
| + | |||
| + |        xhr.onload = function() {  | ||
| + |          if (xhr.status === 200) {  | ||
| + |            const data = JSON.parse(xhr.responseText);  | ||
| + |            document.getElementById("output").innerText = `Nama: ${data.nama}, Status: ${data.status}`;  | ||
| + |          } else {  | ||
| + |            document.getElementById("output").innerText = "Gagal mengambil data!";  | ||
| + |          }  | ||
| + |        };   | ||
| + | |||
| + |        xhr.send();  | ||
| + |      }  | ||
| + |    </script>  | ||
| + |  </body>  | ||
| + |  </html>  | ||
| − | + | '''🚀 Cara Menjalankan'''  | |
| + | * Simpan semua file ke dalam satu folder, misalnya `ajax-demo/`  | ||
| + | * Buka terminal:  | ||
| + | |||
| + |  cd ~/ajax-demo  | ||
| + |  python3 -m http.server 8000  | ||
| − | + | * Buka browser dan kunjungi:    | |
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | + |   http://localhost:8000  | |
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
Klik tombol “Ambil Data” dan lihat data muncul tanpa reload!  | Klik tombol “Ambil Data” dan lihat data muncul tanpa reload!  | ||
| − | + | ==5. 💬 Contoh AJAX POST ke Server Dummy (menggunakan server.py)==  | |
| − | |||
| − | |||
| − | + | '''`index.html` (POST Form)'''  | |
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | + |  <!DOCTYPE html>  | |
| − | + |  <html>  | |
| − | + |  <head>  | |
| − | + |    <title>Form AJAX</title>  | |
| − | + |  </head>  | |
| − | + |  <body>  | |
| + |    <h2>AJAX POST Demo</h2>  | ||
| + |    <input type="text" id="nama" placeholder="Nama">  | ||
| + |    <button onclick="kirimData()">Kirim</button>  | ||
| + |    <p id="hasil"></p>  | ||
| + | |||
| + |    <script>  | ||
| + |      function kirimData() {  | ||
| + |        const nama = document.getElementById("nama").value;  | ||
| + |        const xhr = new XMLHttpRequest();  | ||
| + |        xhr.open("POST", "/kirim", true);  | ||
| + |        xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");    | ||
| + | |||
| + |        xhr.onload = function () {  | ||
| + |          document.getElementById("hasil").innerText = xhr.responseText;  | ||
| + |        };  | ||
| + | |||
| + |        xhr.send(JSON.stringify({ nama: nama }));  | ||
| + |      }  | ||
| + |    </script>  | ||
| + |  </body>  | ||
| + |  </html>  | ||
| − | + | '''`server.py` (Server Python Sederhana)'''  | |
| − | |||
| − | |||
| − | + |  from http.server import BaseHTTPRequestHandler, HTTPServer  | |
| − | + |  import json  | |
| − | + | ||
| − | + |  class Handler(BaseHTTPRequestHandler):  | |
| − | + |      def do_POST(self):  | |
| − | + |          if self.path == '/kirim':  | |
| + |              content_length = int(self.headers['Content-Length'])  | ||
| + |              post_data = self.rfile.read(content_length)  | ||
| + |              data = json.loads(post_data)  | ||
| + |              nama = data.get('nama', 'Tidak ada nama')  | ||
| + |              response = f"Halo, {nama}!"  | ||
| + |              self.send_response(200)  | ||
| + |              self.send_header('Content-type','text/plain')  | ||
| + |              self.end_headers()  | ||
| + |              self.wfile.write(response.encode())  | ||
| + | |||
| + |  httpd = HTTPServer(('localhost', 8000), Handler)  | ||
| + |  print("Server running at http://localhost:8000")  | ||
| + |  httpd.serve_forever()  | ||
| − | + | '''Cara jalankan server POST:'''  | |
| − | |||
| − | |||
| − | |||
| − | + |  python3 server.py  | |
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | + | ==📚 Tugas Mahasiswa==  | |
| − | |||
| − | |||
| − | |||
| − | + | * Buat form AJAX untuk:  | |
| + | ** Mengambil list produk dari file JSON  | ||
| + | ** Menampilkan ke halaman tanpa reload  | ||
| + | * Tambahkan tombol "Refresh Data"  | ||
| + | * (Bonus) Buat form POST sederhana ke Python backend  | ||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | + | ==Pranala Menarik==  | |
| − | + | * [[Web Programming]]  | |
Revision as of 19:11, 6 April 2025
Modul: Pengenalan AJAX (Asynchronous JavaScript and XML)
Tujuan Pembelajaran
- Mahasiswa memahami konsep komunikasi asynchronous antara frontend dan backend.
 - Mahasiswa dapat mengirim permintaan (request) ke server tanpa me-refresh halaman.
 - Mahasiswa mampu menjalankan dan menguji AJAX di Ubuntu menggunakan tools bawaan.
 
1. 🧠 Apa Itu AJAX?
AJAX memungkinkan halaman web untuk:
- Mengambil/mengirim data dari/ke server secara asynchronous.
 - Tidak perlu reload seluruh halaman.
 - Sangat berguna untuk membuat web interaktif dan cepat (misalnya search suggestion, live form check, dsb).
 
2. 🔧 Tools di Ubuntu 24.04
Text Editor
- Gedit: GUI editor bawaan.
 - Nano: Terminal-based editor.
 
Server Lokal
- Python 3 HTTP server (bawaan Ubuntu):
 
cd nama_folder python3 -m http.server 8000
3. 📦 Struktur File Contoh
/ajax-demo │ ├── index.html ← halaman utama ├── data.json ← file dummy dari “server” └── server.py ← contoh server Python (opsional)
4. 📄 Contoh AJAX Sederhana (GET data dari file JSON)
`data.json`
{
  "nama": "Dzaq Rayhan",
  "status": "Mahasiswa Web Programming"
}
`index.html`
<!DOCTYPE html> <html> <head> <title>AJAX Demo</title> </head> <body>
AJAX Demo - Ambil Data
<button onclick="ambilData()">Ambil Data</button>
  <script>
    function ambilData() {
      const xhr = new XMLHttpRequest();
      xhr.open("GET", "data.json", true);
      xhr.onload = function() {
        if (xhr.status === 200) {
          const data = JSON.parse(xhr.responseText);
          document.getElementById("output").innerText = `Nama: ${data.nama}, Status: ${data.status}`;
        } else {
          document.getElementById("output").innerText = "Gagal mengambil data!";
        }
      }; 
      xhr.send();
    }
  </script>
</body>
</html>
🚀 Cara Menjalankan
- Simpan semua file ke dalam satu folder, misalnya `ajax-demo/`
 - Buka terminal:
 
cd ~/ajax-demo python3 -m http.server 8000
- Buka browser dan kunjungi:
 
http://localhost:8000
Klik tombol “Ambil Data” dan lihat data muncul tanpa reload!
5. 💬 Contoh AJAX POST ke Server Dummy (menggunakan server.py)
`index.html` (POST Form)
<!DOCTYPE html> <html> <head> <title>Form AJAX</title> </head> <body>
AJAX POST Demo
<input type="text" id="nama" placeholder="Nama"> <button onclick="kirimData()">Kirim</button>
  <script>
    function kirimData() {
      const nama = document.getElementById("nama").value;
      const xhr = new XMLHttpRequest();
      xhr.open("POST", "/kirim", true);
      xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8"); 
      xhr.onload = function () {
        document.getElementById("hasil").innerText = xhr.responseText;
      };
      xhr.send(JSON.stringify({ nama: nama }));
    }
  </script>
</body>
</html>
`server.py` (Server Python Sederhana)
from http.server import BaseHTTPRequestHandler, HTTPServer
import json
class Handler(BaseHTTPRequestHandler):
    def do_POST(self):
        if self.path == '/kirim':
            content_length = int(self.headers['Content-Length'])
            post_data = self.rfile.read(content_length)
            data = json.loads(post_data)
            nama = data.get('nama', 'Tidak ada nama')
            response = f"Halo, {nama}!"
            self.send_response(200)
            self.send_header('Content-type','text/plain')
            self.end_headers()
            self.wfile.write(response.encode())
httpd = HTTPServer(('localhost', 8000), Handler)
print("Server running at http://localhost:8000")
httpd.serve_forever()
Cara jalankan server POST:
python3 server.py
📚 Tugas Mahasiswa
- Buat form AJAX untuk:
- Mengambil list produk dari file JSON
 - Menampilkan ke halaman tanpa reload
 
 - Tambahkan tombol "Refresh Data"
 - (Bonus) Buat form POST sederhana ke Python backend