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
});
Related
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 years ago.
I'm trying to get a value from a callback, but it returns an undefined value.
Below is the code I'm using:
function getJSON(url, callback) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
if (callback) return callback(this.responseText);
}
};
xhttp.open("GET", url, true);
xhttp.send();
}
function getUserName() {
getJSON("this is my url", function(resultJSON) {
return JSON.parse(resultJSON).user[0].displayName;
});
}
var userN = getUserName();
document.getElementById("username").innerHTML = "Hi " + userN;
I know this has been asked a billion times but I can't get it working the way I need with previous answers. The html element is still giving a "Hi undefined".
Any thought or suggestion?
function getJSON(url, callback) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
if (callback) return callback(this.responseText);
}
};
xhttp.open("GET", url, true);
xhttp.send();
}
function getUserName() {
getJSON("https://my-json-server.typicode.com/typicode/demo/profile", function(resultJSON) {
const userN = JSON.parse(resultJSON).name;
document.getElementById("username").innerHTML = "Hi " + userN;
});
}
getUserName();
<div id="username">Greetings</div>
You should write code for Hi + <userN> inside of 2nd parameter(callback function) of getJSON.
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 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.
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);
});
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
How to return to the calling function (the function above). I would like to return true if the file exists when doing UrlExists('file.png') :
function UrlExists(url)
{
var http = new XMLHttpRequest();
http.open('HEAD', url, true);
http.onerror = function(e){
//console.log('......onerror: ' + JSON.stringify(e));
if (typeof e !== 'undefined'){
return false
}
};
http.send();
return http.onerror();
}
Use XMLHttpResponse as async. Because async responses may not be received in the order that they are requested and since you may be checking for multiple files it may be a good idea to check the responseURL property before acting on the case where the file does not "exist" (is not found or returns error, etc.)
jsFiddle example: http://jsfiddle.net/5f42L6nz/4/
Source: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Synchronous_and_Asynchronous_Requests
function UrlExists(url) {
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true); // true => async request
xhr.onload = function (e) {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
// URL found, do stuff for "exists"
alert("url exists:\r\n" + xhr.responseURL);
} else {
// URL not found, could check xhr.status === 404, etc.
// do stuff when URL not found, but no exception/error thrown
alert("not found or unexpected response:\r\n" + xhr.responseURL);
}
}
};
xhr.onerror = function (e) {
console.error(xhr.statusText);
};
xhr.send(null);
}
var url = '/'; // just an example, get web app root
UrlExists(url);
UrlExists("/badurl");