/    Sign up×
Community /Pin to ProfileBookmark

No data returned from XMLHttpRequest()

I want to retrieve json outside the XMLHttpRequest() but it seems that the scope is wrong.
What am I doing wrong?

https://jsfiddle.net/4ojqnvh5/

to post a comment
JavaScript

21 Comments(s)

Copy linkTweet thisAlerts:
@SempervivumMay 05.2021 — The return statement is located inside the anonymous function for onload. Therefore it's not the return value of your function getdata. There is no return statement for the latter, therefore it's undefined.

As XMLHttpRequest works asynchronously you have to place all your processing that's based on the response inside the callback function for onload as switching to synchronous behaviour is not recommended.
Copy linkTweet thisAlerts:
@sibertauthorMay 05.2021 — > @Sempervivum#1631268 you have to place all your processing that's based on the response inside the callback function for onload

Meaning...?

https://jsfiddle.net/9yaLzm5c/
Copy linkTweet thisAlerts:
@SempervivumMay 05.2021 — ``<i>
</i>var url = "https://jsonplaceholder.typicode.com/photos";
var xhr = new XMLHttpRequest();
let data = []
data = getdata()
alert("no data returned: " + data)

function getdata() {
xhr.open("GET", url);
xhr.setRequestHeader("Accept", "application/json");
xhr.onload = function() {
if (xhr.readyState === 4) {
data = this.responseText;
alert data;
// data is available here. Place all statements
// that need or use data here.
}
};
xhr.send();
// data is not available here
// alert(data)
// return (data)
}<i>
</i>
``
Copy linkTweet thisAlerts:
@sibertauthorMay 05.2021 — > @Sempervivum#1631272

> if (xhr.readyState === 4) {

> data = this.responseText;

> alert data;

> // data is available here. Place all statements

> // that need or use data here.

> }


I thought I did this in my original fiddle:

``<i>
</i> if (xhr.readyState === 4) {
alert(this.responseText)
return (this.responseText)
}<i>
</i>
``


But nothing is returned "outside the function"...
Copy linkTweet thisAlerts:
@SempervivumMay 05.2021 — I extended my remarks:
``<i>
</i> function getdata() {
xhr.open("GET", url);
xhr.setRequestHeader("Accept", "application/json");
xhr.onload = function () {
if (xhr.readyState === 4) {
data = this.responseText;
alert(data);
// data is available here. Place all statements
// that need or use data here.
// return statement here would be affect
// the anonymous function for unload only
}
};
xhr.send();
// It would be necessary to place the return statement
// for the function getdata here
// but unfortunately data is not yet available here
}<i>
</i>
``
Copy linkTweet thisAlerts:
@sibertauthorMay 05.2021 — > @Sempervivum#1631274

> // data is available here. Place all statements

> // that need or use data here.


