I am trying to make an API request and put the return in a div.. What am I doing wrong?
<!DOCTYPE HTML>
<html>
<head>
<script>
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://data.mtgox.com/api/2/BTCUSD/money/ticker_fast?pretty", false);
xhr.send();
xhr = function() {
document.getElementById("myDiv").innerHTML=xhr.responseText;
}
</script>
</head>
<body>
<div id="myDiv"></div>
</body>
</html>
You need to bind onto the onload listener instead of setting a value to xhr:
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://data.mtgox.com/api/2/BTCUSD/money/ticker_fast?pretty", false);
xhr.onload = function() {
document.getElementById("myDiv").innerHTML=this.responseText;
};
xhr.send();
See the MDN docs on Using XMLHttpRequest.
You need
xhr.onload = function() { //onload
document.getElementById("myDiv").innerHTML=xhr.responseText;
}
Related
I want when I click the button a GET Request to send but I don't know how to connect the AJAX script with the button.
<script>
var url = "http://myurl.com";
var xhr = new XMLHttpRequest();
xhr.open("GET", url);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
console.log(xhr.status);
console.log(xhr.responseText);
}};
xhr.send();
</script>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<button>Make a request</button>
you need transform it in a function and call by the button:
<script>
function call()
{
var url = "http://myurl.com";
var xhr = new XMLHttpRequest();
xhr.open("GET", url);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
console.log(xhr.status);
console.log(xhr.responseText);
}};
xhr.send();
}
</script>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<button onclick="call();">Make a request</button>
Seeing as you are importing Jquery, there is also a helper function to fetch data from an AJAX request, you can use it like this:
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<button>Make a request</button>
<!-- Javascript -->
<script>
$('button').click(function(){
$.get("http://myurl.com", function(result) {
console.log(result);
});
});
</script>
this is my second post, I hope to be luckier than last time end get some reply. 🙂
I’m trying to make a Rapidapi api request working with javascript ”XMLHttpRequest”
I must say that the api works perfectly with ios siri shortcut.
this is the code provided from apirapit site on the "XMLHttpRequest" section:
var data = null;
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function () {
if (this.readyState === this.DONE) {
console.log(this.responseText);
}
});
xhr.open("GET", "https://download-video-youtube1.p.rapidapi.com/mp3/medPORJ8KO0");
xhr.setRequestHeader("x-rapidapi-host", "download-video-youtube1.p.rapidapi.com");
xhr.setRequestHeader("x-rapidapi-key", "[my key here]");
xhr.send(data);
And this is my code:
<!DOCTYPE html>
<html>
<body>
<h2>The XMLHttpRequest Object</h2>
<button type="button" onclick="loadDoc()">Request data</button>
<p id="demo"></p>
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.withCredentials = true;
url='https://download-video-youtube1.p.rapidapi.com/mp3/xF5t2jOsCt8';
xhttp.onreadystatechange = function() {
if ((this.readyState == 4 && this.status == 200 )||(this.readyState === this.DONE)) {
document.getElementById("demo").innerHTML = "ciao" + this.responseText;
}
};
xhttp.open("GET", url);
xhttp.setRequestHeader("x-rapidapi-host", "download-video-youtube1.p.rapidapi.com");
xhttp.setRequestHeader("x-rapidapi-key", "[my key here]");
xhttp.send();
}
</script>
</body>
</html>
Just to testing I created a simply bank html page to have the JSON response beneath the button just after pressing it. The result is just the string “ciao” i set before the this.responseText. If I remove the apikey or modify it with a wrong value an JSON error message appear ( so like the case posted, as I intentionally removed it).
Otherwise as said noting but “ciao” string
Is there any syntax error? Is there a logical reason why it behave like this?
Thanks
Franco
Trying adding a data variable as null. That's what RapidAPI provides in their code snippet.
function loadDoc() {
const data = null
var xhttp = new XMLHttpRequest();
xhttp.withCredentials = true;
url='https://download-video-youtube1.p.rapidapi.com/mp3/xF5t2jOsCt8';
xhttp.onreadystatechange = function() {
if ((this.readyState == 4 && this.status == 200 )||(this.readyState === this.DONE)) {
document.getElementById("demo").innerHTML = "ciao" + this.responseText;
}
};
xhttp.open("GET", URL);
xhttp.setRequestHeader("x-rapidapi-host", "download-video-youtube1.p.rapidapi.com");
xhttp.setRequestHeader("x-rapidapi-key", "my key here");
xhttp.send(data);
}
I want display a set of thumbnail images using fileReader api of javascript.I will send requests to my server and it will respond with a stream of bytes.I am sending requests through native xhr methods.But its not displaying any images.
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript" src="/js/jquery-2.1.1.js"></script>
<script>
var thumbURL = ['https://domainname.com/api/th/1','https://domainname.com/api/th/2','https://domainname.com/api/th/3','https://domainname.com/api/th/4','https://domainname.com/api/th/5','https://domainname.com/api/th/6'];
(function(){
for(var i=0;i<thumbURL.length;i++){
var oReq = new XMLHttpRequest();
oReq.open("GET", thumbURL[i]);
oReq.responseType = "blob";
oReq.onload = function(oEvent) {
if (this.status == 200) {
var fileReader = new window.FileReader();
fileReader.readAsDataURL(this.response);
var response=fileReader.result;
$("#thumbnails").append("<img src="+response+"></div>");
}
};
oReq.send();
}
})();
</script>
</head>
<body>
<div id="thumbnails"></div>
</body>
</html>
Any help will be greatly appreciated.Thanks in advance.
UPDATE:correct solution
<html>
<head>
<script type="text/javascript" src="/js/jquery-2.1.1.js"></script>
<script>
var thumbURL = ['https://domainname.com/api/th/1','https://domainname.com/api/th/2','https://domainname.com/api/th/3','https://domainname.com/api/th/4','https://domainname.com/api/th/5','https://domainname.com/api/th/6'];
(function(){
for(var i=0;i<thumbURL.length;i++){
var oReq = new XMLHttpRequest();
oReq.open("GET", thumbURL[i]);
oReq.responseType = "blob";
oReq.onload = function(oEvent) {
if (this.status == 200) {
var filereader=new window.FileReader();
filereader.readAsDataURL(this.response);
filereader.addEventListener("load",function() {
var response=filereader.result;
$("#thumbnails").append("<img src="+response+"></div>");
},false);
}
};
oReq.onerror=function(e){
alert("error");
};
oReq.send();
}
})();
</script>
</head>
<body>
<div id="thumbnails"></div>
</body>
</html>
The FileReader API is asynchronous so you have to add a load handler and when triggered, then add the result:
var fileReader = new window.FileReader();
fileReader.onload = function() { // need load handler
var response=this.result;
$("#thumbnails").append("<img src="+response+"></div>");
};
fileReader.readAsDataURL(this.response);
I would in any case recommend to skip the conversion part. Using the blob directly not only saves memory, but is much faster. You just have to create the image element manually, for example:
oReq.onload = function(oEvent) {
if (this.status === 200) {
var img = new Image;
img.src = (URL || webkitURL).createObjectURL(this.response);
$("#thumbnails").append(img); // todo: append the </div> separately
}
};
Is it possible to call a text file similarily to how you would reference an image in a image tag? Similar to
<img src="http://link.to/image.png">
but
<p src="http://link.to/text.txt"></p>
?
Can you do this with javascript? Any advice would be super appreciated!
You can do this with XHR (XMLHttpRequest) . Pure Javascript:
<p id="text"></p>
<script>
text = document.getElementById('text');
xhr = new XMLHttpRequest();
xhr.open("GET", "http://link.to/file.txt");
xhr.send();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) //the readyState if the status of the request
text.innerHTML = xhr.responseText; // (http://www.w3schools.com/ajax/ajax_xmlhttprequest_onreadystatechange.asp)
// 4 is a completed request
}
</script>
Or, jQuery has the .load() function:
<p id="text"></p>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$('#text').load('http://link.to/file.txt');
</script>
You can load the remote content via AJAX, as long as the remote server sends you proper CORS headers.
Something like this should work:
var $p = document.getElementsByTagName('p')[0];
var url = $p.getAttribute('src');
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function insertContents() {
if (xhr.readyState === 4 && xhr.status === 200) {
$p.innerHTML = xhr.responseText;
}
};
xhr.open('GET', url);
xhr.send();
possible with ajax
<p data-src="http://link.to/text.txt"></p>
JS:
$('p').each(function () {
var $this = $(this);
$.ajax({
url: $this.data('src'),
dataType: "text",
success: function (data) {
$this.html(data);
}
});
});
var client = new XMLHttpRequest();
client.open('GET', 'text.txt');
client.onreadystatechange = function() {
alert(client.responseText);
}
client.send();
You can display text file using IFrame. Like this-
I've created the code below, but it is not working properly. Where have I gone wrong and or what did I forget to include?
var search = document.getElementById("search").value;
var xhr = new XMLHttpRequest();
function results() {
console.log(search);
xhr.send()
}
document.getElementById("results").innerHTML = results();
// Send the XHR
xhr.open('GET', 'https://api.soundcloud.com/tracks?client_id=1dff55bf515582dc759594dac5ba46e9&q=" + search;', true);
<html>
<head>
<!-- JS -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
</head>
<body>
<input type="search" id="search" />
<button onclick="results()">Search</button>
<p id="results"></p>
</body>
</html>
Your code will run on page-load but you want to create an event listener that waits for your user to press Search and then execute your request.
Try:
$('#search').click(function(){
var search = document.getElementById("search").value;
var xhr = new XMLHttpRequest();
var results = xhr.open('GET', 'https://api.soundcloud.com/tracks?client_id=1dff55bf515582dc759594dac5ba46e9&q=" + search;', false);
document.getElementById("results").innerHTML = results;
})
The 'false' parameter in the xhr request prevents the code from running asynchronously but I am sure you could somehow use callbacks?
Figured it out...
function audioResults(){
var search = document.getElementById("search").value;
var xhr = new XMLHttpRequest();
xhr.open('GET', "https://api.soundcloud.com/tracks?client_id=1dff55bf515582dc759594dac5ba46e9&q=" + search, false);
xhr.addEventListener("load", function() {
document.getElementById("results").innerHTML = xhr.response;
}, false);
xhr.send();
}
<html>
<head>
<!-- JS -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
</head>
<body>
<input type="search" id="search" />
<button onclick="audioResults()">Search</button>
<p id="results"></p>
</body>
</html>