Using promise to call Ajax without duplicating code - javascript

is this possible? I want to write an ajax function, that I do not want to duplicate it. Pass it different parameter which are locations to different files. Then use the promise to make them into one object. I would possible use the spread operator. is this possible.
var myFuncCalls = 0;
let promiseAjax = new Promise (function ( resolve,reject) {
//possibly use a for look to grab the number of times the loadDoc was called then call the same function and send it to may be an array?
function loadDoc(location) {
myFuncCalls++;
console.log("loadDoc was called :" + myFuncCalls);
var xyz = new XMLHttpRequest();
xyz.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
//console.log(this.responseText)
resolve(this.responseText);
}
};
xyz.open("GET", location, true);
xyz.send();
}
loadDoc("/_js/someitems.json");
loadDoc("/_js/someMoreItems.json");
})
// then grab all that stuff and make one single object using spread operators
promiseAjax.then(function (fromResolve){
// JSON.parse(fromResolve);
var newObj = JSON.parse(fromResolve);
console.log(newObj);
})

with Promise.all and Object.assign,
function loadDoc(location) {
return new Promise((resolve, reject) => {
var xyz = new XMLHttpRequest();
xyz.onreadystatechange = () => {
if (this.readyState == 4 && this.status == 200) {
resolve(JSON.parse(this.responseText));
} else {
// resolving with empty object to avoid breaking other fetch if one failed
resolve({});
}
};
xyz.open("GET", location, true);
xyz.send();
});
}
const loadDocs = (paths) => Promise.all(paths.map(path => loadDoc(path))
.then(results => {
// combine all result into single object
return Object.assign({}, ...results);
}));
// example
loadDocs([
"/_js/someitems.json",
"/_js/someMoreItems.json"
]).then(function(finalCombinedObject) {
// other logic here
});

Use Promise.all() to get the two calls together and so what ever you want with the array of the data you resolved.
function loadDoc(location) {
return new Promise (function ( resolve,reject) {
var xyz = new XMLHttpRequest();
xyz.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
resolve(this.responseText);
}
};
xyz.open("GET", location, true);
xyz.send();
});
}
const urls = ["/_js/someitems.json", "/_js/someMoreItems.json"]
Promise.all(urls.map(url=>loadDoc(url))).then(responses =>
console.log(responses);
)

I think the easiest thing would be to define async functions, which return promises and can be easily passed around and reused.
You can do something like:
async function loadFile(file) {
...
return {...fileJSON};
}
async function loadFiles() {
const file1JSON = await loadFile('file1');
const file2JSON = await loadFile('file2');
return {...file1JSON, ...file2JSON};
}
loadFiles().then((combinedJSON) => {
...
})
These functions can take arguments and be reused like any other function.

This kind of behavior can archived with Promise.all Promise.all white the use of async+await async and the use of more state of the art calls (fetch) makes the code looks cleaner
async function loadAll(docs) {
return Promise.all(docs.map(async doc => {
const result = await fetch('http://example.com/movies.json');
return result.json();
}));
}
(async function() {
const responses = await loadAll(["/_js/someitems.json", "/_js/someMoreItems.json"]);
console.log(responses);
})();
Note: await can only be used from an async function.
Note2: the code is untested

Yes, youcan send the URL, any parameters, even the type of AJAX call (POST, GET, etc), to the method, then use it to build the call. This way, you can reuse the same method to do anything and everything you need to do from your client with a "simple" method call.
All code in this Answer is copied from the below link.
https://medium.com/front-end-weekly/ajax-async-callback-promise-e98f8074ebd7
function makeAjaxCall(url, methodType)
{
var promiseObj = new Promise(function(resolve, reject)
{
var xhr = new XMLHttpRequest();
xhr.open(methodType, url, true);
xhr.send();
xhr.onreadystatechange = function()
{
if (xhr.readyState === 4)
{
if (xhr.status === 200)
{
console.log("xhr done successfully");
var resp = xhr.responseText;
var respJson = JSON.parse(resp);
resolve(respJson);
}
else
{
reject(xhr.status);
console.log("xhr failed");
}
}
else {console.log('xhr processing going on');}
}
console.log("request sent succesfully");
});
return promiseObj;
}
enter code here
document.getElementById('userDetails').addEventListener('click', function()
{
// git hub url to get btford details
var userId = document.getElementById("userId").value;
var URL = "https://api.github.com/users/"+userId;
makeAjaxCall(URL, "GET").then(processUserDetailsResponse, errorHandler);
});
You can even send it the callback method. I also send it a method to use for errors.
function makeAjaxCall(url, methodType, callback)
{
$.ajax(
{
url : url,
method : methodType,
dataType : "json",
success : callback,
error : function (reason, xhr){
console.log("error in processing your request", reason);
}
});
}
// git hub url to get btford details
var URL = "https://api.github.com/users/btford";
makeAjaxCall(URL, "GET", function(respJson)
{
document.getElementById("userid").innerHTML = respJson.login;
document.getElementById("name").innerHTML = respJson.name;
document.getElementById("company").innerHTML = respJson.company;
document.getElementById("blog").innerHTML = respJson.blog;
document.getElementById("location").innerHTML = respJson.location;
});

