This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
I don't know how to implement getState. What I am trying to do is update a field on click with a state value returned in my AJAX call. I have seen a reference to promises in another response but I do not understand how to use them.
function processRequest(e) {
if (xhr.readyState == 4 && xhr.status == 200) {
var response = JSON.parse(xhr.responseText);
var state = response.state;
}
}
$('#myState').on('click', function() {
var localState = getState();
$('#location').val(localState);
});
You need to change variable scope so it would be accessible from out of processRequest() function.
var response = '';
var state = '';
function processRequest(e) {
if (xhr.readyState == 4 && xhr.status == 200) {
response = JSON.parse(xhr.responseText);
state = response.state;
}
}
$('#myState').on('click', function() {
$('#location').val(state);
});
Related
This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 4 months ago.
I can't find a way to use the value obtained from the JSON function from ipify.org.
I need to use this value in another function, not just write it in HTML like in the examples on ipify.org.
I'm trying to assign a value to the window variable, but it can also be done in another way. I am trying to use the "javascript" example on the site: https://www.ipify.org/
<script type="text/javascript">
function getIP(json) {
window.ipa = json.ip;
}
alert(window.ipa); //return "undefined"
</script>
<script type="text/javascript" src="https://api.ipify.org?format=jsonp&callback=getIP"></script>
You have to make the request to and capture the response from api.ipify.org in your script, there are many ways to do this, I used the old, native XMLHttpRequest API.
You also need to attach this function call to an event (I used "onload" bellow).
Example:
function xhrget(items, route, callback){
const xhr = new XMLHttpRequest();
xhr.open('GET', route);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.timeout = 1000;
xhr.send(encodeURI(items));
xhr.ontimeout = function(e){
callback('404');
};
xhr.onreadystatechange = function () {
if(xhr.readyState === 4 && xhr.status === 200) {
callback(xhr.responseText);
}
if(xhr.status >= 500 && xhr.status < 600){
callback('An error occurred, please wait a bit and try again.');
}
if(xhr.status === 404) {
callback('404');
}
};
}
function getIP() {
xhrget(null, "https://api.ipify.org", (ip) => {
console.log(ip);
window.ipa = ip;
alert(window.ipa); //return "undefined"
});
}
window.addEventListener('load', (event) => {
getIP();
});
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
How do I promisify native XHR?
(6 answers)
Closed 3 years ago.
i have some problem with ordering my functions.
i have 2 function. Two of them to http requests.
what a scenario?
on first request i get some response and in this response i'm getting some string and set it to some variable.
on second request i'm adding this string to my request url.
but my second request working before then in first request response when i set my variable.
because of that i'm getting undefined value of my variable.
I understand this is sync, async problem but how i can resolve this issue ?
it's my variable which i will add end of the second request url.
var urlString = '';
this is my first request:
var requestone = new XMLHttpRequest();
requestone.onload = function () {
if (requestone.status >= 200 && requestone.status < 300) {
var data = requestone.response;
data = JSON.parse(data);
urlString = data.Key
} else {
console.log('fail')
}
};
requestone.open('GET', 'apiurl');
requestone.send();
this is my second request:
var requesttwo = new XMLHttpRequest();
requesttwo.onload = function () {
if (requesttwo.status >= 200 && requesttwo.status < 300) {
var data = requesttwo.response;
} else {
console.log('fail')
}
};
requesttwo.open('GET', 'apiurl' + urlString);
requesttwo.send();
You can do this in 2 ways, using promise, or integrate the second request inside the request1:
var requestone = new XMLHttpRequest();
requestone.onload = function () {
if (requestone.status >= 200 && requestone.status < 300) {
var data = requestone.response;
data = JSON.parse(data);
requesttwo.open('GET', 'apiurl' + data.Key);
requesttwo.send();
} else {
console.log('fail')
}
};
requestone.open('GET', 'apiurl');
requestone.send();
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 4 years ago.
I am using this code to get the contents of data.dat. Here are the files:
main.js
function getData() {
var result;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
result = this.responseText.split(",");
}
};
xhttp.open("POST","data.dat",true);
xhttp.send();
return result;
}
data.dat
A,B,C
However, getData() returns an empty string. When I log this.responseText this way:
if (this.readyState == 4 && this.status == 200) {
console.log(this.responseText);
result = this.responseText.split(",");
}
I get ["A","B","C"]. What am I doing wrong?
Since AJAX stands for Asynchronous JavaScript And XML, you're using an asynchronous call in order to get your desired output. The issue is that return result statement is returned before your AJAX call is finished and that's why you're receiving empty result.
You should use a callback function.
function getData(callback) {
var result;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
result = this.responseText.split(",");
callback(result);
}
};
xhttp.open("POST","data.dat",true);
xhttp.send();
}
getData(function(result){
console.log(result);
});
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 4 years ago.
Why sendResponse({ helloWorld: sendto }) sending back empty string and not that this.responseText is assigned to sendto variable? How to manage my code properly to achieve sending back this.responseText and not the empty string?
chrome.runtime.onMessage.addListener(
function (request, sender, sendResponse) {
**var sendto = 'empty';**
var ccc = new XMLHttpRequest();
ccc.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
console.log(this.responseText)
**sendto = this.responseText;**
}
}
ccc.open("GET", "http://127.0.0.1:3000/" + request.greeting)
ccc.send();
**sendResponse({ helloWorld: sendto });**
});
You need to add return true; to the listener function in order to use sendResponse asynchronously. For example:
chrome.runtime.onMessage.addListener(
function (request, sender, sendResponse) {
var ccc = new XMLHttpRequest();
ccc.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
console.log(this.responseText)
sendResponse({helloWorld: this.responseText});
}
};
ccc.open("GET", "http://127.0.0.1:3000/" + request.greeting)
ccc.send();
return true; // in order to use sendResponse asynchronously
});
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
Strange error, says config is undefined, but that is false:
There is no misspellings:
I am not JavaScript programmer, and that is my first extension. I hope it is a known issue. The only thing used is AJAX. The code starts like this:
var config;
var req = new XMLHttpRequest();
req.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
config = JSON.parse(this.response);
}
}
req.open("GET", chrome.extension.getURL('/config.json'), true);
req.send();
// here console.log(config) will return undefined.
In other words variable is assigned strangely.
Since XMLHTTPRequests are asynchronous (they don't happen instantly as the code flows) you'll have to either put the code inside their load event listener, or call a function that will have that code in it from the same event listener:
var config;
var req = new XMLHttpRequest();
req.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
config = JSON.parse(this.response);
// any code that uses config should be here
}
}
or:
var config;
var req = new XMLHttpRequest();
req.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
config = JSON.parse(this.response);
// call doMagicStuff here
doMagicStuff();
}
}
function doMagicStuff() {
// code that use config goes here
}
in the latter, you might as well just pass config as parameter to doMagicStuff.