XMLHTTRequest mishandling the response status - javascript

let httpRequest = new XMLHttpRequest();
let FHIRserverAddress = '192.168.200.139:3012';
let url = 'http://' + FHIRserverAddress + '/model?starttime=' + startTime + '&endtime=' + endTime;
httpRequest.open('GET', url);
httpRequest.send();
httpRequest.onreadystatechange = function () {
if (httpRequest.readyState == 4 && httpRequest.status == 200) {
let currentModel = JSON.parse(httpRequest.responseText);
console.log('returning a valid model');
return callback(null, currentModel);
} else if (httpRequest.status != 200) {
console.log('get model call failed');
}
};
I can see the network call in Chrome dev tools and response status coming back is 200. The above call always get a 0 for the request status.
Anyone see what I am doing incorrectly?

Related

XMLHttpRequest.readyState & XMLHttpRequest.status final stage comparison

I have a script that I want to see if I can fix a comparison.
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];
if (data.type === 'exact' || data.type === 'aprox') {
var lyric = data.mus[0].text;
document.getElementById('lyric').innerHTML = lyric.replace(/\n/g, '<br />');
//debugging
console.log("Success Lyric found");
} else {
//debugging
console.log("Lyric not found");
}
} else {
//HERE if the condition is not met, it goes to another function
var page = new Page();
page.refreshLyric2(currentSong, currentArtist);
}
}
xhttp.open('GET', 'https://api.vagalume.com.br/search.php?apikey=' + API_KEY + '&art=' + currentArtist + '&mus=' + currentSong.toLowerCase(), true);
xhttp.send()
}
The code is simple, but what I want I cannot achieve.
This comparison to be true has to go through some previous states:
if (this.readyState === 4 && this.status === 200) {
XMLHttpRequest.readyState:
Value State Description
0 UNSENT Client has been created. open() not called yet.
1 OPENED open() has been called.
2 HEADERS_RECEIVED send() has been called, and headers and status are available.
3 LOADING Downloading; responseText holds partial data.
4 DONE The operation is complete.
XMLHttpRequest.status:
Before the request completes, the value of status is 0. Browsers also report a status of 0 in case of XMLHttpRequest errors.
UNSENT: 0
OPENED: 0
LOADING: 200
DONE: 200
What I want to do is if the final stage comparison of the states is not identical to 4 and 200 respectively then go to another function.
if (this.readyState === 4 && this.status === 200) {
//run this code
.....
} else {
//Go to another function
var page = new Page();
page.refreshLyric2(currentSong, currentArtist);
}
Is it possible to achieve this, or am I daydreaming?
If you want different actions in the final stage depending on the status, you need nested if statements. The first if detects the final stage, then you test the status.
this.refreshLyric = function(currentSong, currentArtist) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4) {
if (this.status == 200) {
var data = JSON.parse(this.responseText);
var openLyric = document.getElementsByClassName('lyrics')[0];
if (data.type === 'exact' || data.type === 'aprox') {
var lyric = data.mus[0].text;
document.getElementById('lyric').innerHTML = lyric.replace(/\n/g, '<br />');
//debugging
console.log("Success Lyric found");
} else {
//debugging
console.log("Lyric not found");
}
} else {
// go to another function
var page = new Page();
page.refreshLyric2(currentSong, currentArtist);
}
}
}
xhttp.open('GET', 'https://api.vagalume.com.br/search.php?apikey=' + API_KEY + '&art=' + currentArtist + '&mus=' + currentSong.toLowerCase(), true);
xhttp.send()
}

AJAX with promise

