How to assign data to a variable from a GET request - javascript

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

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) {
.....
}

Setting 'None' instead of required data

I want to set a field value based on the value of another field(Using AJAX). Here, I am trying to set the same value but it is getting set to 'None' instead of the actual value.
script for sending a request :
<script>
function getCustomerName() {
var x = document.ipwhitelistindex.AWSID.value;
console.log(x)
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.ipwhitelistindex.CUSTNAME.value = this.responseText;
}
};
xhttp.open('POST', 'getcustomernamefromexcel', true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send(x);
}
</script>
Here, I am sending x. I can see the exact value in the console but it is setting to None on the page.
python :
def getcustomernamefromexcel(request):
value = request.POST.get('x')
return HttpResponse(value)
If you call xhttp.send(x), then the name of the variable is no longer known. You need to encode this, for example with:
xhttp.send("x="+encodeURIComponent(x));

How to subset specific object properly in JS

I'm currently doing some practice and i want to print the titles of each movie on this api:
https://jsonmock.hackerrank.com/api/movies?Year=1998
Basically, I want each title to be printed for the first page (or preferably a specific page).
This is the code I have:
<script>
function printTItles(year) {
var res;
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
res = JSON.parse(this.responseText);
for(var i=0;i<res.per_page;i++){
document.getElementById("demo").innerHTML = res.data.i.Title;
}
};
}
xmlhttp.open("GET", "https://jsonmock.hackerrank.com/api/movies?Year=<year>", true);
xmlhttp.send();
}
</script>
I know the problem is in res.data.i.title but I'm not sure how to fix it.
You are trying to access the element at the index i in your loop, like you would access a property of an object. To get the element at position i in your res.data array, you need the square bracket access [ ]
Also, you are not replacing the year parameters in your request for the year parameters passed to your function. You might want to check that out.
Here I have use the year 2018 as an example.
function printTItles(year) {
var res;
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
res = JSON.parse(this.responseText);
for(var i=0;i<res.per_page;i++){
document.getElementById("demo").innerHTML = res.data[i].Title;
}
};
}
xmlhttp.open("GET", "https://jsonmock.hackerrank.com/api/movies?Year=2018", true);
xmlhttp.send();
}
printTItles();
<div id="demo"></div>
You could add some more improvement. For example, at each iteration, you are replacing the content of your #demo element. This cause only the last title to be shown. You could, instead, append the data to the already existing html of the div. Or, like I did in this case, build your string before setting it as the new innerHTML value.
function printTItles(year) {
var res;
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
res = JSON.parse(this.responseText);
var output = "";
for(var i=0;i<res.per_page;i++){
if(res.data[i]) {
output += res.data[i].Title + '<br />';
}
}
document.getElementById("demo").innerHTML = output;
};
}
xmlhttp.open("GET", "https://jsonmock.hackerrank.com/api/movies?Year=2018", true);
xmlhttp.send();
}
printTItles();
<div id="demo"></div>
I've also added a condition to check if there is an element at res.data[i].

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;
});

Updating javascript array variable through javascript ajax?

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.

Categories

Resources