in

How do I make an HTTP request in Javascript?

To make an HTTP request in JavaScript, you can use the XMLHttpRequest object or the fetch() function. Here's an example using XMLHttpRequest:

HTTP request using XMLHttpRequest Example

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

xhr.onload = function () {
  // do something with response data
  console.log(this.responseText);
};

xhr.send();

Here's an example to make an HTTP request in JavaScript using fetch():

Using fetch() Example

fetch('http://www.example.com/')
  .then(response => response.text())
  .then(data => {
    // do something with response data
    console.log(data);
  });

Both of these examples make a GET request to the specified URL. You can replace GET with POST or another HTTP method to make a different type of request.

It's worth noting that fetch() is more modern and is generally preferred over XMLHttpRequest, but it may not be supported in older browsers. If you need to support older browsers, you may want to use XMLHttpRequest.

Related:

  1. Execute JavaScript using Nashorn in the Console
  2. How to Remove Blank Lines From Textarea using JavaScript?

Written by Vinish Kapoor

An Oracle Apex Consultant, Oracle ACE, and founder of foxinfotech.org and orclqa.com a question and answer forum for developers. You can connect with me on Facebook and Twitter.

Leave a Reply

Your email address will not be published. Required fields are marked *