API not responding - javascript

The app that I'm working on does not respond with the API address. I only get the ajax responding, but not the weather api that I'm trying to call.
I've tried everything that I could think of with my current knowledge.
let search = document.getElementById("search-bar");
let temp = document.getElementById("temperature");
let input = document.getElementById("input");
let city = document.getElementById("city");
const key = "";
input.addEventListener("keyup", enter);
function enter(event) {
if (event.key==="Enter") {
details();
}
}
function details() {
if (searchInput.value === ""){
} else {
let searchLink = "https://api.openweathermap.org/data/2.5/weather?q={}" + searchInput.value + "&appid=" + key;
httpRequestAsync(searchLink, talk)
}
}
function talk(talking){
let jsonObject = JSON.parse(talking);
city.innerHTML = jsonOject.name;
temp.innerHTML = parseInt(parseInt(jsonObject.main.temp - 273) + "°");
}
function httpRequestAsync(url,callback){
var httpRequest=new XMLHttpRequest();
httpRequest.onreadystatechange = () => {
if (httpRequest.readyState == 4 && httpRequest.status == 200)
callback(httpRequest.responseText);
}
request.open("GET", url, true); // true for asynchronous
request.send();
}
The expected outcome should be the weather api being called and displayed information in the console.

Try replacing last function with this:
function httpRequestAsync(url,callback){
var httpRequest=new XMLHttpRequest();
httpRequest.onreadystatechange = () => {
if (httpRequest.readyState == 4 && httpRequest.status == 200)
callback(httpRequest.responseText);
}
httpRequest.open("GET", url, true); // true for asynchronous
httpRequest.send();
}
I just corrected variable naming

Related

JavaScript helps with conditional syntax