Related

How to add some value to .js file? [duplicate]

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.
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);
}
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;
}
In jQuery:
$.get(
"somepage.php",
{paramOne : 1, paramX : 'abc'},
function(data) {
alert('page content: ' + data);
}
);
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
});
A version without callback
var i = document.createElement("img");
i.src = "/your/GET/url?params=here";
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;
}
}
}
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);
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)
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.
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
Prototype makes it dead simple
new Ajax.Request( '/myurl', {
method: 'get',
parameters: { 'param1': 'value1'},
onSuccess: function(response){
alert(response.responseText);
},
onFailure: function(){
alert('ERROR');
}
});
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();
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
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;
});
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.
Let some basic constants
let data;
const URLAPI = "https://gorest.co.in/public/v1/users";
function setData(dt) {
data = dt;
}
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;
});
}
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);
})
}
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())
)
)();
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));
In your widget's Info.plist file, don't forget to set your AllowNetworkAccess key to true.
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.
});
You can get an HTTP GET request in two ways:
This approach based on xml format. You have to pass the URL for the request.
xmlhttp.open("GET","URL",true);
xmlhttp.send();
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);
}});
});
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 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 my two years of javascript heavy development speaking.
now with asynchronus js we can use this method with fetch() method to make promises in a more concise way. Async functions are supported in all modern browsers.
async function funcName(url){
const response = await fetch(url);
var data = await response.json();
}
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
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();
});
}
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();
}
Ajax
You'd be best off using a library such as Prototype or jQuery.
// 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()
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();
});
}
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.
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
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 him and to 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 contibute to the group. Thanks of 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
<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>

How do I assign text from file to a variable with javascript? [duplicate]

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.
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);
}
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;
}
In jQuery:
$.get(
"somepage.php",
{paramOne : 1, paramX : 'abc'},
function(data) {
alert('page content: ' + data);
}
);
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
});
A version without callback
var i = document.createElement("img");
i.src = "/your/GET/url?params=here";
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;
}
}
}
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);
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)
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.
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
Prototype makes it dead simple
new Ajax.Request( '/myurl', {
method: 'get',
parameters: { 'param1': 'value1'},
onSuccess: function(response){
alert(response.responseText);
},
onFailure: function(){
alert('ERROR');
}
});
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();
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
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;
});
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.
Let some basic constants
let data;
const URLAPI = "https://gorest.co.in/public/v1/users";
function setData(dt) {
data = dt;
}
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;
});
}
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);
})
}
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())
)
)();
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));
In your widget's Info.plist file, don't forget to set your AllowNetworkAccess key to true.
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.
});
You can get an HTTP GET request in two ways:
This approach based on xml format. You have to pass the URL for the request.
xmlhttp.open("GET","URL",true);
xmlhttp.send();
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);
}});
});
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 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 my two years of javascript heavy development speaking.
now with asynchronus js we can use this method with fetch() method to make promises in a more concise way. Async functions are supported in all modern browsers.
async function funcName(url){
const response = await fetch(url);
var data = await response.json();
}
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
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();
});
}
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();
}
Ajax
You'd be best off using a library such as Prototype or jQuery.
// 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()
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();
});
}
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.
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
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 him and to 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 contibute to the group. Thanks of 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
<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>

Chaining promises - correct methodology

