HTTP request Readystate=4 and Status=400 - javascript

Im trying to make a POST call on a JSON based API, but im keep getting Status:400, bad request.
Here is my current code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>API TEST</title>
</head>
<body>
<button onclick="myFunction()">Test</button>
<div id="result"></div>
<script>
function myFunction() {
const xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
//alert(this.status);
alert(this.readyState);
if (this.readyState == 4 && this.status == 200) {
document.getElementById("result").innerHTML = this.responseText;
}
};
xhr.open("POST", URL);
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.send(JSON.stringify({username: "test", password: "test"}))
}
</script>
</body>
</html>

Related

Desperately trying to figure out how to display API info on HTML website [duplicate]

This question already has answers here:
How can I use setInterval and clearInterval?
(5 answers)
Closed 2 years ago.
Im trying to figure out a way to display crypto currency prices in real time on my website. So far Ive got a script that works at posting the current price but im having trouble using the setinterval to autorefresh the data. This is the code im using, and I think ive lost it at the setinterval part, please help!!!
<html>
<head>
<title>Test Site</title>
<style type="text/css">
#data {
text-align: center;
}
</style>
</head>
<body>
<div id="data" />
<script type="text/javascript">
var xmlhttp = new XMLHttpRequest();
var url = "https://api.coindesk.com/v1/bpi/currentprice.json";
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var json = JSON.parse(this.responseText);
parseJson(json);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
function parseJson(json) {
var usdValue = "Bitcoin Price: $" + json["bpi"]["USD"]["rate"];
document.getElementById("data").innerHTML =
usdValue;
}
setInterval(data, 3000);
</script>
</body>
</html>
I have updated your a bit please have a look it will work for you.
<html>
<head>
<title>Test Site</title>
<style type="text/css">
#data {
text-align: center;
}
</style>
</head>
<body>
<div id="data" />
<script type="text/javascript">
function loadBitCointPrice(){
var xmlhttp = new XMLHttpRequest();
var url = "https://api.coindesk.com/v1/bpi/currentprice.json";
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var json = JSON.parse(this.responseText);
parseJson(json);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
function parseJson(json) {
var usdValue = "Bitcoin Price: $" + json["bpi"]["USD"]["rate"];
document.getElementById("data").innerHTML = usdValue;
}
setInterval(function(){
loadBitCointPrice();
}, 3000);
</script>
</body>
</html>
You need to wrap the code that pulls the data in a function, and then use setInterval to call that function:
function pullData() {
var xmlhttp = new XMLHttpRequest();
var url = "https://api.coindesk.com/v1/bpi/currentprice.json";
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var json = JSON.parse(this.responseText);
parseJson(json);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
function parseJson(json) {
var usdValue = "Bitcoin Price: $" + json["bpi"]["USD"]["rate"];
document.getElementById("data").innerHTML =
usdValue;
console.log('Data updated at', new Date())
}
}
pullData() // Call it immediately the first time.
setInterval(pullData, 3000);
<html>
<head>
<title>Test Site</title>
<style type="text/css">
#data {
text-align: center;
}
</style>
</head>
<body>
<div id="data" />
</body>
</html>

Image link from JSON and apply it to HTML

I have created a weather app where I collect the data from an API and receive it as JSON file and it is working well, I just have one issue where I want to get the icon from the link in JSON and apply it to my HTML so I can see it myself.
Very basic HTML
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>weather api</title>
</head>
<body>
<div id="data-result"></div>
<div id="data-result-temp"></div>
<img id="data-result-icon" src="" alt=""> // I changed this a lot but did not really work.
</body>
<script src="app.js"></script>
</html>
and my JS code here
var url = "https://api.weatherapi.com/v1/current.json?key=1a4795e3c8a64d0ba4b92322202711&q=Istanbul";
const city = document.querySelector("#data-result");
const temp = document.querySelector("#data-result-temp");
const icon = document.querySelector("#data-result-icon");
const xhr = new XMLHttpRequest();
xhr.open("GET", url);
xhr.onload = function(data, status) {
const response = JSON.parse(xhr.response);
console.log(response);
if (xhr.status === 200) {
city.innerHTML = response.location.name;
temp.innerHTML = response.current.temp_c;
icon.innerHTML = response.current.condition.icon; // dont really know how to update
} else {
/** .. **/
}
}
xhr.onerror = function(err) {
console.log(`Network Error`, err);
};
xhr.send();
thanks!
Change the innerHTML attribute in the icon element into src attribute. Then you can display the icon. Check the below example
var url = "https://api.weatherapi.com/v1/current.json?key=1a4795e3c8a64d0ba4b92322202711&q=Istanbul";
const city = document.querySelector("#data-result");
const temp = document.querySelector("#data-result-temp");
const icon = document.querySelector("#data-result-icon");
const xhr = new XMLHttpRequest();
xhr.open("GET", url);
xhr.onload = function(data, status) {
const response = JSON.parse(xhr.response);
console.log(response);
if (xhr.status === 200) {
city.innerHTML = response.location.name;
temp.innerHTML = response.current.temp_c;
icon.src = "https:"+response.current.condition.icon;
} else {
/** .. **/
}
}
xhr.onerror = function(err) {
console.log(`Network Error`, err);
};
xhr.send();
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>weather api</title>
</head>
<body>
<div id="data-result"></div>
<div id="data-result-temp"></div>
<img id="data-result-icon" src="" alt="">
</body>
</html>
I think what you're looking for is:
icon.src = response.current.condition.icon;
So you're updating the src of the img rather than innerHTML.
Your current code will just return this:
<img id="data-result-icon" src="" alt="">//cdn.weatherapi.com/weather/64x64/day/113.png</img>

