By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
459,520 Members | 1,246 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 459,520 IT Pros & Developers. It's quick & easy.

AJAX without global variables?

P: n/a
Is there a way to "pass" an XMLHttpRequest object to the callback
function for onreadystatechange? Or a way to access it from
onreadystatechange? I would like to avoid the use of a global
variable...

Example:

/* How do I get rid of this global variable? */
xmlHttp = new XMLHttpRequest();

function myFunc()
{
...
xmlHttp.onreadystatechange = myCallBack;
...
}

function myCallBack()
{
if (xmlHttp.readyState != 4)
{
return;
}

...
}

Any ideas?

Aug 16 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a


na*****@gmail.com wrote:
Is there a way to "pass" an XMLHttpRequest object to the callback
function for onreadystatechange? Or a way to access it from
onreadystatechange? I would like to avoid the use of a global
variable...
xmlHttp = new XMLHttpRequest();

function myFunc()
{
...
xmlHttp.onreadystatechange = myCallBack;


You can use a local variable declared and initialized in the function e.g.
var xmlHttp = new XMLHttpRequest();
and then use a function expression exploiting closures e.g.
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState == 4) {
...
}
};
That would require to use the stuff you have in the callback function
into the body of the function expression.
Or if you want to keep the global callback function then you could use a
function expression with a simple body calling your callback and passing
in the request object e.g.
xmlHttp.onreadystatechange = function () {
myCallBack(xmlHttp);
};
and then of course you need a parameter for your global callback
function e.g.
function myCallBack (httpRequest) {
if (httpRequest.readyState == 4) {
..
}
}
--

Martin Honnen
http://JavaScript.FAQTs.com/
Aug 16 '05 #2

P: n/a
na*****@gmail.com wrote:
Is there a way to "pass" an XMLHttpRequest object to the callback
function for onreadystatechange? Or a way to access it from
onreadystatechange? I would like to avoid the use of a global
variable...


This is a great use of closures. You can look at my ajax library at
http://www.ajaxtoolbox.com/ to see how I implemented it without any global
variables sitting around. This also has the benefit of allowing concurrent
requests which do not collide with each other.

--
Matt Kruse
http://www.JavascriptToolbox.com
http://www.AjaxToolbox.com
Aug 16 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.