1055

I need to do an HTTP GET request in JavaScript. What's the best way to do that?

I need to do this in a Mac OS X dashcode widget.

Jon Schneider
  • 25,758
  • 23
  • 142
  • 170
mclaughj
  • 12,645
  • 4
  • 31
  • 37

31 Answers31

1463

Browsers (and Dashcode) provide an XMLHttpRequest object which can be used to make HTTP requests from JavaScript:

function httpGet(theUrl)
{
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.open( "GET", theUrl, false ); // false for synchronous request
    xmlHttp.send( null );
    return xmlHttp.responseText;
}

However, synchronous requests are discouraged and will generate a warning along the lines of:

Note: Starting with Gecko 30.0 (Firefox 30.0 / Thunderbird 30.0 / SeaMonkey 2.27), synchronous requests on the main thread have been deprecated due to the negative effects to the user experience.

You should make an asynchronous request and handle the response inside an event handler.

function httpGetAsync(theUrl, callback)
{
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.onreadystatechange = function() { 
        if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
            callback(xmlHttp.responseText);
    }
    xmlHttp.open("GET", theUrl, true); // true for asynchronous 
    xmlHttp.send(null);
}
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
Joan
  • 14,694
  • 2
  • 15
  • 2
  • This one is neat, however note that IE 10 pops up a security alert when using this and trying to access url in a different domain than the page's domain – BornToCode Sep 30 '13 at 09:37
  • 2
    Well, of course Javascript has it built in, or how could any Javascript library offer a convenience method for it? The difference being that the convenience methods offer, well, convenience, and a clearer, simpler syntax. – Pistos Jun 26 '14 at 19:53
  • 15
    XML prefix because it uses the X from AJAX ~ [Asynchronous JavaScript and XML](http://en.wikipedia.org/wiki/Ajax_%28programming%29). Also, good point re the "[API that has and ECMAScript binding](http://www.w3.org/TR/XMLHttpRequest)" is due to the fact that JavaScript can be in many things, other than browsers supporting HTTP (e.g. like Adobe Reader ...) Good thing to remember so hats-off to PointedEars. – will Sep 05 '14 at 04:29
  • @AlikElzin-kilaka: there's a good reason, see [this section of the W3 specification](https://www.w3.org/TR/XMLHttpRequest/#introduction) where it explains the name. Google is your friend ;) – KJdev Jan 13 '16 at 13:39
  • 9
    @AlikElzin-kilaka Actually all the answers above are off the mark (infact the linked W3 docs explains "each component of this name is potentially misleading"). Correct answer? its just badly named http://stackoverflow.com/questions/12067185/why-is-it-called-xmlhttprequest – Ashley Coolman May 28 '16 at 11:58
  • Caution: with this function your callback will never be called back if the page responds to anything but status 200 OK. – lucaswxp Oct 21 '16 at 17:55
  • How come this triggers CORS? I thought GET requests weren't supposed to trigger it? – HeroCC May 09 '17 at 22:41
  • For example are characters like >> & << encoded to %26 ?? – Cryptic Pug Jun 05 '17 at 14:07
  • @HeroCC — You thought wrong. Any cross-origin ajax request is subject to the same origin policy. – Quentin Apr 03 '19 at 15:40
  • 3
    why do we need to `xmlHttp.send(null);`. what does it mean? – Tan-007 May 14 '19 at 17:32
  • what if the code is called in $.ajax? is synchronous still deprecated? – Lei Yang Sep 18 '19 at 07:23
  • 5
    The [fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch) offers a better way to do this, and can be polyfilled when necessary (see @PeterGibson's [answer below](https://stackoverflow.com/a/38297729/9069356)). – Dominus.Vobiscum Oct 12 '19 at 17:33
270

window.fetch is a modern replacement for XMLHttpRequest that makes use of ES6 promises. There's a nice explanation here, but it boils down to (from the article):

fetch(url).then(function(response) {
  return response.json();
}).then(function(data) {
  console.log(data);
}).catch(function(err) {
  console.log('Fetch Error :-S', err);
});

Browser support has been good since 2017. IE will likely not get official support. GitHub has a polyfill available adds support to some legacy browsers (esp versions of Safari pre March 2017 and mobile browsers from the same period).

I guess whether this is more convenient than jQuery or XMLHttpRequest or not depends on the nature of the project.

Here's a link to the spec https://fetch.spec.whatwg.org/

Edit:

Using ES7 async/await, this becomes simply (based on this Gist):

async function fetchAsync (url) {
  let response = await fetch(url);
  let data = await response.json();
  return data;
}
Peter Gibson
  • 19,086
  • 7
  • 60
  • 64
  • 13
    I might save someone some time by mentioning that you can do this to include credentials in the request: `fetch(url, { credentials:"include" })` – Enselic Mar 09 '17 at 11:01
  • @bugmenot123 `window.fetch` doesn't come with an XML parser, but you can parse the response yourself if you handle it as text (not json as in the example above). See https://stackoverflow.com/a/37702056/66349 for an example – Peter Gibson Aug 16 '17 at 22:56
  • 2
    Beware that `response.json()` here only returns a `Promise`, not the parsed response payload, hence the need for `return response.json();}).then(function(data) {...` – Raketenolli Mar 30 '22 at 17:05
  • why response .then called afterwards? isn't enough for the response only? @PeterGibson – gumuruh May 30 '22 at 11:53
  • Your update is the simplest method for me. Thanks for that. – jason m Oct 06 '22 at 15:58
  • https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/ – Geoff Langenderfer Apr 19 '23 at 17:15
  • Actually you should call catch before then, so that you handle everything inside then. – Yassir Khaldi Aug 30 '23 at 20:31
212

In jQuery:

$.get(
    "somepage.php",
    {paramOne : 1, paramX : 'abc'},
    function(data) {
       alert('page content: ' + data);
    }
);
Pistos
  • 23,070
  • 14
  • 64
  • 77
  • 5
    note that this isn't working in IE 10 when trying to access url in a different domain than the page's domain – BornToCode Sep 30 '13 at 09:35
  • 6
    @BornToCode you should investigate further and possibly open up a bug on the jQuery issue tracker in that case – ashes999 Oct 08 '13 at 16:58
  • 115
    I know some people want to write pure Javascript. I get that. I have no problem with people doing that in their projects. My "In jQuery:" should be intpreted as "I know you asked how to do it in Javascript, but let me show you how you would do that with jQuery, that you might have your curiosity piqued by seeing what kind of syntax conciseness and clarity you can enjoy by using this library, which would afford you numerous other advantages and tools as well". – Pistos Jun 26 '14 at 19:47
  • 44
    Observe also that the original poster later said: "Thanks for all the answers! I went with jQuery based on some things I read on their site.". – Pistos Jun 26 '14 at 19:49
180

Lots of great advice above, but not very reusable, and too often filled with DOM nonsense and other fluff that hides the easy code.

Here's a Javascript class we created that's reusable and easy to use. Currently it only has a GET method, but that works for us. Adding a POST shouldn't tax anyone's skills.

var HttpClient = function() {
    this.get = function(aUrl, aCallback) {
        var anHttpRequest = new XMLHttpRequest();
        anHttpRequest.onreadystatechange = function() { 
            if (anHttpRequest.readyState == 4 && anHttpRequest.status == 200)
                aCallback(anHttpRequest.responseText);
        }

        anHttpRequest.open( "GET", aUrl, true );            
        anHttpRequest.send( null );
    }
}

Using it is as easy as:

var client = new HttpClient();
client.get('http://some/thing?with=arguments', function(response) {
    // do something with response
});
Liz Av
  • 2,864
  • 1
  • 25
  • 35
tggagne
  • 2,864
  • 1
  • 21
  • 15
103

A version without callback

var i = document.createElement("img");
i.src = "/your/GET/url?params=here";
aNieto2k
  • 1,031
  • 1
  • 7
  • 2
75

Here is code to do it directly with JavaScript. But, as previously mentioned, you'd be much better off with a JavaScript library. My favorite is jQuery.

In the case below, an ASPX page (that's servicing as a poor man's REST service) is being called to return a JavaScript JSON object.

var xmlHttp = null;

function GetCustomerInfo()
{
    var CustomerNumber = document.getElementById( "TextBoxCustomerNumber" ).value;
    var Url = "GetCustomerInfoAsJson.aspx?number=" + CustomerNumber;

    xmlHttp = new XMLHttpRequest(); 
    xmlHttp.onreadystatechange = ProcessRequest;
    xmlHttp.open( "GET", Url, true );
    xmlHttp.send( null );
}

function ProcessRequest() 
{
    if ( xmlHttp.readyState == 4 && xmlHttp.status == 200 ) 
    {
        if ( xmlHttp.responseText == "Not found" ) 
        {
            document.getElementById( "TextBoxCustomerName"    ).value = "Not found";
            document.getElementById( "TextBoxCustomerAddress" ).value = "";
        }
        else
        {
            var info = eval ( "(" + xmlHttp.responseText + ")" );

            // No parsing necessary with JSON!        
            document.getElementById( "TextBoxCustomerName"    ).value = info.jsonData[ 0 ].cmname;
            document.getElementById( "TextBoxCustomerAddress" ).value = info.jsonData[ 0 ].cmaddr1;
        }                    
    }
}
rp.
  • 17,483
  • 12
  • 63
  • 79
  • 39
    Since this answer is one of the top results for googling "http request javascript", it's worth mentioning that running eval on the response data like that is considered bad practice – Kloar May 19 '14 at 09:47
  • 13
    @Kloar good point, but it would be even better to give the reason why it's bad, which I guess is security. Explaining why practices are bad is the best way to make people switch their habits. – Balmipour Sep 16 '15 at 11:16
62

A copy-paste modern version ( using fetch and arrow function ) :

//Option with catch
fetch( textURL )
   .then(async r=> console.log(await r.text()))
   .catch(e=>console.error('Boo...' + e));

//No fear...
(async () =>
    console.log(
            (await (await fetch( jsonURL )).json())
            )
)();

A copy-paste classic version:

let request = new XMLHttpRequest();
request.onreadystatechange = function () {
    if (this.readyState === 4) {
        if (this.status === 200) {
            document.body.className = 'ok';
            console.log(this.responseText);
        } else if (this.response == null && this.status === 0) {
            document.body.className = 'error offline';
            console.log("The computer appears to be offline.");
        } else {
            document.body.className = 'error';
        }
    }
};
request.open("GET", url, true);
request.send(null);
Daniel De León
  • 13,196
  • 5
  • 87
  • 72
47

Short and clean:

const http = new XMLHttpRequest()

http.open("GET", "https://api.lyrics.ovh/v1/toto/africa")
http.send()

http.onload = () => console.log(http.responseText)
Damjan Pavlica
  • 31,277
  • 10
  • 71
  • 76
24

Modern, clean and shortest

fetch('https://baconipsum.com/api/?type=1')

let url = 'https://baconipsum.com/api/?type=all-meat&paras=1&start-with-lorem=2';

// to only send GET request without waiting for response just call 
fetch(url);

// to wait for results use 'then'
fetch(url).then(r=> r.json().then(j=> console.log('\nREQUEST 2',j)));

// or async/await
(async()=> 
  console.log('\nREQUEST 3', await(await fetch(url)).json()) 
)();
Open Chrome console network tab to see request
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
23

IE will cache URLs in order to make loading faster, but if you're, say, polling a server at intervals trying to get new information, IE will cache that URL and will likely return the same data set you've always had.

Regardless of how you end up doing your GET request - vanilla JavaScript, Prototype, jQuery, etc - make sure that you put a mechanism in place to combat caching. In order to combat that, append a unique token to the end of the URL you're going to be hitting. This can be done by:

var sURL = '/your/url.html?' + (new Date()).getTime();

This will append a unique timestamp to the end of the URL and will prevent any caching from happening.

Arend
  • 3,741
  • 2
  • 27
  • 37
Tom
  • 15,527
  • 5
  • 48
  • 62
14

Prototype makes it dead simple

new Ajax.Request( '/myurl', {
  method:  'get',
  parameters:  { 'param1': 'value1'},
  onSuccess:  function(response){
    alert(response.responseText);
  },
  onFailure:  function(){
    alert('ERROR');
  }
});
Mark Biek
  • 146,731
  • 54
  • 156
  • 201
13

One solution supporting older browsers:

function httpRequest() {
    var ajax = null,
        response = null,
        self = this;

    this.method = null;
    this.url = null;
    this.async = true;
    this.data = null;

    this.send = function() {
        ajax.open(this.method, this.url, this.asnyc);
        ajax.send(this.data);
    };

    if(window.XMLHttpRequest) {
        ajax = new XMLHttpRequest();
    }
    else if(window.ActiveXObject) {
        try {
            ajax = new ActiveXObject("Msxml2.XMLHTTP.6.0");
        }
        catch(e) {
            try {
                ajax = new ActiveXObject("Msxml2.XMLHTTP.3.0");
            }
            catch(error) {
                self.fail("not supported");
            }
        }
    }

    if(ajax == null) {
        return false;
    }

    ajax.onreadystatechange = function() {
        if(this.readyState == 4) {
            if(this.status == 200) {
                self.success(this.responseText);
            }
            else {
                self.fail(this.status + " - " + this.statusText);
            }
        }
    };
}

Maybe somewhat overkill but you definitely go safe with this code.

Usage:

//create request with its porperties
var request = new httpRequest();
request.method = "GET";
request.url = "https://example.com/api?parameter=value";

//create callback for success containing the response
request.success = function(response) {
    console.log(response);
};

//and a fail callback containing the error
request.fail = function(error) {
    console.log(error);
};

//and finally send it away
request.send();
  • 3
    Could people please give some comments about what I have done wrong? Not very helpful in that way! –  Oct 15 '16 at 14:04
  • The best answer in my opinion, if one is coding in ES5 using plain javascript. – CoderX Aug 09 '17 at 14:26
  • @CoderX nobody is coding in plain ES5 JavaScript any more these days. We have very good transpilers like Babel for that. – ThaJay Oct 07 '21 at 07:59
11

To do this Fetch API is the recommended approach, using JavaScript Promises. XMLHttpRequest (XHR), IFrame object or dynamic <script> tags are older (and clunkier) approaches.

<script type=“text/javascript”> 
    // Create request object 
    var request = new Request('https://example.com/api/...', 
         { method: 'POST', 
           body: {'name': 'Klaus'}, 
           headers: new Headers({ 'Content-Type': 'application/json' }) 
         });
    // Now use it! 

   fetch(request) 
   .then(resp => { 
         // handle response 
   }) 
   .catch(err => { 
         // handle errors 
    });
</script>

Here is a great fetch demo and MDN docs

lin
  • 17,956
  • 4
  • 59
  • 83
aabiro
  • 3,842
  • 2
  • 23
  • 36
9

I'm not familiar with Mac OS Dashcode Widgets, but if they let you use JavaScript libraries and support XMLHttpRequests, I'd use jQuery and do something like this:

var page_content;
$.get( "somepage.php", function(data){
    page_content = data;
});
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Daniel Beardsley
  • 19,907
  • 21
  • 66
  • 79
7

SET OF FUNCTIONS RECIPES EASY AND SIMPLE

I prepared a set of functions that are somehow similar but yet demonstrate new functionality as well as the simplicity that Javascript has reached if you know how to take advantage of it.


  1. Let some basic constants

let data;
const URLAPI = "https://gorest.co.in/public/v1/users";
function setData(dt) {
    data = dt;
}

  1. Most simple

// MOST SIMPLE ONE 
function makeRequest1() {       
    fetch(URLAPI)
        .then(response => response.json()).then( json => setData(json))
        .catch(error => console.error(error))
        .finally(() => {
            console.log("Data received 1 --> ", data);
            data = null;
    });
}

  1. Variations using Promises and Async facilities

// ASYNC FUNCTIONS 
function makeRequest2() { 
    fetch(URLAPI)
        .then(async response => await response.json()).then(async json => await setData(json))
        .catch(error => console.error(error))
        .finally(() => {
            console.log("Data received 2 --> ", data);
            data = null;            
        });
}

function makeRequest3() {    
    fetch(URLAPI)
        .then(async response => await response.json()).then(json => setData(json))
        .catch(error => console.error(error))
        .finally(() => {
            console.log("Data received 3 --> ", data);
            data = null;
        });
}

// Better Promise usages
function makeRequest4() {
    const response = Promise.resolve(fetch(URLAPI).then(response => response.json())).then(json => setData(json) ).finally(()=> {
        console.log("Data received 4 --> ", data);

    })
}

  1. Demostration of one liner function!!!

// ONE LINER STRIKE ASYNC WRAPPER FUNCTION 
async function makeRequest5() {
    console.log("Data received 5 -->", await Promise.resolve(fetch(URLAPI).then(response => response.json().then(json => json ))) );
}

WORTH MENTION ---> @Daniel De León propably the cleanest function*

(async () =>
    console.log(
            (await (await fetch( URLAPI )).json())
            )
)();

  1. The top answer -> By @tggagne shows functionality with HttpClient API.

The same can be achieve with Fetch. As per this Using Fetch by MDN shows how you can pass a INIT as second argument, basically opening the possibility to configure easily an API with classic methods (get, post...) .


// Example POST method implementation:
async function postData(url = '', data = {}) {
  // Default options are marked with *
  const response = await fetch(url, {
    method: 'POST', // *GET, POST, PUT, DELETE, etc.
    mode: 'cors', // no-cors, *cors, same-origin
    cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
    credentials: 'same-origin', // include, *same-origin, omit
    headers: {
      'Content-Type': 'application/json'
      // 'Content-Type': 'application/x-www-form-urlencoded',
    },
    redirect: 'follow', // manual, *follow, error
    referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
    body: JSON.stringify(data) // body data type must match "Content-Type" header
  });
  return response.json(); // parses JSON response into native JavaScript objects
}

postData('https://example.com/answer', { answer: 42 })
  .then(data => {
    console.log(data); // JSON data parsed by `data.json()` call
  });

Node

Fetch is not available on Node (Server Side)

The easiest solution (end of 2021) is to use Axios.

$ npm install axios

Then Run:

const axios = require('axios');
const request = async (url) => await (await axios.get( url ));
let response = request(URL).then(resp => console.log(resp.data));
Federico Baù
  • 6,013
  • 5
  • 30
  • 38
6

In your widget's Info.plist file, don't forget to set your AllowNetworkAccess key to true.

Andrew Hedges
  • 21,688
  • 16
  • 67
  • 79
6

You can get an HTTP GET request in two ways:

  1. This approach based on xml format. You have to pass the URL for the request.

    xmlhttp.open("GET","URL",true);
    xmlhttp.send();
    
  2. This one is based on jQuery. You have to specify the URL and function_name you want to call.

    $("btn").click(function() {
      $.ajax({url: "demo_test.txt", success: function_name(result) {
        $("#innerdiv").html(result);
      }});
    }); 
    
apaderno
  • 28,547
  • 16
  • 75
  • 90
parag.rane
  • 139
  • 1
  • 6
6

For those who use AngularJs, it's $http.get:

$http.get('/someUrl').
  success(function(data, status, headers, config) {
    // this callback will be called asynchronously
    // when the response is available
  }).
  error(function(data, status, headers, config) {
    // called asynchronously if an error occurs
    // or server returns response with an error status.
  });
Vitalii Fedorenko
  • 110,878
  • 29
  • 149
  • 111
6

Now with asynchronous js, we can use this method with the fetch() method to make promises more concisely. Async functions are supported in all modern browsers.

async function funcName(url) {
  const response = await fetch(url);
  var data = await response.json();
}
InSync
  • 4,851
  • 4
  • 8
  • 30
Azer8
  • 539
  • 8
  • 18
5

The best way is to use AJAX (you can find a simple tutorial on this page Tizag). The reason is that any other technique you may use requires more code, it is not guaranteed to work cross browser without rework and requires you to use more client memory by opening hidden pages inside frames passing urls parsing their data and closing them. AJAX is the way to go in this situation. That is my two years of javascript heavy development speaking.

Ahmad Adibzad
  • 501
  • 2
  • 6
  • 14
Nikola Stjelja
  • 3,659
  • 9
  • 37
  • 45
4
function get(path) {
    var form = document.createElement("form");
    form.setAttribute("method", "get");
    form.setAttribute("action", path);
    document.body.appendChild(form);
    form.submit();
}


get('/my/url/')

Same thing can be done for post request as well.
Have a look at this link JavaScript post request like a form submit

Community
  • 1
  • 1
Gaurav Gupta
  • 1,929
  • 4
  • 21
  • 40
4

To refresh best answer from joann with promise this is my code:

let httpRequestAsync = (method, url) => {
    return new Promise(function (resolve, reject) {
        var xhr = new XMLHttpRequest();
        xhr.open(method, url);
        xhr.onload = function () {
            if (xhr.status == 200) {
                resolve(xhr.responseText);
            }
            else {
                reject(new Error(xhr.responseText));
            }
        };
        xhr.send();
    });
}
negstek
  • 615
  • 8
  • 29
4

Simple async request:

function get(url, callback) {
  var getRequest = new XMLHttpRequest();

  getRequest.open("get", url, true);

  getRequest.addEventListener("readystatechange", function() {
    if (getRequest.readyState === 4 && getRequest.status === 200) {
      callback(getRequest.responseText);
    }
  });

  getRequest.send();
}
3

Ajax

You'd be best off using a library such as Prototype or jQuery.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Greg
  • 316,276
  • 54
  • 369
  • 333
2
// Create a request variable and assign a new XMLHttpRequest object to it.
var request = new XMLHttpRequest()

// Open a new connection, using the GET request on the URL endpoint
request.open('GET', 'restUrl', true)

request.onload = function () {
  // Begin accessing JSON data here
}

// Send request
request.send()
Pradeep Maurya
  • 384
  • 2
  • 8
2

In pure javascript and returning a Promise:

  httpRequest = (url, method = 'GET') => {
    return new Promise((resolve, reject) => {
      const xhr = new XMLHttpRequest();
      xhr.open(method, url);
      xhr.onload = () => {
        if (xhr.status === 200) { resolve(xhr.responseText); }
        else { reject(new Error(xhr.responseText)); }
      };
      xhr.send();
    });
  }
tbo47
  • 2,688
  • 3
  • 20
  • 11
1

If you want to use the code for a Dashboard widget, and you don't want to include a JavaScript library in every widget you created, then you can use the object XMLHttpRequest that Safari natively supports.

As reported by Andrew Hedges, a widget doesn't have access to a network, by default; you need to change that setting in the info.plist associated with the widget.

apaderno
  • 28,547
  • 16
  • 75
  • 90
0

You can do it with pure JS too:

// Create the XHR object.
function createCORSRequest(method, url) {
  var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// XHR for Chrome/Firefox/Opera/Safari.
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
// XDomainRequest for IE.
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
// CORS not supported.
xhr = null;
}
return xhr;
}

// Make the actual CORS request.
function makeCorsRequest() {
 // This is a sample server that supports CORS.
 var url = 'http://html5rocks-cors.s3-website-us-east-1.amazonaws.com/index.html';

var xhr = createCORSRequest('GET', url);
if (!xhr) {
alert('CORS not supported');
return;
}

// Response handlers.
xhr.onload = function() {
var text = xhr.responseText;
alert('Response from CORS request to ' + url + ': ' + text);
};

xhr.onerror = function() {
alert('Woops, there was an error making the request.');
};

xhr.send();
}

See: for more details: html5rocks tutorial

Kondal
  • 2,870
  • 5
  • 26
  • 40
jpereira
  • 648
  • 7
  • 12
0

Here is an alternative to xml files to load your files as an object and access properties as an object in a very fast way.

  • Attention, so that javascript can interpret the content correctly, it is necessary to save your files in the same format as your HTML page. If you use UTF 8 save your files in UTF8, etc.

XML works as a tree ok? instead of writing

     <property> value <property> 

write a simple file like this:

      Property1: value
      Property2: value
      etc.

Save your file .. Now call the function ....

    var objectfile = {};

function getfilecontent(url){
    var cli = new XMLHttpRequest();
    
    cli.onload = function(){
         if((this.status == 200 || this.status == 0) && this.responseText != null) {
        var r = this.responseText;
        var b=(r.indexOf('\n')?'\n':r.indexOf('\r')?'\r':'');
        if(b.length){
        if(b=='\n'){var j=r.toString().replace(/\r/gi,'');}else{var j=r.toString().replace(/\n/gi,'');}
        r=j.split(b);
        r=r.filter(function(val){if( val == '' || val == NaN || val == undefined || val == null ){return false;}return true;});
        r = r.map(f => f.trim());
        }
        if(r.length > 0){
            for(var i=0; i<r.length; i++){
                var m = r[i].split(':');
                if(m.length>1){
                        var mname = m[0];
                        var n = m.shift();
                        var ivalue = m.join(':');
                        objectfile[mname]=ivalue;
                }
            }
        }
        }
    }
cli.open("GET", url);
cli.send();
}

now you can get your values efficiently.

getfilecontent('mesite.com/mefile.txt');

window.onload = function(){
 
if(objectfile !== null){
alert (objectfile.property1.value);
}
}

It's just a small gift to contribute to the group. Thanks for your like :)

If you want to test the function on your PC locally, restart your browser with the following command (supported by all browsers except safari):

yournavigator.exe '' --allow-file-access-from-files
Ahmad Adibzad
  • 501
  • 2
  • 6
  • 14
Cherif
  • 53
  • 2
0
<button type="button" onclick="loadXMLDoc()"> GET CONTENT</button>

 <script>
        function loadXMLDoc() {
            var xmlhttp = new XMLHttpRequest();
            var url = "<Enter URL>";``
            xmlhttp.onload = function () {
                if (xmlhttp.readyState == 4 && xmlhttp.status == "200") {
                    document.getElementById("demo").innerHTML = this.responseText;
                }
            }
            xmlhttp.open("GET", url, true);
            xmlhttp.send();
        }
    </script>
Rama
  • 185
  • 2
  • 4
0

A basic fetch request is really simple to set up. Have a look at the following code:

fetch('https://jsonplaceholder.typicode.com/posts/1')
  .then((response) => response.json())
  .then((data) => console.log(data));
Surya R Praveen
  • 3,393
  • 1
  • 24
  • 25