I interpret this as I cannot call the function from outside and fetch the data. Just use it inside the "readyState"...
Copy linkTweet thisAlerts:
@SempervivumMay 05.2021 — Yes, this is correct. However, to make the code more clear, you can place the processing based on the data of the response, in a function and call this on load:
``<i>
</i> function processData() {
if (xhr.readyState === 4) {
data = xhr.responseText;
alert(data);
// further processing of data here
}
function getdata() {
xhr.open("GET", url);
xhr.setRequestHeader("Accept", "application/json");
xhr.onload =processData;
xhr.send();
}<i>
</i>
`</CODE>
Or hand over that function as a callback:
<CODE>
`<i>
</i> function processData(data) {
alert(data);
// further processing of data here
}
function getdata(url, callback) {
xhr.open("GET", url);
xhr.setRequestHeader("Accept", "application/json");
xhr.onload = function () {
if (xhr.readyState === 4) {
data = xhr.responseText;
callback(data);
};
xhr.send();
}
getdata('your-url', processData);<i>
</i>
``

When doing so, the function getdata could be reused easily.
Copy linkTweet thisAlerts:
@sibertauthorMay 06.2021 — > @Sempervivum#1631280 you can place the processing based on the data of the response, in a function and call this on load:

I do not still get it.

https://jsfiddle.net/5kwh19p6/3/


> Or hand over that function as a callback:

https://jsfiddle.net/prLevqb9/

"Maximum call stack size exceeded"
Copy linkTweet thisAlerts:
@SempervivumMay 06.2021 — Regarding the first Fiddle: **No** trailing brackets for processData, you have to hand over a reference of the function:
``<i>
</i> function getdata() {
xhr.open("GET", url);
xhr.setRequestHeader("Accept", "application/json");
xhr.onload = processData;
xhr.send();
}<i>
</i>
``
Copy linkTweet thisAlerts:
@SempervivumMay 06.2021 — Regarding the second fiddle:

getdata has to be called **outside** of the function, otherwise there is an endless recursion:
``<i>
</i> var url = "http://94.237.92.101:6061/users";
var xhr = new XMLHttpRequest();

function processData(data) {
alert(data);
// further processing of data here
}

function getdata(url, callback) {
xhr.open("GET", url);
xhr.setRequestHeader("Accept", "application/json");
xhr.onload = function () {
if (xhr.readyState === 4) {
data = xhr.responseText;
alert(data)
callback(data);
}
}
xhr.send()
}
getdata(url, processData);<i>
</i>
``

Edit: And xhr.send() has to be called **outside** of the anonymous function for onload.
Copy linkTweet thisAlerts:
@sibertauthorMay 06.2021 — > @Sempervivum#1631291 Regarding the first Fiddle:

This does not work either. But I finally got this to work by translating (to my brain) "callback" to "send data". You cannot assign ajax data to a variable or "get data" in Javascript (as I understand it). You have to "send it" to another function. Correct?

https://jsfiddle.net/w3084tgr/
Copy linkTweet thisAlerts:
@SempervivumMay 06.2021 — The code from the first fiddle works fine for me:
``<i>
</i> &lt;button onclick="getdata()"&gt;
getdata
&lt;/button&gt;
&lt;script&gt;
var url = "http://94.237.92.101:6061/users";
var xhr = new XMLHttpRequest();

function processData() {
console.log("readystate: " + xhr.readyState);
if (xhr.readyState === 4) {
data = xhr.responseText;
console.log(data);
// further processing of data here
}
}

function getdata() {
xhr.open("GET", url);
xhr.setRequestHeader("Accept", "application/json");
xhr.onload = processData;
xhr.send();
}
&lt;/script&gt;<i>
</i>
``
Copy linkTweet thisAlerts:
@sibertauthorMay 06.2021 — > @Sempervivum#1631296 The code from the first fiddle works fine for me:

I cannot get it to work...

https://jsfiddle.net/0qzcsmou/
Copy linkTweet thisAlerts:
@SempervivumMay 06.2021 — Take a look at the console, it says:
>Mixed Content: The page at 'https://www.webdeveloper.com/' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint 'http://94.237.92.101:6061/users'. This request has been blocked; the content must be served over HTTPS.

The URL of the JSON is not loaded via https, therefore the browser rejects it due to security reasons.

I tested on my local webserver, therefore it worked as my test page was not called via https.
Copy linkTweet thisAlerts:
@sibertauthorMay 06.2021 — > @Sempervivum#1631301 The URL of the JSON is not loaded via https

I was not aware of that the url was different. Thank you. But I cannot still get your code to work...

https://jsfiddle.net/tpLxqkm1/1/

The result is an empty {}
Copy linkTweet thisAlerts:
@SempervivumMay 06.2021 — When I call that url directly in my browser, the response is exactly the same: `{}</C>.

When I change the URL, e. g., like this:<br/>
<C>
var url = "https://jsonplaceholder.typicode.com/users/1";`


I get an output.
Copy linkTweet thisAlerts:
@sibertauthorMay 06.2021 — > @Sempervivum#1631305 When I call that url directly in my browser, the response is exactly the same: {}.

Sorry. Should be https://jsonplaceholder.typicode.com/users. The final "s" was missing.

But you have helped me a lot, so thank you indeed for your help!
Copy linkTweet thisAlerts:
@SempervivumMay 06.2021 — You're welcome!
Copy linkTweet thisAlerts:
@sibertauthorMay 06.2021 — My intention was to fill a table with data. That is why I wanted to "separate" the data from the axaj:

https://jsfiddle.net/trfjpeom/2/

It seems that I have to learn more about what [object Object] is :-)
Copy linkTweet thisAlerts:
@SempervivumMay 06.2021 — >My intention was to fill a table with data. That is why I wanted to "separate" the data from the axaj:

In this situation datatables can be your friend. A few lines of javascript and done:
``<i>
</i>$(document).ready(function() {
$('#example').DataTable( {
"ajax": '../ajax/data/arrays.txt'
} );
} );<i>
</i>
``

https://datatables.net/examples/data_sources/ajax.html
Copy linkTweet thisAlerts:
@sibertauthorMay 06.2021 — > @Sempervivum#1631320 In this situation datatables can be your friend. A few lines of javascript and done:

Thanks. Yes, I know. I have investigated Tabulator, w2ui, Datatables and ag-Grid.

http://94.237.92.101:7070/aggrid

But when I tried Datatables I got too many "dependency error". Using a "grid library", you have to learn the library, JQuery and sometimes Vanilla.

All grid libraries that is based on vanilla JS are simpler. But I am still in the investigation phase. So who knows how it will ends. Using SSR can be an option, but it seems that AJAX will be the way to go.
×

Success!

Help @sibert spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 4.25,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...