XMLHttpRequest atau XHR merupakan objek yang tersedia pada browser yang digunakan untuk membuat HTTP Requests menggunakan JavaScript. Karena namanya kita mungkin beranggapan bahwa XHR hanya mendukung format data XML, tetapi nyatanya saat ini XHR dapat digunakan oleh banyak format, bukan hanya XML.

Walaupun sekarang terdapat cara yang lebih modern yaitu menggunakan fetch, namun masih ada kok beberapa developer yang menggunakan XHR dalam melakukan HTTP Request. Alasannya karena alasan dukungan browser tua atau suatu fitur yang tidak bisa fetch lakukan seperti tracking upload progress.

Basic Usage

XMLHttpRequest dapat berjalan secara synchronous maupun asynchronous. Namun kebanyakan kasus HTTP Request sebaiknya asynchronous.
Contoh penggunaan dasar dari XMLHttpRequest adalah seperti ini:
202003132318522fefb326486e99f9449b3ea0b5d8cb31.png
Langkah awal untuk menggunakan XMLHttpRequest adalah dengan membuat instance baru dari objek XMLHttpRequest seperti ini:

  1. const xhr = new XMLHttpRequest();


Lalu pada instance dari objek tersebut (xhr) kita tentukan callback function ketika request berhasil (onload) dan ketika request gagal (onerror).

  1. xhr.onload = function () {

  2. console.log(this.responseText);

  3. }

  4. xhr.onerror = function () {

  5. console.log("Ups something error")

  6. }


Di dalam callback function tersebut, nilai dari this merupakan XHR objek. Sehingga this.responseText akan memiliki nilai response (dalam bentuk text) dari server. Ingat karena pada callback function tersebut nilai this merupakan XHR objek, kita tidak dapat menggunakan gaya arrow function dalam menuliskan callback function-nya.

  1. xhr.onload = () => {

  2.     // akan menyebabkan error, karena arrow function tidak memiliki this.

  3.     console.log(this.responseText);

  4. }


Selanjutnya kita tentukan HTTP Method dan URL yang dituju dengan menggunakan method .open()

  1. xhr.open("GET", "https://api-to-call.com/endpoint");


Nah, langkah akhir adalah mengirimkan request yang sudah kita konfigurasi di atas menggunakan method .send().

  1. xhr.send();


Sehingga seluruh kode dalam penggunaan dasar dari XMLHttpRequest dengan contoh target url berikut https://web-server-book-dicoding.appspot.com/list adalah seperti ini:

  1. const xhr = new XMLHttpRequest();

  2.  

  3. xhr.onload = function () {

  4.  console.log(this.responseText)

  5. }

  6. xhr.onerror = function () {

  7.  console.log("Ups something error")

  8. }

  9.  

  10. xhr.open("GET", "https://web-server-book-dicoding.appspot.com/list");

  11. xhr.send();


Coba Anda copy dan paste kode di atas dan jalankan pada console devTools. Jika request berhasil, Anda akan mendapatkan data dalam bentuk JSON String. Data tersebut bisa Anda olah menjadi JavaScript objek dengan mengubahnya menggunakan method JSON.parse().

  1. JSON.parse(this.responseText)


Anda juga bisa mencoba menjalankan potongan kode di atas pada repl.it melalui tautan berikut: https://repl.it/@dicodingacademy/163-06-AJAX-XHR-basic?lite=true

Header and Body Request using XHR

Sebelumnya kita sudah belajar bagaimana cara menggunakan dasar XMLHttpRequest dalam membuat sebuah GET Request. Lalu bagaimana jika kita ingin menggunakan method POST dan menetapkan properti pada Header ? Lalu bagaimana cara mengirimkan data pada body HTTP Request? Yuk kita bahas permasalahan tersebut satu per satu.

Set Header Property

