How to delay a method until another is finished first , javascript? - javascript

I'm currently working on a project for school using a pokemon api that will display the information needed to evolve the pokemon (please note that I'm completely new to javascript and HTML).
Link :http://pokeapi.co/docsv2/
The website will ask the user for a name and that name will be used to get a url for the main information that I'm looking for.
For example : if someone enters in pikachu, the program will request the object for pikachu which contains the url for pikachu's evolution chain and that url is the one that will provide the main information for the website.
Currently the code looks like this:
var pokemon = new XMLHttpRequest();
var name = prompt("Whats the name of the pokemon you have?").toLowerCase();
var url = "http://pokeapi.co/api/v2/pokemon-species/" + name;
var url2;
pokemon.onreadystatechange = function(){
if(pokemon.readyState == 4 && pokemon.status == 200){
var myArr = JSON.parse(pokemon.responseText);
var url2 = myArr.evolution_chain;
}
}
pokemon2.onreadystatechange = function() {
if (pokemon2.readyState == 4 && pokemon2.status == 200) {
var myArr2 = JSON.parse(pokemon2.responseText);
console.log(myArr2.chain.species.name);
}
}
var pokemon2 = new XMLHttpRequest();
pokemon2.open("GET", url2, true).done(onreadystatechange);
pokemon2.send();
pokemon.open("GET", url, true);
pokemon.send();
However the program doesn't work due to the fact that the getting is occurring at the same time and pokemon2 should only be called after pokemon is finished because it's getting the actual url for pokemon2.
Does anyone know how to be able to accomplish this?
Many thanks! :).

You can call pokemon2 once pokemon finishes:
pokemon.onreadystatechange = function(){
if(pokemon.readyState == 4 && pokemon.status == 200){
var myArr = JSON.parse(pokemon.responseText);
var url2 = myArr.evolution_chain;
// Call pokemon2 here
var pokemon2 = new XMLHttpRequest();
pokemon2.open("GET", url2, true);
pokemon2.send();
}
}

Related

API response is giving two responses when only one is requested

I'm making an API request in JS that is working, but it keeps giving two responses when I'm only expecting one. Here's the code:
CallCoinGecko();
function CallCoinGecko() {
var cgrequest = new XMLHttpRequest();
var url1 = 'https://api.coingecko.com/api/v3/simple/price?ids=';
var id = 'ethereum';
var url2 = '&vs_currencies=USD&include_market_cap=true&include_24hr_vol=true&include_24hr_change=true';
cgrequest.open("GET", url1 + id + url2, true);
cgrequest.send();
cgrequest.onreadystatechange = function () {
if (cgrequest.status == 200) {
var cgresponse = cgrequest.responseText;
var cgobj = JSON.parse(cgresponse);
console.log(cgobj);
var cgprice = (cgobj[id]['usd']);
console.log(cgprice);
}}}
Here is a console image that shows two responses:
image
Any thoughts on this are appreciated thanks
Try verifying the value of readyState after the request. Example:
if (cgrequest.status === 200 && cgrequest.readyState === 4)
The problem is that, as mentioned, the readyState can have multiple values - therefore everytime it changes, your code to print the response text will trigger. I'm sure if you looked in the network tab, the API request isn't being carried out two times, only your response text is being printed two times. Checking if it is 4 confirms that the request is done - and should only be carried out once.
My hunch that the API isn't being called two times is due to the fact that the data is exactly the same on each console.log().
Good luck :)
You should compare the readyState value in your if statement as well.
function CallCoinGecko() {
var cgrequest = new XMLHttpRequest();
var url1 = 'https://api.coingecko.com/api/v3/simple/price?ids=';
var id = 'ethereum';
var url2 = '&vs_currencies=USD&include_market_cap=true&include_24hr_vol=true&include_24hr_change=true';
cgrequest.open("GET", url1 + id + url2, true);
cgrequest.onreadystatechange = function(res){
if (cgrequest.status === 200 && cgrequest.readyState === XMLHttpRequest.DONE) {
var cgresponse = cgrequest.responseText;
var cgobj = JSON.parse(cgresponse);
console.log(cgrequest.status, cgobj);
var cgprice = (cgobj[id]['usd']);
console.log(cgrequest.status, cgprice);
}
};
cgrequest.send();
}