How to use promises (ES6) and .then method in order to this code will work?
getGif: function (searchingText, callback) {
var url = GIPHY_API_URL + '/v1/gifs/random?api_key=' + GIPHY_PUB_KEY + '&tag=' + searchingText;
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.onload = function () {
if (xhr.status === 200) {
var data = JSON.parse(xhr.responseText).data;
var gif = {
url: data.fixed_width_downsampled_url,
sourceUrl: data.url
};
callback(gif);
}
};
xhr.send();
},
Using Promise-Based XHR your code looks like:
getGif = function (searchingText) {
return new Promise((resolve, reject)=>{
var url = GIPHY_API_URL + '/v1/gifs/random?api_key=' + GIPHY_PUB_KEY + '&tag=' + searchingText;
var xhr = new XMLHttpRequest();
// Setup our listener to process compeleted requests
xhr.onreadystatechange = function () {
// Only run if the request is complete
if (xhr.readyState !== 4) return;
// Process the response
if (xhr.status >= 200 && xhr.status < 300) {
// If successful
var data = JSON.parse(xhr.responseText).data;
var gif = {
url: data.fixed_width_downsampled_url,
sourceUrl: data.url
};
resolve(gif);
} else {
// If failed
reject({
status: request.status,
statusText: request.statusText
});
}
};
xhr.open('GET', url);
xhr.send();
});
}
Need to invoke method depends on signature of function.
getGif(searchText).then((response)=>{
console.log(response);
}, (error)=> {
console.log(error);
})

ajax variable is undefined only for the first time in cordova

well, this is the problem: the variable day is undefined for the first time that setDates() function works. Then the next time it returns the value that the day variable should have the last time. The variable is defined until to reach in the setDates.php file. Then for some a reason it is undefined for the first time. Php file is nothing important, just a die(variable) function... Please help me.
function controlDates() {
//today = $('#chooseDate').val();
today= document.getElementById('chooseDate').value;
user = localStorage.Username;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
msg = this.responseText;
$('#comfirmMess').html(msg);
if (msg == 'available') {
$('#comfirmMess').html('');
$('#ChooseHour').show();
$('#checkButton').show();
setDates();
}
}
};
xhttp.open("GET", "https://ptyxiaki.000webhostapp.com/controlDates.php?today=" + today + '&user=' + user, true);
xhttp.send();
}
function setDates() {
if ($("input:radio[name='ProgramName']").is(":checked"))
trainName = $("input[name='ProgramName']:checked").val();
//today = $('#chooseDate').val();
var dsplit = today.split("/");
// day = new Date(dsplit[0], dsplit[1] - 1, dsplit[2]);
day = new Date(today);
var weekday = new Array(7);
weekday[0] = "Sunday";
weekday[1] = "Monday";
weekday[2] = "Tuesday";
weekday[3] = "Wednesday";
weekday[4] = "Thursday";
weekday[5] = "Friday";
weekday[6] = "Saturday";
day = weekday[day.getDay()];
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
msg = this.responseText;
mess=msg;
msgarr = msg.split(" ");
startTime = msgarr[0];
finnishTime = msgarr[1];
}
};
xhttp.open("GET", "https://ptyxiaki.000webhostapp.com/setDates.php?today=" + day, true);
xhttp.send();
var xhttl = new XMLHttpRequest();
xhttl.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
msg = this.responseText;
if (msg == 'Please enter a valid trainer') {
$('#comfirmMess').html(msg);
$('#ChooseHour').hide();
$('#checkButton').hide();
}
res = [];
DisHours = msg.split(" ");
for (i = 0; i < DisHours.length - 1; i++) {
res[i] = DisHours[i].split(":");
DisHours[i] = res[i][0];
}
}
}
xhttl.open("GET", "https://ptyxiaki.000webhostapp.com/showAvailDates.php?date=" + today + '&trainName=' + trainName, true);
xhttl.send();
}
The problem is that AJAX requests are asyncrononous; your call to setDates isn't waiting on your response to your call to controlDates. As such, the flow of your logic is like this:
You make a request to controlDates
The request has been successfully sent to controlDates
You make a request to setDates with an undefined day
The request has been successfully sent to setDates
At some random point, the response from the call to controlDates comes back (presumably successfully), and day gets defined.
As such, your first call to setDates is still waiting for day to be defined by the success response from the call to controlDates.
To get around this, you're looking to make use of a promise and say that 'something is going to come back from call A, wait until it gets here to make call B'.
To make use of a promise with a raw XMLHttpRequest, you can use the following (credited to SomeKittens):
function makeRequest (method, url) {
return new Promise(function (resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open(method, url);
xhr.onload = function () {
if (this.status >= 200 && this.status < 300) {
resolve(xhr.response);
} else {
reject({
status: this.status,
statusText: xhr.statusText
});
}
};
xhr.onerror = function () {
reject({
status: this.status,
statusText: xhr.statusText
});
};
xhr.send();
});
}
makeRequest('GET', 'http://example.com')
.then(function (datums) {
console.log(datums);
})
.catch(function (err) {
console.error('Augh, there was an error!', err.statusText);
});
Hope this helps! :)

