I'm using Giphy's API to learn how to make a random GIF generator. The code below works fine for generating one GIF and putting it in the imageContainer, but I'm wondering what I can add to make a new GIF appear in the imageContainer when the randomDog button is clicked? As it looks now, the request for more GIFs is successful if you click the button, but they are not posted in the image container since there is already a GIF in it.
This is my JavaScript:
document.addEventListener('DOMContentLoaded', function () {
request = new XMLHttpRequest;
request.open('GET', 'http://api.giphy.com/v1/gifs/random?api_key=dc6zaTOxFJmzC&tag=cute+dog', true);
document.getElementById("randomDog").onclick = function () {
if (request.status >= 200 && request.status < 400){
data = JSON.parse(request.responseText).data.image_url;
console.log(data);
document.getElementById("imageContainer").innerHTML = '<center><img src = "'+data+'" title="GIF via Giphy"></center>';
} else {
console.log('reached giphy, but API returned an error');
}
};
request.onerror = function() {
console.log('connection error');
};
request.send();
});
And this is my HTML:
<!DOCTYPE html>
<html>
<head>
<link rel= "stylesheet" type="text/css" href="dogstyle.css">
<meta charset="UTF-8">
<title>Sadness be gone!</title>
</head>
<body>
<div id="headers">
<h1> Having a bad day?</h1>
<h1> Not anymore! </h1>
</div>
<h3 id="subheader">Happiness and fluffyness is just a click away</h3>
<div id="imageContainer"></div>
<button id="randomDog" class="button">Click away!</button>
<script src="js/experiment.js"></script>
</body>
Thanks in advance!
Just move the lines initializing and sending the XMLHttpRequest inside of the click handler, and include the success function inside an onreadystatechange event handler.
(Note that the API key you are using returns an error for me when I use it in a snippet; unsure of how I would fix that but maybe it will work on your end.)
document.addEventListener('DOMContentLoaded', function() {
document.getElementById("randomDog").onclick = function() {
request = new XMLHttpRequest;
request.open('GET', 'http://api.giphy.com/v1/gifs/random?api_key=dc6zaTOxFJmzC&tag=cute+dog', true);
request.onreadystatechange = function() {
if (request.readyState === 4) {
if (request.status >= 200 && request.status < 400) {
data = JSON.parse(request.responseText).data.image_url;
console.log(data);
document.getElementById("imageContainer").innerHTML = '<center><img src = "' + data + '" title="GIF via Giphy"></center>';
} else {
console.log('reached giphy, but API returned an error');
}
}
}
request.onerror = function() {
console.log('connection error');
};
request.send();
};
});
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="dogstyle.css">
<meta charset="UTF-8">
<title>Sadness be gone!</title>
</head>
<body>
<div id="headers">
<h1> Having a bad day?</h1>
<h1> Not anymore! </h1>
</div>
<h3 id="subheader">Happiness and fluffyness is just a click away</h3>
<div id="imageContainer"></div>
<button id="randomDog" class="button">Click away!</button>
<script src="js/experiment.js"></script>
</body>
Try this
....
document.getElementById("randomDog").onclick = function () {
if (request.status >= 200 && request.status < 400){
data = JSON.parse(request.responseText).data.image_url;
console.log(data);
// Clear the existing image first
document.getElementById("imageContainer").removeChild(document.getElementsByClassName("mygif")[0]);
// Now set the new image in image container
document.getElementById("imageContainer").innerHTML = '<center><img class="mygif" src = "'+data+'" title="GIF via Giphy"></center>';
} else {
console.log('reached giphy, but API returned an error');
}
};
....
Related
This is my javascript function which is routing a csv file to /uploader.
function getData() {
var csv=document.getElementById('myFile').files[0];
var formData=new FormData();
formData.append("uploadCsv",csv);
var request = new XMLHttpRequest();
//Open first, before setting the request headers.
request.open("POST", "/uploader", true);
//here you can set the request header to set the content type, this can be avoided.
//The browser sets the setRequestHeader and other headers by default based on the formData that is being passed in the request.
request.setRequestHeader("Content-type", "multipart/form-data"); //----(*)
request.onreadystatechange = function (){
if(request.readyState === XMLHttpRequest.DONE && request.status === 200) {
console.log(request.response);
}
}
request.send(formData);
}
My python function does get invoked to the app routing part seems to correct. However the request.files length is 0.
This is the python code -
#app.route("/uploader", methods=["POST"])
def post_javascript_data():
f = request.files["uploadCsv"]
print(f)
return "OK"
In the picture below you can see the request.files length remains 0. What am I doing wrong here?
The solution is to not manually set the header for the content type. This is set automatically.
The following is an example with XMLHttpRequest and alternatively with fetch.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<!-- Using XMLHttpRequest -->
<form name="upload-form-1">
<input type="file" name="upload-csv" accept="text/csv" />
<input type="submit" />
</form>
<script type="text/javascript">
(function() {
let form = document.querySelector("form[name='upload-form-1']");
form.addEventListener(
"submit",
(event) => {
event.preventDefault();
let xhr = new XMLHttpRequest();
xhr.open("POST", "/uploader");
xhr.onload = function() {
if(this.status === 200) {
console.log(this.response);
} else {
console.error(`Error ${this.status} occurred.`)
}
}
xhr.send(new FormData(event.target));
},
false);
})();
</script>
<!-- Using Fetch -->
<form name="upload-form-2">
<input type="file" name="upload-csv" accept="text/csv" />
<input type="submit" />
</form>
<script type="text/javascript">
(function() {
let form = document.querySelector("form[name='upload-form-2']");
form.addEventListener(
"submit",
(event) => {
event.preventDefault();
fetch("/uploader", {
method: "POST",
body: new FormData(event.target)
}).then(resp => {
console.log(resp);
}).catch(err => {
console.error(err);
});
},
false);
})();
</script>
</body>
</html>
from flask import abort, make_response, request
#app.route('/uploader', methods=['POST'])
def uploader():
if 'upload-csv' in request.files:
f = request.files['upload-csv']
# Use the object of the type werkzeug.FileStorage here.
return make_response('')
abort(400)
Have fun implementing your project.
I am practicing my API skills and decided to make a Crypto Currency calculator (simple enough).
I have been stuck on how to output the value that I want in my HTML doc to a specific DIV "id". To the best of my knowledge everything seems like it should be working but when I try to output the desired value onto my innerHTML it outputs nothing.
I am trying to output this value {"USD":1.94} onto my HTML. However I am not skilled enough to properly call this value from its respective storage. I was hoping if anyone can help me fix this. Thank you.
Here is my HTML:
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Crypto Calc</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" media="screen" href="style.css" />
<!-- <script type="text/javascript" src="https://min-api.cryptocompare.com/"></script> -->
</head>
<body>
<header>
Header
</header>
<div id="pbf-main-container">
</div>
<footer>
Footer
</footer>
<script src="pbf.js"></script>
</body>
</html>
Here is the Javascript:
// Get the HTTP Header Request for CryptoCompare API
var request = new XMLHttpRequest();
request.onreadystatechange = function () {
if (request.readyState === 4) {
if (request.status === 200) {
document.body.className = 'ok';
console.log(request.responseText); // This is the outcome of the curreny value
} else if (!isValid(this.response) && this.status == 0) {
document.body.className = 'error offline';
console.log("The computer appears to be offline.");
} else {
document.body.className = 'error';
}
}
};
request.open("GET", 'https://min-api.cryptocompare.com/data/price?fsym=XRP&tsyms=USD' , true);
request.send(null);
// Putting the outcome of the HTTP request into a Variable
var XRPUSD = request.responseText;
// This it to integrate it with the index.html
// console.log(XRPUSD);
document.getElementById("pbf-main-container").innerHTML = XRPUSD;
Move last five lines
// Putting the outcome of the HTTP request into a Variable
var XRPUSD = request.responseText;
// This it to integrate it with the index.html
// console.log(XRPUSD);
document.getElementById("pbf-main-container").innerHTML = XRPUSD;
after this line
document.body.className = 'ok';
// Putting the outcome of the HTTP request into a Variable
var XRPUSD = request.responseText;
// This it to integrate it with the index.html
// console.log(XRPUSD);
document.getElementById("pbf-main-container").innerHTML = XRPUSD;
// Get the HTTP Header Request for CryptoCompare API
var request = new XMLHttpRequest();
request.onreadystatechange = function () {
if (request.readyState === 4) {
if (request.status === 200) {
document.body.className = 'ok';
console.log(request.responseText); // This is the outcome of the curreny value
// Putting the outcome of the HTTP request into a Variable
var XRPUSD = request.responseText;
// beautify JSON object
document.getElementById("pbf-main-container").innerHTML = JSON.stringify(XRPUSD,null,2);
} else if (!isValid(this.response) && this.status == 0) {
document.body.className = 'error offline';
console.log("The computer appears to be offline.");
} else {
document.body.className = 'error';
}
}
};
request.open("GET", 'https://min-api.cryptocompare.com/data/price?fsym=XRP&tsyms=USD' , true);
request.send(null);
Http request is async,so you
<html>
<head>
<script>
var request = new XMLHttpRequest();
request.open('GET', 'https://www.googleapis.com/youtube/v3/channels?part=statistics&id=UCiWypivJjO5CIQPVVfFlVQA&key=AIzaSyD5FVw6fP3ingbjTvUEzm-EYctX2ytfL2Y', true);
request.onload = function() {
if (request.status >= 200 && request.status < 400) {
// Success!
var data = JSON.parse(request.responseText);
} else {
// We reached our target server, but it returned an error
}
};
</script>
</head>
<body>
</body>
</html>
My problem is simple, I have requested the JSON YouTube v3 Data API, however, I'd like to display data requested from the link: https://www.googleapis.com/youtube/v3/channels?part=statistics&id=UCiWypivJjO5CIQPVVfFlVQA&key=AIzaSyD5FVw6fP3ingbjTvUEzm-EYctX2ytfL2Y Namely the subscriber count, how would I be able to use this GET request to load the number of subscribers into the innerHTML of an element? What do I have to do?
Using the object you get by parsing the JSON (data), get the subscriberCount value and place it into a div or other element using .innerHTML. Make sure you use request.send() to actually send your AJAX request.
<html>
<head>
<script>
var request = new XMLHttpRequest();
request.open('GET', 'https://www.googleapis.com/youtube/v3/channels?part=statistics&id=UCiWypivJjO5CIQPVVfFlVQA&key=AIzaSyD5FVw6fP3ingbjTvUEzm-EYctX2ytfL2Y', true);
request.onload = function() {
if (request.status >= 200 && request.status < 400) {
var data = JSON.parse(request.responseText);
document.getElementById("subs").innerHTML = data.items[0].statistics.subscriberCount;
} else {
// We reached our target server, but it returned an error
}
};
request.send();
</script>
</head>
<body>
<div id="subs"></div>
</body>
</html>
I was wondering what I was doing wrong with this code? I'm trying to get the response for PC players from the API to be set to a tag in the html, but this isn't working.
Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Battlefield 4 Tracker</title>
<link href="css/bootstrap/bootstrap.min.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="js/bootstrap/bootstrap.min.js"></script>
<script src="js/jquery-3.1.1.min.js"></script>
</head>
<body>
<div id="fullscreen">
<div class="fullscreen-content">
<div id="centered">
<h1>Battlefield 4 Stats Tracker</h1>
<input id="username" name="username" placeholder="PSN Username">
<button id="submit">Submit</button>
<p id="response">
Response goes here.
</p>
</div>
</div>
</div>
<script>
var request = new XMLHttpRequest();
var jsonResponse = request.open("GET", "http://api.bf4stats.com/api/onlinePlayers", false)
var obj = JSON.parse(jsonResponse);
document.getElementById("response").innerHTML = obj.pc[1].count + "";
</script>
</body>
</html>
Since you are using JQuery as suggested by the html you provided , you can use $.get method of it. This method is a simple wrapper to work with the xmlHTTP asynchronous calls. The success call back of this method is where you should populate the obj with response.
And obj.pc is also an object, so you should access it like obj.pc.count
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Battlefield 4 Tracker</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.5/css/bootstrap.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.5/js/bootstrap.min.js"></script>
</head>
<body>
<div id="fullscreen">
<div class="fullscreen-content">
<div id="centered">
<h1>Battlefield 4 Stats Tracker</h1>
<input id="username" name="username" placeholder="PSN Username">
<button id="submit">Submit</button>
<p id="response">
Response goes here.
</p>
</div>
</div>
</div>
<script>
var request = new XMLHttpRequest();
var obj = null;
var jsonResponse = $.get("http://api.bf4stats.com/api/onlinePlayers", function(response){
obj = response;
document.getElementById("response").innerHTML = obj.pc.count + "";
})
</script>
</body>
</html>
you forgot to send the XMLHttpRequest and what you get back is a object of object so you can call directly obj.pc.count. Try this one:
var json = new XMLHttpRequest();
json.open("GET", "http://api.bf4stats.com/api/onlinePlayers", false)
json.send(null)
var obj = JSON.parse(json.responseText);
document.getElementById("response").innerHTML = obj.pc.count;
You never sent the request. You're missing request.send(). You then listen for the load event, when you've gotten a response.
Here's an edited version of your code. I assumed that you want to loop through all the types of devices and count them.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="fullscreen">
<div class="fullscreen-content">
<div id="centered">
<h1>Battlefield 4 Stats Tracker</h1>
<input id="username" name="username" placeholder="PSN Username">
<button id="submit">Submit</button>
<p id="response">
Response goes here.
</p>
</div>
</div>
</div>
<script>
function reqListener () {
//THIS HAPPENS AFTER THE REQUEST HAS BEEN LOADED.
var obj = JSON.parse(this.responseText);
var counter = 0;
for(var k in obj) {
var o = obj[k];
counter += o.count;
}
document.getElementById("response").innerHTML = counter;
}
var request = new XMLHttpRequest();
request.addEventListener("load", reqListener);
request.open("GET", "http://api.bf4stats.com/api/onlinePlayers");
request.send();
</script>
</body>
</html>
You may want to consider other events such as a failed attempt to load the request, etc. Here's more info: https://developer.mozilla.org/en/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest
The request is never send send();
The correct way to do this is to handle it in the onreadystatechange event.
Try this (together with a proper check):
var xmlhttp = new XMLHttpRequest();
var url = "http://api.bf4stats.com/api/onlinePlayers";
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var obj = JSON.parse(this.responseText);
myFunction(obj);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(obj) {
document.getElementById("response").innerHTML = obj.pc.count;
}
or directly without extra function:
var xmlhttp = new XMLHttpRequest();
var url = "http://api.bf4stats.com/api/onlinePlayers";
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var obj = JSON.parse(this.responseText);
document.getElementById("response").innerHTML = obj.pc.count;
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
Demo
var xmlhttp = new XMLHttpRequest();
var url = "http://api.bf4stats.com/api/onlinePlayers";
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var obj = JSON.parse(this.responseText);
document.getElementById("response").innerHTML = obj.pc.count;
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
<div id="response"></div>
Try this one :-
<script>
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var obj = JSON.parse(this.responseText);
document.getElementById("response").innerHTML = obj.pc.count + "";
}
};
jsonResponse = request.open("GET", "http://api.bf4stats.com/api/onlinePlayers", true);
request.send();
</script>
I'm trying to do a simple http request to my server in a tizen web application for gear s2.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no"/>
<title>Wearable UI</title>
<link rel="stylesheet" href="../../lib/tau/wearable/theme/default/tau.min.css">
<link rel="stylesheet" href="../../css/style.css">
<!--<script type="text/javascript" src="toggle.js"></script>-->
<script type="text/javascript" >
function checkToggle(name){
//make box2 = box1 when checked
var checkbox = document.getElementById(name);
if (checkbox.checked == 1){
HTTPReq('http://secret.nl/WebServer/edit.php?name='+name+'&value=1');
console.log("set "+name+" ON");
}else{
HTTPReq('http://secret.nl/WebServer/edit.php?name='+name+'&value=0');
console.log("set "+name+" OFF");
}
}
function HTTPReq(theUrl){
console.log('httpReq');
var client = new XMLHttpRequest();
client.open('GET', theUrl);
client.send();
}
</script>
</head>
<body>
<div class="ui-page" data-enable-page-scroll="false">
<div class="ui-content">
<div class="ui-switch">
<div class="ui-switch-text">
Led001
</div>
<div class="ui-toggleswitch ui-toggleswitch-large">
<input type="checkbox" class="ui-switch-input" id="Led001" onclick="checkToggle('Led001')">
<div class="ui-switch-button"></div>
</div>
<div class="ui-switch-sub-text">
Bedroom Light
</div>
</div>
</div>
<script src="controls.js"></script>
</div>
</body>
<script type="text/javascript" src="../../lib/tau/wearable/js/tau.min.js"></script>
</html>
When i emulate this i get the error: Uncaught ReferenceError: checkToggle is not defined. How ever when i save the same file when i'm in web emulator mode and live editing. the code works....?
Can anyone explain this and tell me how to fix this. Thanks
Try:
document.getElementById("Led001").addEventListener("click", function(){
checkToggle("Led001")
})
And remove the onClick from your HTML
I'm not 100% sure how i fixed it but here is the code that works:
( function () {
var led001Button = document.getElementById("Led001"),
led002Button = document.getElementById("Led002");
function httpReq(theUrl){
var xmlhttp = null;
xmlhttp = new XMLHttpRequest();
// xmlhttp.onreadystatechange = function(){
// if (xmlhttp.readyState == xmlhttp.DONE){
// alert(xmlhttp.responseText);
// }
// else{
// alert(xmlhttp.statusText);
// }
// };
// xmlhttp.onerror = function(e){
// alert("onerror: " + xmlhttp.statusText);
// };
xmlhttp.open("GET", theUrl);
xmlhttp.send();
}
function checkToggle(name){
//make box2 = box1 when checked
var checkbox = document.getElementById(name);
if (checkbox.checked === true){
httpReq('http://secret.nl/WebServer/edit.php?name='+name+'&value=1');
// console.log("set "+name+" ON");
}else{
httpReq('http://secret.nl/WebServer/edit.php?name='+name+'&value=0');
// console.log("set "+name+" OFF");
}
}
if (led001Button) {
led001Button.addEventListener("change", function(){
checkToggle("Led001");
});
}
if (led002Button) {
console.log('test');
led002Button.addEventListener("change", function(){
checkToggle("Led002");
});
}
} () );
Thanks for all the replies they have all helped in some way.