XMLHttpRequest Replace Element Won't Work With LocalStorage - javascript

I tried to implement cookie logging with localStorage into the javascript code for replacing a specific element. It uses the XMLHttprequest method and, I got no idea why it won't work with localStorage. Please enlighten me.
localStorage.setItem("replace1", this.JSON.parse(responseText));
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("replace1").innerHTML = localStorage.getItem("replace1");
}
};
xhttp.open("GET", "yoinkexecutor2.php", true);
xhttp.send();
}

You can only display data when the async operation (GET) request terminates.
Otherwise you'll get undefined since nothing exits in the localStorage under that key
Also, you can only store strings in local storage, meaning you need to parse that object string once you want to retrieve the data using getItem
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
localStorage.setItem("replace1", JSON.stringify(this.responseText))
document.getElementById("replace1").innerHTML = JSON.parse(localStorage.getItem("replace1"))
}
};
xhttp.open("GET", "yoinkexecutor2.php", true);
xhttp.send();
}

Related

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

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

Can't get JSON file into variable

I am trying to parse the content of the JSON file into a variable called weatherArray. However, this variable is always an empty array.
let weatherArray = [];
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
weatherArray = JSON.parse(this.responseText);
}
};
xhttp.open("GET", "https://fcc-weather-api.glitch.me/api/current?lon=55&lat=12", true);
xhttp.send();
}
/* Expecting the value to be stored and be shown in console*/
console.log(weatherArray);
You're checking the results before they come back. You need to move the line:
console.log(weatherArray);
To inside the onreadystatechange function, which will check the results once they arrive. Also you need to call the loadDoc() function (you probably did that).
let weatherArray = [];
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
weatherArray = JSON.parse(this.responseText);
console.log(weatherArray);
}
};
xhttp.open("GET", "https://fcc-weather-api.glitch.me/api/current?lon=55&lat=12", true);
xhttp.send();
}
loadDoc();
EDIT If you like to process the results in another function instead of inside onreadystatechange, you can call that function from onreadystatechange. You can do that with your global weatherArray, but I just recommend in this case to simply pass the data in a parameter:
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
showWeather(JSON.parse(this.responseText));
}
};
xhttp.open("GET", "https://fcc-weather-api.glitch.me/api/current?lon=55&lat=12", true);
xhttp.send();
}
function showWeather(weatherArray) {
console.log(weatherArray);
}
loadDoc();
Ajax is asynchronous call, and you are printing data before invoking the ajax call,
I made some changes try it.
let weatherArray = [];
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
weatherArray = JSON.parse(this.responseText);
console.log(this.responseText);
}
};
xhttp.open("GET", "https://fcc-weather-api.glitch.me/api/current?lon=55&lat=12", true);
xhttp.send();
}
loadDoc();
/* Expecting the value to be stored and be shown in console*/
I'd like to provide an alternative modern approach using the Fetch api and Promises.
First fetch from the api
Convert it to json
Return the promise
Listen for the promise and log the result in the callback
function loadDoc() {
return fetch("https://fcc-weather-api.glitch.me/api/current?lon=55&lat=12")
.then(res => res.json())
}
loadDoc().then((weatherArray) => {
console.log(weatherArray);
})

generic callback function with xmlhttp how to send the reference to a function when "this" changes

I am polling a database.
see the "<--------------" in the code below.
This works:
class MultiplayerGame{
...
...
callPhpWithAjax(url){
var xmlhttp = new XMLHttpRequest();
var instance = this;
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
instance.pollResponse(this.responseText); <-----------works, pollResponse is called and I can access the object with "this"
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
poll(){
var url = "myurl.com"
this.callPhpWithAjax(url);
}
pollResponse(response){
this.variable = response;
}
}
When I try to implement it a bit more generic, it doesn't work:
class MultiplayerGame{
...
callPhpWithAjaxGenericNOTWORKING(url,callbackfunction){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
callbackfunction(this.responseText); <----------callbackfunction not calling what I wanted.
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
poll(){
var url = "myurl.com"
this.callPhpWithAjaxGenericNOTWORKING(url, this.pollResponse); <--------------- it seems like this.pollResponse is not ok. I don't know how to do it.
}
pollResponse(response){
this.variable = response; <----- this.variable is undefined. (this is not the class instance i was hoping)
}
When I call the function with the callbackfunction, I use "this", but apparently, it does not reference the same object. I am confused here.
How do I send the callbackfunction correctly as a paramenter?
Add .bind(this) when using an object's method as a callback parameter.
So your code inside poll should be
this.callPhpWithAjaxGenericNOTWORKING(url, this.pollResponse.bind(this))
See Function.prototype.bind()

accessing nested tags in XML files

I am making a simple XML parser in javascript using the XMLHttpRequest object, and i am having trouble returning only the tags I want. For example, for this xml file I would like to access and print the variant array (1st one), however my current code is not working.
JavaScript
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
function run() {
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "http://www.deadstock.ca/collections/adidas/products/adidas-equipment- support-adv-core-black-24.xml", true);
xhttp.send();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// Typical action to be performed when the document is ready:
console.log(xhttp.responseText.hash.variant[0]);
}
}
}
run();
However, this works (returns everything)
console.log(xhttp.responseText);
I am currently running the file using node.

Categories

Resources