Bagaimana cara membuat permintaan HTTP dalam Javascript dan PHP?

Dec 15 2022
Untuk membuat permintaan HTTP dalam JavaScript, Anda dapat menggunakan objek XMLHttpRequest atau API pengambilan yang lebih baru. Berikut adalah contoh penggunaan XMLHttpRequest: Perhatikan bahwa API pengambilan hanya didukung di browser modern, jadi Anda mungkin perlu menggunakan polyfill atau kembali menggunakan XMLHttpRequest untuk browser lama.

Untuk membuat permintaan HTTP di JavaScript, Anda bisa menggunakan XMLHttpRequestobjek atau fetchAPI yang lebih baru.

Berikut ini contoh menggunakan XMLHttpRequest:

var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://www.example.com/', true);

xhr.onload = function() {
  if (this.status == 200) {
    var data = JSON.parse(this.response);
    console.log(data);
  }
};

xhr.send();

fetch('https://www.example.com/')
  .then(response => response.json())
  .then(data => console.log(data));

Perhatikan bahwa fetchAPI hanya didukung di browser modern, jadi Anda mungkin perlu menggunakan polyfill atau kembali menggunakan XMLHttpRequestbrowser lama.

Dan untuk membuat permintaan HTTP di PHP, Anda dapat menggunakan fungsi bawaan file_get_contents() atau pustaka cURL yang lebih kuat.

Menggunakan file_get_contents():

<?php
  // Set the URL of the request
  $url = 'http://www.example.com';
  
  // Send the request and store the response
  $response = file_get_contents($url);
  
  // Check for errors
  if($response === false) {
    // Handle error
  } else {
    // Use the response
  }
?>

<?php 
    // Initialize cURL
    $ch = curl_init();
    
    // Set the URL of the request
    curl_setopt($ch, CURLOPT_URL, 'http://www.example.com');
    
    // Set cURL options
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Return the response as a string
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // Follow redirects
    
    // Send the request and store the response
    $response = curl_exec($ch);
    
    // Check for errors
    if(curl_errno($ch)) {
      // Handle error
    } else {
      // Use the response
    }
    
    // Close the cURL handle
    curl_close($ch);
?>