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

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.

Related

Unable to get the same results with 2 pieces of somewhat similar XMLHttpRequest

Hope you are able to help or just help me understand why I have 2 almost similar codeblocks where one does not do what I expect.
I am trying to make some API calls where I populate a variable with the data that is pulled from the API call. In the first there is no problem at all, but the second I can't populate the variable.
I have tried googling the problem and it seems to be because of the asynchronous nature of XmlHttprequests. But again, I do not get why one solutions works and another don't.
The solution that work:
// Get JSON and convert it to an object
var obj;
const Http = new XMLHttpRequest();
const url = "https://type.fit/api/quotes";
Http.open("GET", url);
Http.send();
Http.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
obj = JSON.parse(Http.responseText);
}
};
In this solution I am able to get the data and populate the variable obj and use it globally.
link to the solution: https://codepen.io/Kfriis/pen/QWjGZmx
The solution that don't work:
//function that takes a currency in capital letters and returns
var rates;
var currency = 'gbp';
const currencyString = currency.toUpperCase();
const API = "api.frankfurter.app"
const URL = `https://${API}/latest?amount=1&from=${currencyString}&to=DKK`
const http = new XMLHttpRequest();
http.open("GET", URL);
http.send();
http.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
rates = JSON.parse(http.responseText);
}
};
console.log(rates)
This do, for some reason, not work. I do not get why the rates variable do not get populated since the request is basically the same for the first code snippet.
I have come down to an idea of it being because the data sent from the 2 API endpoints may be different in some way. Because if it was only because of the asynchronous requests, both code snippets should return undefined.
Link https://codepen.io/Kfriis/pen/VwvpKmd
I do hope someone is able to shine some light on this.
I must be doing something wrong in the second snippet, because I can console.log() from inside the onreadystatechange but not outside it. Which led me to believe for a long time that it was a scoping issue.
Your code does work. However, you're logging console.log(rates) outside the http.onreadystatechange-function which means you're logging the rates before you get the response. If you change the code block
http.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
rates = JSON.parse(http.responseText);
}
};
console.log(rates)
to
http.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
rates = JSON.parse(http.responseText);
console.log(rates)
}
};
it should work.
Here's a working example code if you wanna add the code to a function.
// Function that takes a currency in capital letters and returns
function getCurrencyRates(currency, cb) {
const currencyString = currency.toUpperCase();
const API = "api.frankfurter.app"
const URL = `https://${API}/latest?amount=1&from=${currencyString}&to=DKK`
const http = new XMLHttpRequest();
http.open("GET", URL);
http.send();
http.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
cb(JSON.parse(http.responseText));
}
};
}
// Call the function and pass "gbp" as currency.
// Rates will be logged in response.
getCurrencyRates('gbp', function(response) {
console.log(response);
});

Why isn't my POST XMLHttpRequest.Send working?

I am having issues correctly setting up my XMLHttpRequest object to POST data to a server. The data (from an HTML form) never seems to get posted, or at least readyState == 4 && status are never reached.
function PostToAPI() {
var payersName = document.forms["myForm"]["payersName"].value;
var recipientPhoneNumber = document.forms["myForm"]["recipientPhoneNumber"].value;
var apiKey = document.forms["myForm"]["apiKey"].value;
var params = "payersName="+payersName+
"&recipientPhoneNumber="+recipientPhoneNumber+
"&apiKey="+apiKey;
alert(params); // Note#1
var Url = "https://api.blackShawls.af/c2b"; // Note#2
var xhr = new XMLHttpRequest();
xhr.open('POST', Url, true);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.onreadystatechange = processRequest;
function processRequest(e) {
if (xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText.headers.Host); // Note#3
}
}
xhr.send(params);
}
Notes
(Note#1) This alert yields the following result:
This suggests that the various fields from the HTML form have been successfully read in, and that everything is working just fine to this point.
(Note#2) The Url value here is fictitious, in contrast to one in my code.
(Note#3) The alert(xhr.responseText.headers.Host); never seems to fire-up, suggesting that the readyState and the status conditions are never met.
Or could it be that the xhr.send(params) is never sent?
Can someone kindly point out where I am going wrong in my code?
Looking forward to your help.

Need help to get JSON data from warframe game

any idea with this is not working?
var xmlhttp = new XMLHttpRequest();
var url = "http://content.warframe.com/dynamic/worldState.php";
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var myArr = JSON.parse(xmlhttp.responseText);
myFunction(myArr);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(arr) {
}
everytime i get status = 0.
i use the same method to get my script working with the twitch one, but can't get this one working.
thank for your help guys.
edit : ok thanks any idea what can i do to get the data from this site then?(if someone have any idea it will be awesome. as you can guess i can't edit the page who provide the date, but i know some people are able to get the JSON data) .

How to delay a method until another is finished first , 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();
}
}

How to display certain JSON elements in HTML?

I would like to display the variable "hashrate" from this JSON file on a HTML webpage. I have looked around the internet, but many of the methods have not worked. Sorry if this is a duplicate question, I am very lost.
var json = {"getpoolstatus":{"version":"1.0.0","runtime":19.948959350586,"data":{"pool_name":"Capy's Pool - Gabencoin","hashrate":5.8254222222222,"efficiency":0,"workers":0,"currentnetworkblock":21903,"nextnetworkblock":21904,"lastblock":21903,"networkdiff":0.0392466,"esttime":28935.733248,"estshares":2572,"timesincelast":189,"nethashrate":451133}}};
your variable - json.getpoolstatus.data.hashrate
var xhr = new XMLHttpRequest(); //Request the data
xhr.open('POST','http://gaben.capyspool.co.uk/gabencoin/public/index.php?page=api&action=getpoolstatus&api_key=72f3fd60d9a536215a6f6f92938592a60f919586635d7d0dedcf6a394888c435',true);
xhr.send();
xhr.onreadystatechange = function() {
if (this.readyState === 4) { //When it's ready
var data = JSON.parse(this.responseText); //Parse the data
alert(data.getpoolstatus.data.hashrate); //And here it is!
}
}

Categories

Resources