Dalam menggunakan Web API tidak selamanya kita hanya menggunakan GET request saja, terutama ketika request yang kita inginkan bertujuan mengubah atau menambahkan data. Web API biasanya meminta kita untuk melakukannya dengan method POST atau PUT. Tak jarang juga Web API meminta kita untuk menetapkan properti tertentu pada request header untuk menunjukkan credential yang kita miliki. Request tersebut sudah pernah kita coba ya menggunakan Postman. Tapi bagaimana ya caranya jika menggunakan XHR?
Untuk menetapkan properti pada request header, Anda dapat gunakan method setRequestHeader() pada instance XMLHttpRequest setelah menetapkan method .open(). Method tersebut menerima dua parameter. Parameter pertama merupakan nama properti dan parameter yang kedua adalah nilai yang akan ditetapkan pada properti tersebut. Sehingga untuk menetapkan properti Content-Type dengan nilai application/json pada request kita dapat melakukannya dengan cara:

  1. const xhr = new XMLHttpRequest();

  2.  

  3. xhr.onload = function() {

  4.  console.log(this.responseText);

  5. }

  6.  

  7. xhr.onerror = function() {

  8.  console.log("Ups something error");

  9. }

  10.  

  11. xhr.open("POST", "https://web-server-book-dicoding.appspot.com/add");

  12.  

  13. // menambahkan properti pada header request

  14. xhr.setRequestHeader("Content-Type", "application/json");


Kita dapat menetapkan properti pada request header sebanyak yang kita perlukan

  1. const xhr = new XMLHttpRequest();

  2.  

  3. xhr.onload = function() {

  4.  console.log(this.responseText);

  5. }

  6.  

  7. xhr.onerror = function() {

  8.  console.log("Ups something error");

  9. }

  10.  

  11. xhr.open("POST", "https://web-server-book-dicoding.appspot.com/add");

  12.  

  13. // menambahkan properti pada header request

  14. xhr.setRequestHeader("Content-Type", "application/json");

  15. xhr.setRequestHeader("X-Auth-Token", "12345")


Cukup mudah bukan?

Set Data to Body Request

Lalu untuk menetapkan data pada body request, lakukanlah pada method .send() dari instance XMLHttpRequest. Contohnya untuk mengirimkan data JSON String pada body request, begini caranya: 

  1. const xhr = new XMLHttpRequest();

  2.  

  3. xhr.onload = function() {

  4.  console.log(this.responseText);

  5. }

  6.  

  7. xhr.onerror = function() {

  8.  console.log("Ups something error");

  9. }

  10.  

  11. xhr.open("POST", "https://web-server-book-dicoding.appspot.com/add");

  12.  

  13. // menambahkan properti pada header request

  14. xhr.setRequestHeader("Content-Type", "application/json");

  15. xhr.setRequestHeader("X-Auth-Token", "12345")

  16.  

  17. const book = {

  18.  id: 10,

  19.  title: "Edensor",

  20.  author: "Andrea Hirata"

  21. }

  22.  

  23. xhr.send(JSON.stringify(book));


Sebenarnya tidak hanya JSON format yang dapat dikirimkan melalui body, pada situs MDN menyebutkan bahwa kita dapat mengirimkan dokumen yang sudah ter-serialized sebelum dikirim, atau data lain yang terdaftar pada Fetch spec seperti Blob, BufferSource, FormData, URLSeachParam, ReadableStream atau USVString object.
Contoh kode di atas dapat Anda temukan pada tautan berikut https://repl.it/@dicodingacademy/163-06-AJAX-XHR-Header-and-Body?lite=true. Anda bisa coba lakukan POST Request dengan menjalankan potongan kode tersebut
Hasil Akhir Cek :
https://github.com/dicodingacademy/a163-bfwd-labs/tree/302-dicoding-books-xhr
Contoh Dasar Ajax Menggunakan XMLHttpRequest
Bookmark

Contoh Dasar Ajax Menggunakan XMLHttpRequest

Type:
Genre:
Status:
Country:
Keywords: Watch online Contoh Dasar Ajax Menggunakan XMLHttpRequest bahasa Indonesia, Streaming anime Contoh Dasar Ajax Menggunakan XMLHttpRequest sub indo, Mau nonton anime terbaik dengan subtitle Indonesia? Streaming anime Jepang dari anime Contoh Dasar Ajax Menggunakan XMLHttpRequest, website streaming anime subtitle indonesia dan nonton anime indo update setiap hari, TV Contoh Dasar Ajax Menggunakan XMLHttpRequest, Terbaru Terupdate dan Terlengkap dengan Kualitas 1080p, 720p. 480p, 360p Anime Sub Indo.

