/    Sign up×
Community /Pin to ProfileBookmark

Moving AJAX response data from one function to another

Hi Guys,

I am working on a function which processes the XMLHttpRequest object then returns the data to the function that requested it. The function works fine, the only problem arises when I try and send the data back to the function requesting it, it returns nothing. Using the alert method I get a “undefined” when I try to view the data. See code below:

[CODE]function SendRequest(action, fileName) {
var xhr = CreateRequest();

xhr.open(action,”_” + fileName + “.htm”,true);
xhr.onreadystatechange=function() {
if(xhr.readyState==4) {
alert(xhr.responseText);/*Outputs correct data*/

return xhr.responseText;
}
}
xhr.send(null);
}

function loadtab(tabClicked) {
var out = SendRequest(“GET”, tabClicked);
alert(out); /*Outputs undefined*/
}[/CODE]

to post a comment
JavaScript

3 Comments(s)

Copy linkTweet thisAlerts:
@rnd_meJul 24.2008 — [CODE]

function SendRequest(action, fileName) {
var xhr = !window.XMLHttpRequest ? new ActiveXObject('Microsoft.XMLHTTP') : new XMLHttpRequest()
xhr.open(action,"_" + fileName + ".htm",false);
xhr.send(null);
return xhr.responseText;
}
[/CODE]
Copy linkTweet thisAlerts:
@ShaolinauthorJul 25.2008 — Thanks.

I have a question, how does changing the true to false affect the outcome ? I know that its a difference between sync/async but I don#t know how it could possibly affect the results ?

Also, why remove the onreadystatechange ?
Copy linkTweet thisAlerts:
@rnd_meJul 25.2008 — Thanks.

I have a question, how does changing the true to false affect the outcome ? I know that its a difference between sync/async but I don#t know how it could possibly affect the results ?

Also, why remove the onreadystatechange ?[/QUOTE]


onreadystatechange is what return the text, not the SendRequest function. while the xhr is off in lala land, the SendRequest function completes and returns. but it has nothing to return, as the data has not come in.

you could change the whole thing back to asynch, but you would have to re-arrange the way your calls are made.

if its synch, SendRequest waits in the middle until the data comes in, then return.
×

Success!

Help @Shaolin 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 5.18,
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: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

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