I have a function that calls an API (let's call it API-1) to get the song lyrics.
Since this API sometimes can't find a song in its database, I want to call another API (let's call it API-2) to do the same search.
I need to integrate the code of both APIs inside the function, when the first one doesn't get data.
I tell you some very important information:
In API-1 I must force the data to be fetched as XML and the responseType must be 'document'.
API-2 does not require any of the above conditions, the data is parced as JSON and the responseType it supports is 'text', but does not require it to be set, with 'document' it DOES NOT work, it gives error.
Now I will share the function code for API-1 and then I will share the same function code for API-2.
They both work perfect if I test them independently.
The help I am asking for is to integrate API-2 when API-1 does not fetch data.
Code using API-1
this.refreshLyric = function (currentSong, currentArtist) {
var xhr = new XMLHttpRequest;
xhr.open('GET', proxy_URL + api_URL + 'apiv1.asmx/SearchLyricDirect?artist=' + currentArtistE + '&song=' + ucwords(currentSongE), true);
// ONLY FOR THIS XMLHttpRequest responseType must be empty string or 'document'
xhr.responseType = 'document';
// ONLY FOR THIS XMLHttpRequest force the response to be parsed as XML
xhr.overrideMimeType('text/xml');
xhr.onload = function () {
if (xhr.readyState === xhr.DONE && xhr.status === 200) {
var openLyric = document.getElementsByClassName('lyrics')[0];
var lyric = xhr.responseXML.getElementsByTagName('Lyric')[0].innerHTML;
//check if any data was obtained
if (lyric != '') {
document.getElementById('lyric').innerHTML = lyric.replace(/\n/g, '<br />');
openLyric.style.opacity = "1";
openLyric.setAttribute('data-toggle', 'modal');
} else { /////// HERE INTEGRATE API-2 //////
openLyric.style.opacity = "0.3";
openLyric.removeAttribute('data-toggle');
var modalLyric = document.getElementById('modalLyrics');
modalLyric.style.display = "none";
modalLyric.setAttribute('aria-hidden', 'true');
(document.getElementsByClassName('modal-backdrop')[0]) ? document.getElementsByClassName('modal-backdrop')[0].remove(): '';
}
} else {
document.getElementsByClassName('lyrics')[0].style.opacity = "0.3";
document.getElementsByClassName('lyrics')[0].removeAttribute('data-toggle');
}
};
xhr.send();
}
The same code using API-2
this.refreshLyric = function (currentSong, currentArtist) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState === 4 && this.status === 200) {
var data = JSON.parse(this.responseText);
var openLyric = document.getElementsByClassName('lyrics')[0];
var lyric = data.mus[0].text;
//check if any data was obtained
if (lyric != '') {
document.getElementById('lyric').innerHTML = lyric.replace(/\n/g, '<br />');
openLyric.style.opacity = "1";
openLyric.setAttribute('data-toggle', 'modal');
} else {
openLyric.style.opacity = "0.3";
openLyric.removeAttribute('data-toggle');
var modalLyric = document.getElementById('modalLyrics');
modalLyric.style.display = "none";
modalLyric.setAttribute('aria-hidden', 'true');
(document.getElementsByClassName('modal-backdrop')[0]) ? document.getElementsByClassName('modal-backdrop')[0].remove(): '';
}
} else {
document.getElementsByClassName('lyrics')[0].style.opacity = "0.3";
document.getElementsByClassName('lyrics')[0].removeAttribute('data-toggle');
}
}
xhttp.open('GET', 'https://api.vagalume.com.br/search.php?apikey=' + API_KEY + '&art=' + currentArtist + '&mus=' + currentSong.toLowerCase(), true);
xhttp.send()
}
The shared codes are of the SAME function (this.refreshLyric), what has to be integrated is only the XMLHttpRequest API.
In the ELSE of line 23 of API-1 I must integrate the code of API-2.
I have already tried it in several ways but I am presented with syntax problems with the IF - ELSE conditionals and errors with the API-2 which is getting the responseType and the MimeType of API-1.
EDIT
FIXED: When API-1 cannot find the lyric, I have created a new function that calls API-2. refreshLyric2(currentSong, currentArtist); :)
this.refreshLyric = function (currentSong, currentArtist) {
var xhr = new XMLHttpRequest;
xhr.open('GET', proxy_URL + api_URL + 'apiv1.asmx/SearchLyricDirect?artist=' + currentArtistE + '&song=' + ucwords(currentSongE), true);
// ONLY FOR THIS XMLHttpRequest responseType must be empty string or 'document'
xhr.responseType = 'document';
// ONLY FOR THIS XMLHttpRequest force the response to be parsed as XML
xhr.overrideMimeType('text/xml');
xhr.onload = function () {
if (xhr.readyState === xhr.DONE && xhr.status === 200) {
var openLyric = document.getElementsByClassName('lyrics')[0];
var lyric = xhr.responseXML.getElementsByTagName('Lyric')[0].innerHTML;
//check if any data was obtained
if (lyric != '') {
document.getElementById('lyric').innerHTML = lyric.replace(/\n/g, '<br />');
openLyric.style.opacity = "1";
openLyric.setAttribute('data-toggle', 'modal');
} else {
//If lyric was not obtained, we call API-2
refreshLyric2(currentSong, currentArtist);
}
} else {
document.getElementsByClassName('lyrics')[0].style.opacity = "0.3";
document.getElementsByClassName('lyrics')[0].removeAttribute('data-toggle');
}
};
xhr.send();
}
refreshLyric2 = function (currentSong, currentArtist) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState === 4 && this.status === 200) {
var data = JSON.parse(this.responseText);
var openLyric = document.getElementsByClassName('lyrics')[0];
var lyric = data.mus[0].text;
//check if any data was obtained
if (lyric != '') {
document.getElementById('lyric').innerHTML = lyric.replace(/\n/g, '<br />');
openLyric.style.opacity = "1";
openLyric.setAttribute('data-toggle', 'modal');
} else {
openLyric.style.opacity = "0.3";
openLyric.removeAttribute('data-toggle');
var modalLyric = document.getElementById('modalLyrics');
modalLyric.style.display = "none";
modalLyric.setAttribute('aria-hidden', 'true');
(document.getElementsByClassName('modal-backdrop')[0]) ? document.getElementsByClassName('modal-backdrop')[0].remove(): '';
}
} else {
document.getElementsByClassName('lyrics')[0].style.opacity = "0.3";
document.getElementsByClassName('lyrics')[0].removeAttribute('data-toggle');
}
}
xhttp.open('GET', 'https://api.vagalume.com.br/search.php?apikey=' + API_KEY + '&art=' + currentArtist + '&mus=' + currentSong.toLowerCase(), true);
xhttp.send()
}

Ajax doesn't fire onreadystatechange

