AJAX, JS and scoping

Rogue roguexz at gmail.com
Sat Aug 18 13:23:06 UTC 2007


-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Hi Gary,

Gary Stainburn wrote:
> Hi folks.
> 
> Having another go with AJAX and trying to create a library function based on a 
> tutorial I've been looking at.
> 

First up, this is not the appropriate list for queries on JavaScript :-)

> However, It's not working and I think it's a javascript scoping issue. In the 
> call-back function it's complaining that xmlHttp doesn't exist when I try to 
> check that readyState == 4.
> 
> AjaxRequest itself is obviously working as it should, but how to I make the 
> xmlHttp created by it available to the call-back?
> 

This is possible, and to better understand the available options, you
might want to get yourself a nice primer on JavaScript.

One of the simplest option is just returning the xmlHttpRequest from the
method.

var xmlHttp = AjaxRequest(...);
....
 function AjaxRequest(Url,Fn) {
   var xmlHttp;
   try {
    ....
   }
   xmlHttp.onreadystatechange=Fn;
   xmlHttp.open("GET",Url,true);
   xmlHttp.send(null);

    return xmlHttp;

 }
.....

Next option is to register the call back with the function (c.f. read up
on JS on how to do it)

Lastly, I guess, you might want to split up your libraries to be browser
specific, that way you will have smaller sized scripts being pushed on
to the browsers (also improves browser page loading performance).

HTH,
Rogue

> In my web page:
> 
> ***
> <SCRIPT LANGUAGE="JavaScript">
> function getstaff(str) {
>   if (str.length==0) { 
>     document.getElementById("suggestlist").innerHTML="";
>     return;
>   }
>   AjaxRequest("/roster/chooser_ajax.html?$actval:"+str,
>      function() {
>        if(xmlHttp.readyState==4) {         
> document.getElementById("suggestlist").innerHTML=xmlHttp.responseText;
>         }
>       }
>     );
> }
> </SCRIPT>
> ***
> 
> In my library
> 
> ***
> function AjaxRequest(Url,Fn) {
>   var xmlHttp;
>   try {
>     // Firefox, Opera 8.0+, Safari
>     xmlHttp=new XMLHttpRequest();
>   }
>   catch (e) {
>     // Internet Explorer
>     try {
>       xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
>     }
>     catch (e) {
>       try {
>         xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
>       }
>       catch (e) {
>         alert("Your browser does not support AJAX!");
>         return false;
>       }
>     }
>   }
>   xmlHttp.onreadystatechange=Fn;
>   xmlHttp.open("GET",Url,true);
>   xmlHttp.send(null);
> }
> ***
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.7 (GNU/Linux)

iD8DBQFGxvK6ceS9IQvx51YRAqrbAKCInBhJBu1Cf9v6DY+WlRxjbY7q+QCgwT9K
DXAQs/hI2gJF0VugJurzACw=
=/q17
-----END PGP SIGNATURE-----




More information about the fedora-list mailing list