I'm trying to create an excel add-in using Javascript that requires asynchronous functions return a JS promise to Excel and that the promise is resolved with the final value using the callback function. I am new to promises and have spent hours reading and testing this out with no success, and was hoping someone could help me understand what I'm doing wrong. Below is the code:
function TEST(num1) {
return new Promise(function (resolve) {
var corsproxy = "https://cors-anywhere.herokuapp.com/"
var apiurl = "https://randomapi.com/testapi"
var data = getData(corsproxy+apiurl).then(function(result){
console.log ("here it comes")
console.log(result.meta.status) /// This returns "Success"
return (result.meta.status) /// I need this to be resolved
})
console.log("last")
resolve(data)
})
};
/// Get JSON
function getData(url) {
return new Promise(function (resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'json';
xhr.onload = function () {
try {
if (xhr.status === 200) {
resolve(xhr.response);
}
else if (xhr.status !== 200) {
reject({
error: 'Request failed. ' + xhr.response
});
}
} catch (e) {
reject({
error: e
});
}
};
xhr.send();
});
}
The second function getData is working as intended and returning a JS Object. What I'm trying to accomplish with the TEST function is:
Create a new promise - this needs to be resolved/returned as "Success"
Call the API data with getData(temporarily running through a proxy to bypass CORS erros)
Extract the meta.status value ("Success")
I've tried a number of different things but the current code write "last" and resolves an undefined data before the getData function completes. Changing the "return (result.meta.status)" to "resolve (result.meta.status)" also doesn't help.
Any assistance with what I'm doing wrong would be greatly appreciated.
function TEST(num1) {
var corsproxy = "https://cors-anywhere.herokuapp.com/"
var apiurl = "https://randomapi.com/testapi"
return getData(corsproxy+apiurl)
}
TEST(valofnum1).then(function(result){
console.log ("here it comes")
console.log(result.meta.status) /// This returns "Success"
return (result.meta.status) /// Needs to be resolved
})
that's how you chain promises. you don't resolve a promise within another promise,
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises
You can use async/await since ES6 that solves a lot of this headache by simplifying the chain process into using await statements when letting promises resolve. I've updated your code block to use it, take a look:
async function TEST(num1) {
return new Promise(function (resolve) {
var corsproxy = "https://cors-anywhere.herokuapp.com/"
var apiurl = "https://randomapi.com/testapi"
var result = await getData(corsproxy+apiurl);
resolve(result.meta.status)
})
};
/// Get JSON
function getData(url) {
return new Promise(function (resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'json';
xhr.onload = function () {
try {
if (xhr.status === 200) {
resolve(xhr.response);
}
else if (xhr.status !== 200) {
reject({
error: 'Request failed. ' + xhr.response
});
}
} catch (e) {
reject({
error: e
});
}
};
xhr.send();
});
}
Changes made:
TESTis now an async function.
Rather chaining the resolved promise from getData and resolving in TEST, you simply await the response from getData and then resolve it.

Reading JSON using JavaScript [duplicate]

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.
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);
}
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;
}
In jQuery:
$.get(
"somepage.php",
{paramOne : 1, paramX : 'abc'},
function(data) {
alert('page content: ' + data);
}
);
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
});
A version without callback
var i = document.createElement("img");
i.src = "/your/GET/url?params=here";
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;
}
}
}
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);
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)
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.
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
Prototype makes it dead simple
new Ajax.Request( '/myurl', {
method: 'get',
parameters: { 'param1': 'value1'},
onSuccess: function(response){
alert(response.responseText);
},
onFailure: function(){
alert('ERROR');
}
});
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();
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
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;
});
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.
Let some basic constants
let data;
const URLAPI = "https://gorest.co.in/public/v1/users";
function setData(dt) {
data = dt;
}
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;
});
}
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);
})
}
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())
)
)();
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));
In your widget's Info.plist file, don't forget to set your AllowNetworkAccess key to true.
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.
});
You can get an HTTP GET request in two ways:
This approach based on xml format. You have to pass the URL for the request.
xmlhttp.open("GET","URL",true);
xmlhttp.send();
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);
}});
});
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 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 my two years of javascript heavy development speaking.
now with asynchronus js we can use this method with fetch() method to make promises in a more concise way. Async functions are supported in all modern browsers.
async function funcName(url){
const response = await fetch(url);
var data = await response.json();
}
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
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();
});
}
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();
}
Ajax
You'd be best off using a library such as Prototype or jQuery.
// 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()
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();
});
}
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.
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
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 him and to 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 contibute to the group. Thanks of 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
<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>

HTTP GET request in JavaScript?

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.
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);
}
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;
}
In jQuery:
$.get(
"somepage.php",
{paramOne : 1, paramX : 'abc'},
function(data) {
alert('page content: ' + data);
}
);
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
});
A version without callback
var i = document.createElement("img");
i.src = "/your/GET/url?params=here";
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;
}
}
}
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);
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)
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.
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
Prototype makes it dead simple
new Ajax.Request( '/myurl', {
method: 'get',
parameters: { 'param1': 'value1'},
onSuccess: function(response){
alert(response.responseText);
},
onFailure: function(){
alert('ERROR');
}
});
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();
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
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;
});
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.
Let some basic constants
let data;
const URLAPI = "https://gorest.co.in/public/v1/users";
function setData(dt) {
data = dt;
}
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;
});
}
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);
})
}
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())
)
)();
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));
In your widget's Info.plist file, don't forget to set your AllowNetworkAccess key to true.
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.
});
You can get an HTTP GET request in two ways:
This approach based on xml format. You have to pass the URL for the request.
xmlhttp.open("GET","URL",true);
xmlhttp.send();
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);
}});
});
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 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 my two years of javascript heavy development speaking.
now with asynchronus js we can use this method with fetch() method to make promises in a more concise way. Async functions are supported in all modern browsers.
async function funcName(url){
const response = await fetch(url);
var data = await response.json();
}
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
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();
});
}
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();
}
Ajax
You'd be best off using a library such as Prototype or jQuery.
// 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()
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();
});
}
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.
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
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 him and to 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 contibute to the group. Thanks of 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
<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>

Categories

Resources