I know the URL is working as intended as i logged that to the console and it is fine. However I can't get "Good News" to log to the console when readyState == 4 and status == 200. I tried removing readState and it still wouldn't log. I tried logging the status and It would only fire once with a value of 0. This is the first time I am working with Ajax so any help is appreciated.
function setupRequest(){
var bttn = document.querySelector('#send');
bttn.addEventListener('click', sendData)
}
setupRequest();
function sendData () {
console.log('ran')
var url = 'localhost/bev/drinks.php';
var data = document.getElementById('input').value;
url += '?' + 'alcohol=' + data;
console.log(url)
var request = new XMLHttpRequest();
request.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
console.log('good news')
console.log(this.responseText)
} else {
console.log(this.status)
}
}
request.open('GET', url, true);
request.send;
console.log('sent')
}
You need to actually call send(). You aren't doing anything whenever you say request.send;
function setupRequest() {
var bttn = document.querySelector('#send');
bttn.addEventListener('click', sendData)
}
setupRequest();
function sendData() {
console.log('ran')
var url = 'https://jsonplaceholder.typicode.com/posts';
var data = document.getElementById('input').value;
//url += '?' + 'alcohol=' + data;
console.log(url)
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log('good news')
console.log(this.responseText)
} else {
console.log(this.status)
}
}
request.open('GET', url, true);
// You wrote (without parentheses):
///////////////////
// request.send; //
///////////////////
// You need to write
request.send();
console.log('sent')
}
<button type="button" id="send">Btn</button>
<input type="text" id="input">

JavaScript: Variables not working outside function?

Why cannot I call variables that I have defined inside a function? This is my code...
var username;
var rank;
var steamid;
var avatar;
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
if (this.responseText == "null") {
} else {
var infoArr = JSON.parse(this.responseText);
var username = infoArr.username;
var rank = infoArr.rank;
var steamid = infoArr.steamid;
var avatar = infoArr.avatar;
testIt();
}
}
};
xhr.open("GET", "../getInfo.php", true);
xhr.send();
function testIt() {
alert(username);
}
Function testIt() is returning: undefined
What my code does is to get info from a JSON encoded page and make variables.
If you want to use the variables outside of the function, they need to be defined outside of the function.
var username, rank, steamid, avatar, infoArr, username, rank, steamid, avatar;
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
if (this.responseText == "null") {
} else {
infoArr = JSON.parse(this.responseText);
username = infoArr.username;
rank = infoArr.rank;
steamid = infoArr.steamid;
avatar = infoArr.avatar;
testIt();
}
}
};
xhr.open("GET", "../getInfo.php", true);
xhr.send();
function testIt() {
alert(username);
}

Loop Calling Function in Native Ajax

Here's my native ajax code:
function script_grabbed(str) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("numvalue").value = xmlhttp.responseText;
var result = document.getElementById("numvalue").value;
if (typeof result !== 'undefined'){
alert('Data Found:' + result);
//start: new request data for #valdata
xmlhttp.open("POST", "inc.php?q="+str, true);
document.getElementById("valdata").value = xmlhttp.responseText;
xmlhttp.send(null);
var dataval = document.getElementById("valdata").value;
if (typeof dataval !== 'undefined'){
alert('Data Bound:' + dataval);
//continue to call maps
script_dkill()
}
//end: new request data for #valdata
}
}
}
xmlhttp.open("POST", "inc_num.php?q="+str, true);
xmlhttp.send(null);
}
From the code, let me explain that:
I want to get data/value from result and dataval. After I get the data, I execute script_dkill() function.
However, It creates loop and never get to script_dkill.
So, the question is: How to get to script_dkill and execute it?
For example:
The script_dkill() has content as follow:
function script_dkill(){
alert('Hallo, you call me!');
}
Any help, please...
You need to use a different XMLHttpRequest object for the second request, since you are using the same object it will call the same onreadystatechange event again and again
function script_grabbed(str) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("numvalue").value = xmlhttp.responseText;
var result = document.getElementById("numvalue").value;
if (typeof result !== 'undefined') {
alert('Data Found:' + result);
//start: new request data for #valdata
var xmlhttp2 = new XMLHttpRequest();
xmlhttp2.onreadystatechange = function() {
if (xmlhttp2.readyState == 4 && xmlhttp2.status == 200) {
document.getElementById("valdata").value = xmlhttp2.responseText;
var dataval = document.getElementById("valdata").value;
if (typeof dataval !== 'undefined') {
alert('Data Bound:' + dataval);
//continue to call maps
script_dkill()
}
}
}
xmlhttp2.open("POST", "inc.php?q=" + str, true);
xmlhttp2.send(null);
//end: new request data for #valdata
}
}
}
xmlhttp.open("POST", "inc_num.php?q=" + str, true);
xmlhttp.send(null);
}

Return value from AJAX onreadystatechange Event