Access ArangoDB data from browser

I want to get access to JSON data from arangoDB, which I installed locally from the browser (own interface). I get the "401 Unauthorized" request, how can I fix this?
function getRequest(){
alert("test")
var request = new XMLHttpRequest();
request.open("GET","http://root#localhost:8529/_db/_system/_api/document/FC_ACTUAL_SALES/945545",true);
request.setRequestHeader('Content-Type','application/json');
request.setRequestHeader('Access-Control-Allow-Credential','true');
request.responseType = 'json';
request.addEventListener('load', function(event) {
if (request.status >= 200 && request.status < 300) {
console.log(request.responseText);
} else {
console.warn(request.statusText, request.responseText);
}
});
request.send();
}
You are not using basic authentication.
Change your function to this:
function getRequest(){
var request = new XMLHttpRequest();
var user = "root";
var pass = "";
request.open("GET","http://root#localhost:8529/_db/_system/_api/document/FC_ACTUAL_SALES/945545",true);
//Use Basic authentication
request.setRequestHeader("Authorization", "Basic " + btoa(user + ":" + pass));
request.setRequestHeader('Content-Type','application/json');
request.setRequestHeader('Access-Control-Allow-Credential','true');
//request.responseType = 'json'; <--Notice it was removed
request.addEventListener('load', function(event) {
if (request.status >= 200 && request.status < 300) {
console.log(request.responseText);
} else {
console.warn(request.statusText, request.responseText);
}
});
request.send();
}

JavaScript ajax call inside another ajax call

I’ve got a call that brings up an url id for a recipe, that I’m trying feed into another call to return additional recipe data, but I think the scope is incorrect somewhere.
I’m getting
Cannot read property 'id' of undefined at XMLHttpRequest.http.onreadystatechange
in Chrome.
function searchFood() {
var http = new XMLHttpRequest();
var foodID = 'a1e1c125';
var foodApiKey = 'c84a720e4f1750b59ce036329fccdc00';
var foodMethod = 'GET';
var url = 'http://api.yummly.com/v1/api/recipes?_app_id=' + foodID + '&_app_key=' + foodApiKey + '&q=scandinavian';
http.open(foodMethod, url);
http.onreadystatechange = function() {
if (http.readyState == XMLHttpRequest.DONE && http.status === 200) {
var foodData = JSON.parse(http.responseText);
var foodName = foodData.matches[0].recipeName;
console.log(foodData);
for (var i = 0; foodData.matches.length; i++) {
var recipeId = foodData.matches[i].id;
console.log(recipeId);
}
function getRecipe() {
var http = new XMLHttpRequest();
var foodID = 'a1e1c125';
var foodApiKey = 'c84a720e4f1750b59ce036329fccdc00';
var foodMethod = 'GET';
var url = 'http://api.yummly.com/v1/api/recipe/' + recipeId + '?_app_id=' + foodID + '&_app_key=' + foodApiKey;
http.open(foodMethod, url);
http.onreadystatechange = function() {
if (http.readyState == XMLHttpRequest.DONE && http.status === 200) {
var data = JSON.parse(http.responseText);
console.log(data);
} else if (http.readyState === XMLHttpRequest.DONE) {
alert("something went wrong");
}
};
http.send();
};
} else if (http.readyState === XMLHttpRequest.DONE) {
alert('Something went wrong')
}
};
http.send();
};
Any tips would be appreciated, thanks
Your truthy check is always true
for (var i = 0; foodData.matches.length; i++)
you are missing i<

Categories