I\'m having problems with this piece of code; the return value comes back as \'undefined\'. What\'s the problem?
var fx = null;
xmlhttp.open(\"GET\", URL ,fa
Update based on your edit
function getData(callback)
{
// you should move the creation of xmlhttp in here
// so you can make multiple getData calls if needed
// if you keep xmlhttp outside the function the different calls to getData will interfere
// with each other
xmlhttp.open("GET", URL ,false); // false should be true, to make it async
...
{
alert(xmlhttp.responseText);
cbfunc(xmlhttp.responseText); // your function gets passed as the
// parameter "callback" but you're
// using "cbfunc" here instead of "callback"
...
getData(function cbfoo(txt) // you can omit the function name here
...
Fixing those issues should make the code work.
Old answer
You're calling the XMLHttpRequest in Synchronous mode, that means that it will block the script until the request has finished, since you're assigning the onreadystatechange
callback after the blocking call (that means after the request has already finished) your code never gets notified.
Since the synchronous mode blocks the script, it also blocks the Browser's UI, so it's not recommended to use this mode.
You should (for 99% of the cases) use the Asynchronous mode and use a callback to handle the data, since xmlhttp.open
does not return the return value of the onreadystatechange
callback, it simply returns undefined
immediately when run in async mode.
Now a common pattern is to write a wrapper for the request and pass an anonymous function to this wrapper, which later will get called back when the request has finished.
function doRequest(url, callback) {
var xmlhttp = ....; // create a new request here
xmlhttp.open("GET", url, true); // for async
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4) {
if (xmlhttp.status == 200) {
// pass the response to the callback function
callback(null, xmlhttp.responseText);
} else {
// pass the error to the callback function
callback(xmlhttp.statusText);
}
}
}
xmlhttp.send(null);
}
You can now do a request and supply a function that will get called as soon as the request finishes, inside of that function you then do whatever you want to do with the response.
doRequest('http://mysite.com/foo', function(err, response) { // pass an anonymous function
if (err) {
alert('Error: ' + err);
} else {
alert('Response: ' + response);
}
});
This is the common programming model in the browser, always go with a asynchronous solution, if you block the script you block the whole Browser.