I have some problems with returning a value from a function into a variable. It is apparently "undefined". This apparently happens due to the asynchronity of JavaScript. But in my case I don't know how to circumvent it with "callbacks" or "promises". Please see code below. I would like to return the exchange rate saved in "value" back to "rate" and use it further in my code. Any ideas?
var rate = rateCalc();
var currency = "EUR";
function rateCalc(){
var value;
if (currency != "EUR") {
var xmlhttp = new XMLHttpRequest();
var rateURL = "http://query.yahooapis.com/v1/public/yql?q=select%20rate%2Cname%20from%20csv%20where%20url%3D'http%3A%2F%2Fdownload.finance.yahoo.com%2Fd%2Fquotes%3Fs%3D"+"EUR"+"HKD"+"%253DX%26f%3Dl1n'%20and%20columns%3D'rate%2Cname'&format=json";
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var json = JSON.parse(xmlhttp.responseText);
value = json.query.results.row.rate;
alert("At this position the value is defined: "+ value);
return value;
}
}
xmlhttp.open("GET", rateURL, true);
xmlhttp.send();
}
else {
value = 1;
return value;
}
}
alert("The return statement somehow didn't work: "+ rate);
I'm a newbie, by the way. So sorry, if this question has already been asked like a million times before.
Thanks
René
You can't return anything from a async function in JS. So create a new function and use it as a callback function. See the below example.
var rate = rateCalc();
var currency = "EUR";
function rateCalc(){
var value;
if (currency != "EUR") {
var xmlhttp = new XMLHttpRequest();
var rateURL = "http://query.yahooapis.com/v1/public/yql?q=select%20rate%2Cname%20from%20csv%20where%20url%3D'http%3A%2F%2Fdownload.finance.yahoo.com%2Fd%2Fquotes%3Fs%3D"+"EUR"+"HKD"+"%253DX%26f%3Dl1n'%20and%20columns%3D'rate%2Cname'&format=json";
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var json = JSON.parse(xmlhttp.responseText);
value = json.query.results.row.rate;
alert("At this position the value is defined: "+ value);
valueCallBack(value); //Callback function
}
}
xmlhttp.open("GET", rateURL, true);
xmlhttp.send();
}
else {
value = 1;
return value;
}
}
function valueCallBack(value){
console.log("value is " + value);
}
Update : You can use the Promise API introduced in the ES6 or use JQUERY deferred objects.
xmlhttp.send() shouldn't be empty. Try this. I hope it will do the job!
xmlhttp.send(null);
You can send the response value to another function so when you have a value it will be displayed without it being undefined.
Try this:
rateCalc();
var currency = "EUR";
function rateCalc() {
var value;
if (currency != "EUR") {
var xmlhttp = new XMLHttpRequest();
var rateURL = "http://query.yahooapis.com/v1/public/yql?q=select%20rate%2Cname%20from%20csv%20where%20url%3D'http%3A%2F%2Fdownload.finance.yahoo.com%2Fd%2Fquotes%3Fs%3D"+"EUR"+"HKD"+"%253DX%26f%3Dl1n'%20and%20columns%3D'rate%2Cname'&format=json";
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var json = JSON.parse(xmlhttp.responseText);
value = json.query.results.row.rate;
show(value);
}
};
xmlhttp.open("GET", rateURL, true);
xmlhttp.send();
} else {
value = 1;
show(value);
}
}
function show(rate) {
alert("Value: "+ rate);
}
So this is how I changed the code now. The call back function is used for all further calculations with the called back value. Thanks again to #Jijo John and #nx0side.
var currency = "HKD";
var value;
if (currency != "EUR")
{
var xmlhttp = new XMLHttpRequest();
var rateURL = "http://query.yahooapis.com/v1/public/yql?q=select%20rate%2Cname%20from%20csv%20where%20url%3D'http%3A%2F%2Fdownload.finance.yahoo.com%2Fd%2Fquotes%3Fs%3D"+"EUR"+"HKD"+"%253DX%26f%3Dl1n'%20and%20columns%3D'rate%2Cname'&format=json";
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
var json = JSON.parse(xmlhttp.responseText);
value = json.query.results.row.rate;
valueCallBack(value); //Callback function
}
}
xmlhttp.open("GET", rateURL, true);
xmlhttp.send();
}
else
{
valueCallBack(1);
}
//in this function all further calculations with "value" need to take place.
function valueCallBack(value)
{
//example
var result = 70000/value;
console.log("Result is " + result);
}

Categories

Resources