Comments

Comment Report Rule
Show Comments
9Anime Comment Policies & Guidelines
  1. Spoiling Content

    Definition

    “Anime Comment” is a spoiler-free section and is usually used for a general discussion about anime without spoiling any content.

    “Episode Comment” may contain spoilers for current or previous episodes. Contents from manga or future episodes are considered as spoilers.

    Hiding spoilers with spoiler tags is not allowed either.

    Consequences

    Minor Spoiler:-

    1st Offense: Warning + Temporary Ban (Ranging 1 day to 3 days)

    2nd Offense Within 30 Days of 1st Offense: Permanent Ban

    Major Spoiler:-

    1st Offense: Permanent Ban

  2. Diversion From Topic

    Definition

    The comment section should be about the anime on hand. Although references from other anime may be used, the core topic of the comments should be about the anime at hand.

    This rule also applies on advertising other streaming websites which results in an instant ban.

    This rule also applies to spam, posting comments like “first”, “second”, etc. are considered spam.

    Consequences

    1st Offense: Warning + Temporary Ban (Ranging 1 day to 3 days)

    2nd Offense Within 30 Days of 1st Offense: Permanent Ban

  3. Flame War

    Definition

    Exchange of angry or abusive messages between the comments. Any form of insulting is also considered as flame war.

    Consequences

    1st Offense: Warning + Temporary Ban (Ranging 1 day to 3 days)

    2nd Offense Within 30 Days of 1st Offense: Permanent Ban

  4. Posting Harmful Link

    Definition

    Post of hyperlinks for websites that may contain viruses or may harm your PC or device.

    Consequences

    1st Offense: Permanent Ban + Deletion of All Comments

  5. Posting NSFW Content

    Definition

    Posting contents that are not safe for work, such as pornographic images or video, ecchi anime, hentai, etc.

    Consequences

    1st Offense: Warning + Temporary Ban (Ranging 1 day to 3 days)

    2nd Offense Within 30 Days of 1st Offense: Permanent Ban

  6. Inappropriate Profile Picture

    Definition

    Using a profile picture that is not safe for work. Although minor ecchi or fanservice is acceptable.

    Consequences

    1st Offense: Warning + Temporary Ban (Ranging 1 day to 3 days)

    2nd Offense Within 30 Days of 1st Offense: Permanent Ban

  7. Use of Common Sense

    Definition

    If you think that you’ll get in trouble for what you’re about to do, don’t do it.

    Consequences

    1st Offense: Warning + Temporary Ban (Ranging 1 day to 3 days)

    2nd Offense Within 30 Days of 1st Offense: Permanent Ban

  8. Upvote Abusing

    Definition

    Creating multiple alternative accounts to upvote your own comments.

    Consequences

    1st Offense: Permanent Ban on All Accounts + Deletion of All Comments

  9. Downvote Abusing

    Definition

    Targeting a user and downvoting all his comments, or creating multiple accounts to downvote one or more comments.

    Consequences

    1st Offense: Permanent Ban on All Accounts

  10. Swearing

    Definition

    Swearing is fine, as long as it’s not directed towards anyone, even as a joke. It may be misinterpreted by a moderator.

    Consequences

    1st Offense: Warning + Temporary Ban (Ranging 1 day to 3 days)

    2nd Offense Within 30 Days of 1st Offense: Permanent Ban

  11. Moderator Verdict

    Definition

    A moderator’s verdict is final and arguing with them will only cause further punishment. If you have a complaint against a staff member, or wish to file a ban appeal, go to the 9Anime Discord Server and post your issue in the #disqus-appeals channel.

    Consequences

    1st Offense: Warning + Temporary Ban (Ranging 1 day to 3 days)

    2nd Offense Within 30 Days of 1st Offense: Permanent Ban

Think you have been unfairly warned or banned?

If you believe that you’ve been unfairly banned or if you have a complaint against one or more Disqus Staff Members, you may post an appeal or complaint on 9Anime Discord Server.

STEPS

  1. Join 9Anime Discord Server: https://discord.gg/xxxxxxx
  2. Read the #rules channel and follow instructions. (Optional, but highly recommended)
  3. Head towards #disqus-appeals channel.
  4. Use the appropriate template to appeal a ban or file a complaint.