How to get "file" parameter of http request in javascript?

I'm trying to program a java script script that based on whether a user logs in properly or not will redirect them to a separate PHP script. The issue is that I can't seem to figure out how to get the file parameter of the request so that I can see if the request I'm looking for is there. How do I get the file parameter of a request in java script?
Sorry for misconceptions, what i mean by the file attribute is what is under the "file" section for each request in the following.
example
So if under the file tab of the packet, it set a certain file, how would i differentiate?
It's not clear what you're asking.
The part " so that I can see if the request I'm looking for is there" tells me, you want to debug your website, or at least, that's my interpretation of it.
If you use Chrome or Firefox Developer Edition, you can press F12 (or CTRL + SHIFT + J) to open the developer console.
Change to the tab "Network, and you'll see all the XMLHTTPRequests.
Click on a specific request, and you'll see its details.
A basic XmlHttpReuqest goes like this:
function reqListener () {
console.log(this.responseText);
}
var oReq = new XMLHttpRequest();
oReq.addEventListener("load", reqListener);
oReq.open("GET", "http://www.example.org/example.txt");
oReq.send();
And you get the result of your request in the callback function reqListener.
See also https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest
If you want to get the request handler's URL, that goes like this:
function reqListener (e) {
//console.log(this.responseText);
console.log(e);
console.log(e.currentTarget.responseURL);
}
var oReq = new XMLHttpRequest();
oReq.addEventListener("load", reqListener);
oReq.open("GET", "https://stackoverflow.com/questions/58407228");
oReq.send();
And if you want to get a parameter called "file" inside an url, this goes like
function getUrlVars(urlHref)
{
var vars = [], hash;
var hashes = urlHref.slice(urlHref.indexOf('?') + 1).split('&');
var i;
for (i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(decodeURIComponent(hash[0]));
vars[decodeURIComponent(hash[0])] = decodeURIComponent(hash[1]);
} // Next i
return vars;
} // End Function getUrlVars
var dictParameters = getUrlVars("http://www.example.com/handler?file=bla.bin");
if (dictParameters.contains("file"))
{
console.log(dictParameters["file"]);
}
As for XMLHTTPRequest, it doesn't have a property called file.
Also, this is 2019, you should be using the FETCH-API with async and await, not the XMLHttpRequest-API, which doesn't use promises.
Here's a getting started overview.
Edit:
Ah, I see:
If you have a url, such as
var url = "http://www6.scratch99.com/web-development/javascript/test.js?abc=def";
you do
var url = "http://www6.scratch99.com";
var urlParts = url.replace('http://','').replace('https://','').split(/[/?#]/);
var domain = urlParts[0];
to get the domain part. Then you subtract the domain (+protocol), and end it at ? or #:
Full code:
var url = "http://www6.scratch99.com/web-development/javascript/test.js?abc=def";
// var url = "http://www6.scratch99.com";
// var url = "http://www6.scratch99.com?test=123";
var protocol = url.substr(0, url.indexOf(":") + 3)
var urlParts = url.substr(protocol.length).split(/[/?#]/);
var domain = urlParts[0];
var fileParts = url.substr(protocol.length + domain.length);
var file = fileParts.split(/[?#]/)[0];
and if you want the filename only:
var pathParts = file.split('/');
var fileOnly = pathParts[pathParts.length-1];

Accessing Elements and Attributes from a Live Feed XML

I am trying to access the time until the next bus arrives for a Live Feed bus transit system in Asheville NC at the given bus stop but I keep returning two console errors:
"time is not defined"
and
"Cannot read property of geElementsbyTagName of undefined"
You can use "470" as an exam stopID to see the XML file.
I have made sure the right stop ID is being added although I am not sure I am adding the ID correctly onto the URL.
If the element is nested in another, is that an issue?
var feedURL = "http://webservices.nextbus.com/service/publicXMLFeed?command=predictions&a=art&stopId="+stopID;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function(){
if(this.readyState == 4 && this.status == 200){
attribute(this);
}
};
xhttp.open("GET", feedURL, true);
xhttp.send();
function attribute(feedURL){
var y;
var xmlDoc = xml.responseXML;
var time = "";
y = xmlDoc.getElementsbyTagName('prediction');
time = x.getAttribute('minutes');
}
console.log(time);
I am expecting the number of minutes given until the bus arrives at a given stop.
You are trying to log the value of variable time outside of the function you've defined it in. You could change your code to this and that should work:
function attribute(feedURL){
var y;
var xmlDoc = xml.responseXML;
var time = "";
y = xmlDoc.getElementsbyTagName('prediction');
time = x.getAttribute('minutes');
console.log(time);
}

JavaScript - Push objects within object to global array

ORIGINAL QUESTION
I'm trying to write a function in JavaScript that allows for articles from another source to be loaded on another page using an XMLHTTPRequest.
Each article is a JavaScript object containing the link, image, summary etc.
Each request will retrieve 5 articles, but I only want to show 4 articles on each button click. Because of this, I want to push the articles (objects) to a global array.
Since I'm fairly new at using XMLHTTPRequests, I can't find how to do this.
Everything works except for:
var i;
for (i = 0; i < newArticles.length; i++) {
articles.push(newArticles[i]);
}
newArticles is an object containing the 5 articles (objects) which I'm trying to push to the global array titled articles.
My code:
var articles = [];
document.getElementById("fc-blog-button-loadmore").addEventListener("click", receiveNewArticles);
function receiveNewArticles() {
var http = new XMLHttpRequest();
var url = "thelinktothepagewith5newarticles.json";
http.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200) {
var newObj = JSON.parse(http.responseText);
var newArticles = (newObj.blog.articles);
console.log(newObj);
console.log(newArticles);
var i;
for (i = 0; i < newArticles.length; i++) {
articles.push(newArticles[i]);
}
console.log(articles);
}
}
http.open("GET", url, true);
http.send();
}
SOLVED
After the helpful comments my code currently looks like this:
var articles = [];
document.getElementById("fc-blog-button-loadmore").addEventListener("click", receiveNewArticles);
function receiveNewArticles() {
var http = new XMLHttpRequest();
var url = "http://freshcotton-dev.webshopapp.com/nl/blogs/blog/page2.html?format=json";
http.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200) {
var newObj = JSON.parse(http.responseText);
var newArticles = (newObj.blog.articles);
console.log(newObj);
console.log(newArticles);
articles.push(...Object.values(newArticles))
console.log(articles);
}
}
http.open("GET", url, true);
http.send();
}
Problem has been solved!
You can solve the issue simply by using [spread operator][1] ...
articles.push(...Object.values(newArticles));
[1]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax

Javascript / REST / Activiti - What am I doing wrong in my XMLHttpRequest?

I'm trying to learn how to use the Activiti REST api and I'm have trouble getting back data. I'm not very familiar with using rest apis so I may be making a stupid mistake, but as it stands I can't figure it out.
I've had success getting back JSON using the Advanced REST Client for Chrome but I can't seem to implement it with Javascript.
I'd really appreciate it if someone could point me in the right direction. Links to relevant tutorials and videos would also be much appreciated.
window.onload = function get_json() {
var hr = new XMLHttpRequest();
var url = "http://kermit:kermit#localhost:8080/activiti-rest/service/repository/process-definitions";
var result = document.getElementById("result");
hr.open("GET", url, true);
hr.setRequestHeader("Content-type", "application/json", true);
hr.onreadystatechange = function() {
if(hr.readystate == 4 && hr.status == 200) {
var data = JSON.parse(hr.responseText);
result.innerHTML = data;
}
}
hr.send();
}
Two problems. The main is that it's readyState, not readystate. So it should be
hr.onreadystatechange = function() {
if (hr.readyState == 4 && hr.status == 200) {
var data = JSON.parse(hr.responseText);
result.innerHTML = data;
}
}
The second problem is that you probably don't want to just assign object to innerHTML because it will be meaningless [object Object]. But rendering of the data is beyond this question.

Categories

Resources