Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
How can I read this API and get information from it?
to javascript.
https://bitcoinfees.earn.com/api/v1/fees/recommended
this does not seem to work -
loadJSON("https://bitcoinfees.earn.com/api/v1/fees/recommended", gotData, 'jsonp');
function gotData(data) {
println(data);
}
loadJSON is not a native JS function(it is in library p5). You can use the fetch function like this:
fetch("https://bitcoinfees.earn.com/api/v1/fees/recommended") // Call the fetch function passing the url of the API as a parameter
.then((resp) => resp.json()) // Transform the data into json
.then(function(data) {
// Your code for handling the data you get from the API
console.log(data);
console.log(data.fastestFee); //And since it is just an object you can access any value like this
})
.catch(function(err) {
// This is where you run code if the server returns any errors (optional)
console.log(err)
});
Using javascript only:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
// Typical action to be performed when the document is ready:
document.getElementById("demo").innerHTML = xhttp.responseText;
alert(JSON.stringify(xhttp.responseText));
//To display fastestFee's value
var parseData = JSON.parse(xhttp.responseText);
alert(parseData.fastestFee);
}
};
xhttp.open("GET", "https://bitcoinfees.earn.com/api/v1/fees/recommended", true);
xhttp.send();
<div id="demo"> </div>
First result on Google. Learn it. Use it.
var url = "https://bitcoinfees.earn.com/api/v1/fees/recommended";
var req = $.ajax(url, {
success: function(data) {
console.log(data);
},
error: function() {
console.log('Error!');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Related
This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 4 months ago.
I can't find a way to use the value obtained from the JSON function from ipify.org.
I need to use this value in another function, not just write it in HTML like in the examples on ipify.org.
I'm trying to assign a value to the window variable, but it can also be done in another way. I am trying to use the "javascript" example on the site: https://www.ipify.org/
<script type="text/javascript">
function getIP(json) {
window.ipa = json.ip;
}
alert(window.ipa); //return "undefined"
</script>
<script type="text/javascript" src="https://api.ipify.org?format=jsonp&callback=getIP"></script>
You have to make the request to and capture the response from api.ipify.org in your script, there are many ways to do this, I used the old, native XMLHttpRequest API.
You also need to attach this function call to an event (I used "onload" bellow).
Example:
function xhrget(items, route, callback){
const xhr = new XMLHttpRequest();
xhr.open('GET', route);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.timeout = 1000;
xhr.send(encodeURI(items));
xhr.ontimeout = function(e){
callback('404');
};
xhr.onreadystatechange = function () {
if(xhr.readyState === 4 && xhr.status === 200) {
callback(xhr.responseText);
}
if(xhr.status >= 500 && xhr.status < 600){
callback('An error occurred, please wait a bit and try again.');
}
if(xhr.status === 404) {
callback('404');
}
};
}
function getIP() {
xhrget(null, "https://api.ipify.org", (ip) => {
console.log(ip);
window.ipa = ip;
alert(window.ipa); //return "undefined"
});
}
window.addEventListener('load', (event) => {
getIP();
});
What is the correct way to call this API? The api url is: https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd
I tried with this code
<p id="demo">
</p>
<script>
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myObj = JSON.parse(this.responseText);
document.getElementById("demo").innerHTML = myObj.bitcoin;
}
};
xmlhttp.open("GET", "https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd" + new Date().getTime(), true);
xmlhttp.send();
</script>
however the value I get is [object Object]. I want to get the value in "usd".
Where am I wrong? Thx
Replaces myObj with myObj.usd but returns null value
The API returns in the form of {"bitcoin":{"usd": -insert value here-}}, so you have to use myObj.bitcoin.usd
You need to access the usd part of the object when you set the innerHTML as #SuspenseFallback mentioned.
You also need to remove the + new Date().getTime() part from your URL string. I don't see a date part in the API docs for the price endpoint.
you should use the fetch method. the better and the modern way of calling API using native javascript.
There is no problem with the way you did it but there are a few things that you can do with fetch and not with XHR.
you can read more about fetch by this link: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API
there is an example of using fetch:
fetch(
"https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd"
)
.then((response) => response.json())
.then((data) => {
console.log(data);
});
or you can use async-await to achieve the same result :
(async () => {
const response = await fetch(
"https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd"
);
const data = await response.json();
console.log(data);
})();
note: I have used Javascript Self Invoking Functions which is a
function that calls itself.
The answers quickly resolve the issue, however I ran into another problem where there are hyphenated words.
Sample API:
https://api.coingecko.com/api/v3/simple/price?ids=bitcoin-cash&vs_currencies=usd
This question already has answers here:
How to replace the entire html webpage with ajax response?
(6 answers)
How to replace innerHTML of a div using jQuery?
(14 answers)
Closed 3 years ago.
In index.html, I'm getting a value stored in localStorage:
<script>
function checkChannel() {
if (localStorage.getItem('channel')) {
const channel = localStorage.getItem('channel');
const request = new XMLHttpRequest();
request.open('POST', '/convert');
// Add data to send with request
const data = new FormData();
data.append('channel', channel);
// Send request
request.send(data);
}
}
</script>
</head>
<body onload="checkChannel()">
.
.
.
This works fine. It is routed to the code below in application.py. The debugger hits the first line in convert() below, so I know it's getting there.
#app.route("/convert", methods=["POST"])
def convert():
channel = request.form.get("channel")
channel_messages = channels_dict[channel]
return render_template("channel.html", channel=channel, channel_messages=channel_messages)
However, channel.html is not being rendered. Instead, it stays on the same page. What am I doing wrong here? I can give more details if needed.
You need to define a request.onload() function. This function will be called after the response is received. so your JS code will be similar to this:
function checkChannel() {
if (localStorage.getItem('channel')) {
const channel = localStorage.getItem('channel');
const request = new XMLHttpRequest();
request.open('POST', '/convert');
// Add data to send with request
const data = new FormData();
data.append('channel', channel);
// Send request
request.send(data);
// 4. This will be called after the response is received
request.onload = function() {
if (request.status != 200) {
// analyze HTTP status of the response
alert(`Error ${request.status}: ${request.statusText}`);
// e.g. 404: Not Found
} else { // show the result
$('body').html(request.response)
}
};
}
}
Please note that you can replace $('body').html('some content') by $('div').html('some content') or $('#some-id').html('some content') based on channel.html file content.
Please find this example.
Before I explain what I want to do, here's an MCV of what I'm coding
$("#button").submit(function(event) {
event.preventDefault();
var formData = new FormData(this);
var myString = $('#textarea').val();
var myRegexp = /src="blob:([^'"]+)"/gm;
match = myRegexp.exec(myString);
var inProgress = 0;
while (match != null) {
var xhr = new XMLHttpRequest();
addr = match[1];
xhr.open('GET', 'blob:' + addr, true);
xhr.responseType = 'blob';
xhr.onload = function(e) {
if (this.status == 200) {
var myBlob = this.response;
var data = new FormData();
data.append('file', myBlob);
$.ajax({
url: "uploader.php",
type: 'POST',
data: data,
contentType: false,
processData: false,
beforeSend: function() {
inProgress++;
},
success: function(data) {
myString = myString.replace("blob:" + addr, data);
},
error: function() {
// error
},
complete: function() {
--inProgress;
}
});
} else {
// error
}
};
xhr.send();
match = myRegexp.exec(myString);
}
if (!inProgress) {
formData.set('textarea', myString);
submitForm(formData);
}
});
So, I have a text area and it contains an unknown number of BLOB objects. I first try to find these BLOB objects using regexp and then I upload them to the server using a PHP file called uploader.php. Once the file is uploaded, it will return the URL of the uploaded file and I want to replace the BLOB URL by the URL of the uploaded file in the text area and then submit the final content of the textarea to the server for further processing.
It turns out that when I run the code, only the last instance of the regexp is replaced by its uploaded URL. The others remain as they were. I suspect that this is because the while loop does not wait for the ajax requests to be complete. I had a similar problem when trying to submit the form and I solved it by following the suggestions in this answer but I don't know how to fix this issue this time.
Any idea is appreciated
Update: I tried to make ajax work synchronously but my browser said that it was deprecated and it didn't work.
It seems you don't really need it to be synchronous (and I can't see a case when it's better to make an async action look synchronous), but rather only need it to be sequential.
It is possible to make async actions sequential by the use of callbacks (which are rewritable as Promise and in turn rewritable as async/await methods but I'll keep it simple):
// myString is made global for simplicity
var myString;
function uploadBlob(myBlob, addr, callback) {
var data = new FormData();
data.append('file', myBlob);
$.ajax({
url: "uploader.php",
type: 'POST',
data: data,
contentType: false,
processData: false,
success: function(data) {
// file uploaded OK, replace the blob expr by the uploaded file url(data)
myString = myString.replace("blob:" + addr, data);
callback();
},
error: function() {
// error, the uploaded most likely failed, we leave myString alone
// or alternatively replace the blob expr by empty string
// because maybe we dont want to post blob in the final form submit
// uncomment if needed
// myString = myString.replace("blob:" + addr, "");
callback();
}
});
}
function getBlobAndUpload(addr, callback) {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'blob:' + addr, true);
xhr.responseType = 'blob';
xhr.onload = function(e) {
if (this.status == 200) {
var myBlob = this.response;
uploadBlob(myBlob, addr, callback);
} else {
// error, but callback anyway to continue processing
callback();
}
};
xhr.send();
}
function processAddresses(addresses, callback, current) {
var index = current || 0;
// all addresses processed?
if (index >= addresses.length) {
// yes no more address, call the callback function
callback();
} else {
var addr = addresses[index];
// once the get/upload is done the next address will be processed
getBlobAndUpload(addr, function() {
processAddresses(addresses, callback, index + 1);
});
}
}
$("#button").submit(function(event) {
event.preventDefault();
var formData = new FormData(this);
var addresses = [];
// initialize both localString and myString to the content of the textArea
// localString will be used to extract addresses,
// while myString will be mutated during the upload process
var localString = myString = $('#textarea').val();
var myRegexp = /src="blob:([^'"]+)"/gm;
match = myRegexp.exec(localString);
// collect all addresses first
while (match != null) {
addr = match[1];
addresses.push(addr);
match = myRegexp.exec(localString);
}
// initiate sequential processing of all addresses, and
// pass the callback function triggering the form submit
processAddresses(addresses, function() {
// all the successfully uploaded blob exprs in my string should
// be now replaced by the remote file url now (see commented part
// in upload blob error for a variation of the feature
formData.set('textarea', myString);
submitForm(formData);
});
});
So. I said in comments, that you could use async/await, and gave links. Now I am going to try to teach you how to work with promises and XMLHttpRequest.
So first thing. I would use my own 'library' (not really a library, just 3 new command) called PromiseReq which has XMLHttpsRequest that returns Promises.
You would need two functions from it:
sendToServer(config, data) and getServerFile(config). They do what their names implies.(sendToServer is not so good at the time, but I will improve it sometime later). They just use Promises as returns. They work in very easy way. Code # Github
BUT It was designed for my uses only, so it is not very flexible (although I hope I will improve it sometime).
So we need to learn how to use Promises.
Firstly you need to know what Promise is and why do we use it.
Then you can create one like this:
let pmq = new Promise((res,rej)=>{
// PROMISE BODY HERE
});
Here first warning. Promises made that way don't support return as a way to resolve Promise! You have to use res()!
Some functions just return them (such as fetch()) and we can handle them right after calling function.
Now pmq will be our promise.
You can use pmq.then(callback) to handle what will happen if somewhere in promise body is res() call and pmq.catch(callback) to handle what happens when rej() is called. Remember, that .catch(cb) and .then(cb) returns a Promise, so you can safely chain more than one .then() and at the end add .catch() and it will handle rejection from every one of .then()s.
For example:
pmq = fetch("file.txt");
pmq.then(e=>console.log(e.json())).then(console.log).catch(console.error);
There is a big note there.
The order in which this events will fire.
If for example rP() waits 1s than logs "A" then resolves, this code:
let a = rP();
a.then(_=>console.log("B")).catch(console.error);
console.log("C");
will result in:
C
A
B
Becuase of this there is async/await needed to do this.
To do so you have to make an async function with keyword async.
let fn = async ()=>{}
Here is second thing. Async functions ALWAYS return Promise. And that is the second way you can create a promise. You just don't use res(), rej() only return and throw.
Now we can call inside fn():
let a = await rP().then(_=>console.log("B")).catch(console.error);
console.log("C");
and we will get our
A
B
C
Now. How to use it with XMLHttpRequest?
You need to create new Promise with simple XMLHttpRequest inside:
let xmlp = (type, path,data) => return new Promise((res,req)=>{
let xhr = new XMLHttpsRequest();
xhr.open(type, path, true); // true implies that is it asynchronous call
//...
xhr.send(data);
});
And now when to resolve?
XMLHttpRequest has useful event properties and events. The one that is best for our case is onreadystatechange.
You can use it like so:
xhr.onreadystatechange = _=>{
if(xhr.readyState === 4 && xhr.status === 200) // Everything went smoothly
res(xhr.responseText);
else if(shr.readyState === 4 && xhr.status !== 200) // Something went wrong!
rej(xhr.status);
}
And then to get data you can either
Async/Await
// INSIDE ASYNC FUNCTION
let resData = await xmpl("GET", "path.txt", null).catch(console.error);
.then()
let resData;
xmpl("GET", "path.txt", null).then(r=>{
resData = r;
// REST OF WHOLE FUNCTION TO ENSURE THAT resData HAS BEEN SET
})
.catch(console.error);
You can also send data with xmpl().
xmpl("POST", "observer.php", "Data to send to observer.php!")
.then(whatToDoAfterSendFN);
/*
to get such data in PHP you have to use
$post = file_get_contents('php://input');
*/
I know that this answer is a bit messy and stuff, but I didn't have any idea how to write it :P Sorry.
I was wondering if there's any ES6 way of getting json or other data from a url.
jQuery GET and Ajax calls are very common but I don't want to use jQuery in this one.
A typical call would look like this:
var root = 'http://jsonplaceholder.typicode.com';
$.ajax({
url: root + '/posts/1',
method: 'GET'
}).then(function(data) {
console.log(data);
});
or without jQuery something like this:
function loadXMLDoc() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
if (xmlhttp.status == 200) {
document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
}
else if (xmlhttp.status == 400) {
alert('There was an error 400');
}
else {
alert('something else other than 200 was returned');
}
}
};
xmlhttp.open("GET", "ajax_info.txt", true);
xmlhttp.send();
}
My question is...Is there any new ways of doing this ... for example ES6 or is it still the same way?
FETCH API
Example:
// url (required), options (optional)
fetch('https://davidwalsh.name/some/url', {
method: 'get'
}).then(function(response) {
}).catch(function(err) {
// Error :(
});
For more information:
https://developer.mozilla.org/en/docs/Web/API/Fetch_API
Yes there is, using the new Fetch API. Using that you can compess it as much as doing something like:
fetch(url).then(r => r.json())
.then(data => console.log(data))
.catch(e => console.log("Booo"))
However, it's not supported by all browsers yet and not everybody is equally positive about the Fetch API implementation.
Anyhow, you can create your own opinion on that and read up more on it here.
What you want is the Fetch API, but the Fetch API is not a part of ES6 - it just happens to use Promises, which were standardised in ES6.
To get JSON from a URL with the Fetch API:
window.fetch('/path/to.json')
.then(function(response){
return response.json();
}).then(function(json){
return doSomethingWith(json);
});
If you need to support browsers which don’t have the Fetch API, Github has open sourced a polyfill.
Here is another method using axios which is a Promise based HTTP client for the browser and node.js.
Installation:
npm install --save axios
or
yarn add axios
Then, in your project file:
import axios from 'axios'
const data = axios.get('/path/to/your/data.json')