Updating javascript array variable through javascript ajax? - javascript

I have a javascript variable that holds an array to update a map and I am trying to get AJAX to update that variable with the server data so that it will update the map based on a selected option.
Basically, here is where I'm at
Javascript:
var mapData=[];
function stateData(inputData){
data = [inputData];
return data;
}
AJAX:
function updateData(selectedVar){
var newRequest = new XMLHttpRequest();
newRequest.onreadystatechange = function(){
if (this.readyState == 4 && this.status == 200){
serverdata = this.responseText;
mapData = serverdata;
stateData(mapData);
}
};
newRequest.open("GET", "testscript.php?selection="+selectedVar, true);
newRequest.send();
}
If it helps the data that I'm transferring is in this format after PHP script:
{state="AK", hourlypay=18.22, annualpay="43,666"}, {state="AZ", hourlypay=25.88, annualpay="89,980"}, etc.

Related

JS: problem with for loop (only one image is shown)

I am completely new to javascript and web development.
I'm having a problem with the for loop; what happens to me is that the ids come back to me all together and not individually in order to retrieve the relative image and title through the id, so I can't recover images and title from the json array.
Specifically I get the error:
Uncaught TypeError: Cannot read properties of undefined (reading 'immagine') at XMLHttpRequest.xmlhttp.onreadystatechange
Warning: I have no problems in how to retrieve items in a json array because I know how to do it very well
This is my code:
//here I get all the articles, so my json array
var xmlhttp = new XMLHttpRequest();
var url = "https://wjko5u1234.execute-api.us-east-2.amazonaws.com/articles";
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var allart = JSON.parse(this.responseText);
var container=document.getElementById("slideshow")
for(var i = 0; i < allart.Items.length; i++)
{
container.innerHTML += '<div class="slideshow-container"></div>';
document.getElementById("id").innerHTML += "<br/>" + allart.Items[i].id;
myFunction1(allart.Items[i].id);
}
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
//here I pass the id via function call, and for each id I want to retrieve image and title which has that specific id only i get the set of ids without having one at a time to retrieve what i need
function myFunction1(id) {
var xmlhttp = new XMLHttpRequest();
var url = "https://wjko5u1234.execute-api.us-east-2.amazonaws.com/articles/"+id;
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myArr = JSON.parse(this.responseText);
console.log(myArr);
document.getElementById("img1").src="articoli_img/"+myArr.Item.immagine;
document.getElementById("title1").innerHTML = myArr.Item.titolo;
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
I would be very thankful for any help.
It seems that "Item" prop doesn't exist in returned object (located in myFunction1()) (did you mean to write myArr.immagine?)
Since you are new: I recommend to use for-each loops in collections, by using:
for(let item of allart.Items) {
.....
}

How to assign data to a variable from a GET request

I am trying to pass an ID to the API and have the server return the object and then assign that object to a variable but I cant quite figure out where I am going wrong
function createList() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function(){
if(this.readyState == 4 && this.status == 200 ){
var theList = JSON.parse(this.responseText);
console.log("the name of the current list given the ID is: " + theList.name);
}
};
xhttp.open('GET', 'todoapi/lists/' + editID , true);
xhttp.send();
}
I want the end result to be a variable that is storing an object, obtained by passing the API the object's id

Can you return a value from a xhttp request?

I have an xhttp function that calls my db and returns an array, the array is different depending on the parameter passed in the xhttp function when called.
This is the xhttp function I have:
fetchGroupInfo: function (groupNum) {
var global = this;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() { //(callback function)this function runs after xhttp.open because we have asynchronous data sending so as soon as the data is recieved this is run
if (xhttp.readyState === XMLHttpRequest.DONE && xhttp.status == 200) {
console.log(this.responseText);
//I parse the rawdata received into jason structure then I pass it into and call the manipulate function
var rawdata = this.responseText;
var json = JSON.parse(rawdata); //parses the query result
return json;
}
};
xhttp.open("GET", "http://178.62.***.***:1020/groupInfo/"+groupNum, true);
xhttp.send();
},
Since I need to call the function 8 times on page load and get back 8 different arrays, I do not want to have to write out this function 8 times for each different array I need to get back. what I would like to be able to do later is something like this, so that I can keep my code clean:
this.group1Info = this.fetchGroupInfo(1);
this.group2Info = this.fetchGroupInfo(2);
this.group3Info = this.fetchGroupInfo(3);
this.group4Info = this.fetchGroupInfo(4);
.....
At the moment the way that the function is set up it is returning an undefined value, how would I make this work?
Your code is asynchronous, so you'll you to add a callback function and then set your variables in the callback:
fetchGroupInfo: function (groupNum, callback) {
var global = this;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() { //(callback function)this function runs after xhttp.open because we have asynchronous data sending so as soon as the data is recieved this is run
if (xhttp.readyState === XMLHttpRequest.DONE && xhttp.status == 200) {
console.log(this.responseText);
//I parse the rawdata received into jason structure then I pass it into and call the manipulate function
var rawdata = this.responseText;
var json = JSON.parse(rawdata); //parses the query result
return callback(json);
}
};
xhttp.open("GET", "http://178.62.***.***:1020/groupInfo/"+groupNum, true);
xhttp.send();
}
and now to set the variables, pass a callback each time you call fetchGroupInfo:
this.fetchGroupInfo(1, function(result) {
this.group1Info = result;
});

Properly passing information to a prototype

Only using javascript.
I want to create a prototype called Table that gets all table values such the array that contains all information, how many rows are going to be displayed, the default rows that are going to be displayed, etc.
With AJAX i'm getting the query and parsing to json, then giving to loadTable the jsonArrayList so I can dynamically create the table depending on how many rows the user want to be displayed.
I am not able to give to the prototype the Array (jsonObj.aaData), i guess is not in the scope and ends being undefined, how do i do it correctly?
function loadQuery() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
//parse to JSON, sends arrayList to loadTable
var jsonObj = JSON.parse(xhttp.responseText);
// function to create the table
//loadTable(jsonObj.aaData);
//does not work
var table_info = new Table(jsonObj.aaData);
}
};
display_number = refreshDropdown();
xhttp.open("GET", "server_processing2.php?iDisplayStart=1&iDisplayLength=" + display_number, true);
xhttp.send();
}
The thing is creating an instance that all functions can see and extract the information from that instance instead of passing parameters from one function to another.
function Table(jsonArrayL){
this.jsonArrayL = jsonArrayL;
this.default_rows = 25;
}

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