Javascript HttpRequest POST Access-Control-Allow-Origin error in web server

I tried to do HttpRequest by JavaScript. Because I had previously received an Access-Control-Allow-Origin error, I used Python's SimpleHTTPServer. But still I received the Access-Control-Allow-Origin error message. Is there another way? And is there anything wrong with javascript?
Here is my code.
The server needs :
basic Authorization
'Accept' : 'application/json'
'Content-Type' : 'application/json'
'Content-Length' : '*'
body written by JSON
And I used the Chrome browser.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
<script language="javascript" type="text/javascript">
function OnButtonClick() {
var clientId = "-my ID-";
var clientSecret = "-my password";
var authorizationBasic = window.btoa(clientId + ':' + clientSecret);
var request = new XMLHttpRequest();
request.open('POST', "-my url-");
request.setRequestHeader('Authorization', 'Basic ' + authorizationBasic);
request.setRequestHeader('Accept', 'application/json');
request.setRequestHeader('Content-Type', 'application/json');
request.send(JSON.stringify({email: "-my email-" }));
request.onreadystatechange = function () {
if (request.readyState === 4) {
alert(request.responseText);
}
};
}
</script>
</head>
<body>
<input id="Button1" type="button" value="送信" onclick="OnButtonClick();" />
<div id="output"></div>
</body>
</html>

Why The News Is Not Being Pulled [XML JS Query]

Here's my code.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>News Site</title>
<script>
window.document.onload = function () {
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "cdcatalog.xml", true);
xhttp.send();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var xmlDoc = this.responseXML;
console.log(xmlDoc);
document.getElementById("demo").innerHTML = xmlDoc.getElementsByTagName("TITLE")[0].childNodes[0].nodeValue + "<br/>" + xmlDoc.getElementsByTagName("PRICE")[0].childNodes[0].nodeValue;
} else {
document.getElementById("demo").innerHTML = "Can't show it.";
}
}
}
</script>
</head>
<body>
<div id="demo"></div>
</body>
</html>
I am a beginner in using Ajax and this is my first project. I checked with the format, even validated it with W3 Validator, and it doesn't seem to work.
Nothing is showing on the page. It's completely blank.
Can anyone point out my mistake please?
The document object does not have an onload property. Using that style of event handler assignment, you are looking for window.onload.

How to get google plus user image?

I tried to search on stackoverflow but all answer not work.
This is my code for get google plus user image, but not work.
How can i do that ?
<html>
<head>
<script src="https://apis.google.com/js/plusone.js"></script>
<script type="text/javascript">
function onSignin(e){
accessToken = e.access_token;
var xhr = new XMLHttpRequest();
xhr.open('GET', "https://www.googleapis.com/plus/v1/people/me/");
xhr.setRequestHeader('Authorization', 'Bearer ' + accessToken);
xhr.send();
xhr.onreadystatechange = function(){
if (this.readyState == 4){
var myProfile = JSON.parse(xhr.responseText);
alert(myProfile.image.url);
}
}
}
</script>
</head>
<body>
<g:plus action="connect" clientid="100009709084787102522" scope="https://www.googleapis.com/auth/plus.me" callback="onSignin">
</g:plus>
</body>
</html>

Categories