Sei sulla pagina 1di 52

  Resources | Buyer's Guide | Newsletter | Safari Bookshelf 

NEW! Altova SemanticWorks 2006 ­ The ground­breaking visual RDF/OWL editor. Try for free! 

  Very Dynamic Web Interfaces  Print  Add to Project 


Business  Sponsored By: 
Databases  by Drew McLellan  Tags: javascript ajax xml 
Graphics  February 09, 2005 
Metadata      xmlhttprequest web 
Mobile 
Bookmark with del.icio.us 
Programming 
Schemas 
Semantic Web 
Style 
Web  One of the classic drawbacks to building a 
Web Services  web application interface is that once a 
page has been downloaded to the client, 
Sponsored By
the connection to the server is severed. 
Any attempt at a dynamic interface 
involves a full roundtrip of the whole 
XML  page back to the server for a rebuild­­a 
Development  process which tends to make your web 
Tools 
app feel inelegant and unresponsive. In 
Free Download Stylus 
this article, I'll be exploring how this 
Studio – The World's  problem can be tackled with the use of 
best XML Editor! JavaScript and the XMLHttpRequest
Learn XML  object. 
development with 
Stylus Studio XML 
IDE  I'm sure you're familiar with the 
traditional interface model for a web 
Join the XML  application. The user requests a page from 
discussion at the 
Stylus Studio  the server, which is built and delivered to 
Developer Network the browser. This page includes an HTML 
form element for capturing data from the 
  user. Once the user posts their input back 
Annotated XML 
What is XML?  to the server, the next page can be built 
What is XSLT?  and served based on the input, and so the 
What is XSL­FO?  process continues. This is largely dictated 
What is XLink? 
What is XML Schema?  by the nature of HTTP and differs from 
What is XQuery?  the traditional desktop application model 
What is RDF?  of an interface which is inherently 
What is RSS? 
What is AJAX?  connected to the application layer. 
What are Topic Maps? 
What are Web Services?  Take the simple example of filling out a serial number box to register a desktop app on a platform 
What are XForms? 
XSLT Recipe of the Day  like Microsoft Windows. According to convention, once you've finished typing that tiresome 
string of alphanumeric into the little boxes, a big green 'tick' icon appears to indicate you've 
Article Archive entered a valid code. This happens instantly as a result of the interface being sewn to the 
application; as soon as you finish typing the number, the application is able to check its validity 
  and respond. 
<taglines/> 
Agile Web 
Dive into XML  Contrast this to the standard behavior of the same task represented through a web interface. Sure, 
Hacking Congress  all the boxes for keying in the serial number will look identical, but on completing input, the user 
Hacking the Library 
Java Web Services 
would need to submit the page back to the server for the input to be validated. A new page would 
Security  then load with a message to indicate success or failure, and on failure, the user would need to go 
Jon Udell  back and try again ad infinitum. 
Perl and XML 
Practical XQuery 
Python and XML  So whilst it's not terribly common that a user would be asked to enter a serial number into a web 
Rich Salz  application, there are countless other examples of user actions that can benefit from very fast 
Sacré SVG 
Standards Lowdown 
reactions from the interface, and when the business logic is all the way back at the server, this can 
The Restful Web  be difficult to achieve in a traditional web app. 
Transforming XML 
XML Annoyances 
Enter JavaScript 
XML Q&A  Through the use of JavaScript, a reasonable amount of logic can be added to an HTML page in 
XML Tourist 
XML­Deviant order to give timely feedback to user interactions. This has some major drawbacks, however. The  Ads by Google 

first problem is that, as the JavaScript has been delivered to the browser along with the page, that 
logic has been opened up to interrogation. This might be fine for checking the format of an email  Visual Basic Coder 
 
needed 
XML Resources  address but would be no good for something like our serial number example, as the exposure of  Join GetAFreelancer.com 
Buyer's Guide 
Events Calendar 
the method of verifying that input would compromise the integrity of the serial number  and bid on projects. Free 

Standards List  mechanism.  and quick signup. 


www.GetAFreelancer.com 
Submissions List 
The second problem with including any serious logic within the page is that the interface layer is 
simply not the place for serious logic. This belongs in the application layer, which is way back at 
XML Schema Editor 
the server. The problem is compounded by the fact that JavaScript cannot usually be relied upon  Design, Edit & Convert XML 
to be available at the client. Whilst the majority of users are able and willing to run JavaScript in  Schema Easy­to­use, 
their browser, a considerable number prefer not to, or browse with a device where JavaScript is  Download a Free Trial. 
www.Altova.com 
either unavailable or makes no sense. Therefore, any logic operations performed with JavaScript 
at the client must be verified at the server in case the operation never occurred. 

The XMLHttpRequest Object  XML Editor for free 
XML, XSLT Debugger, XML 
Schema etc No registration. 
A solution to these problem presents itself in the form of the XMLHttpRequest object. This  Download today! 
object, first implemented by Microsoft as an ActiveX object but now also available as a native  www.freexmleditor.com 

object within both Mozilla and Apple's Safari browser, enables JavaScript to make HTTP 
requests to a remote server without the need to reload the page. In essence, HTTP requests can be 
made and responses received, completely in the background and without the user experiencing 
any visual interruptions.  Xml vb 
We Found What You Are 
Looking For Xml vb 
This is a tremendous boon, as it takes the developer a long way towards achieving the goals of  www.advancedwebsearch.com 
both a responsive user interface and keeping all the important logic in the application layer. By 
using JavaScript to ferry input back to the server in real time, the logic can be performed on the 
server and the response returned for near­instant feedback. 
Free Microsoft XML 
Editor 
The Basics  Build .NET XML 
Applications Easy to use, 
Download Now! 
Due to its history, and not yet being embodied in any public standard (although something  www.stylusstudio.com
similar is in the works for the proposed W3C DOM Level 3 Load and Save spec), there are two 
distinct methods for instantiating an XMLHttpRequest object. For Internet Explorer, an ActiveX 
object is used: 
var req = new ActiveXObject("Microsoft.XMLHTTP"); 

For Mozilla and Safari, it's just a native object: 

var req = new XMLHttpRequest(); 

Clearly, as a result of this inconsistency, it's necessary to fork your code based on support for the 
appropriate object. Whilst there are a number of methods for doing this (including inelegant 
browser hacks and conditional comment mechanisms), I believe it's best to simply test for 
support of either object. A good example of this can be found in Apple's developer 
documentation on the subject. Let's take their example: 

var req; 

function loadXMLDoc(url) 

// branch for native XMLHttpRequest object 
if (window.XMLHttpRequest) { 
req = new XMLHttpRequest(); 
req.onreadystatechange = processReqChange; 
req.open("GET", url, true); 
req.send(null); 
// branch for IE/Windows ActiveX version 
} else if (window.ActiveXObject) { 
req = new ActiveXObject("Microsoft.XMLHTTP"); 
if (req) { 
req.onreadystatechange = processReqChange; 
req.open("GET", url, true); 
req.send(); 


}

A particularly important property to note is the onreadystatechange  property. Note how it is 
assigned to a function processReqChange. This property is an event handler which is triggered 
whenever the state of the request changes. The states run from zero (uninitialized) through to four 
(complete). This is important because our script isn't going to wait for the response before 
continuing. The HTTP shenanigans are initiated, but then they carry on out of process whilst the 
rest of the script runs. Due to this, it's not as simple as having loadXMLDoc  return the result of the 
request at the end of the function, because we don't know if we'll have a response by then or not. 
By having the function processReqChange  check for the state changing, we can tell when the 
process has finished and carry on only if it has been successful. 

With this in mind, a skeleton processReqChange  function needs to check for two things. The 
first is the state changing to a value of 4, indicating the process complete. The second is to check 
the HTTP status code. You'll be familiar with common status codes like 404 (file not found) and 
500 (internal server error), but the status code we're looking for is good old 200 (ok), which 
means everything went well. If we get both a state of 4 and an HTTP status code of 200, we can 
go right ahead and start processing the response. Optionally, of course, we can attempt to handle 
any errors at this point, if, for example, the HTTP status code was something other than 200. 

function processReqChange() 

// only if req shows "complete" 
if (req.readyState == 4) { 
// only if "OK" 
if (req.status == 200) { 
// ...processing statements go here... 
} else { 
alert("There was a problem retrieving 
the XML data:\n" + req.statusText); 


}

In Practice 

I'm going to work up a practical example so we can get this going. Most web applications have 
some method of signing up users, and it's common to ask the user to pick a username to use for 
the site. Often, these need to be unique, and so a check is made against the database to see if any 
other user already has the username a new recruit is trying to sign up with. If you've ever signed 
up for a web mail account, you'll know how infuriating it is cycling around the process trying to 
find a username that isn't already taken. It would be really helpful if that check could be made 
without the user leaving the page. 

The solution will involve four key elements: an XHTML form, a JavaScript function for handling 
the specifics of this case, our pair of generic functions (as above) for dealing with HTTP, and 
finally, a script on the server to search the database. 

The Form 

Here's the easy bit­­a simple form field to collect the user's chosen username. An onblur  event 
handler is used to fire the script. In order to display a friendly message to the user if the name is 
taken, I've embedded it in the form and hidden it with CSS. This should prove a little less violent 
than a standard JavaScript alert box. 

<input id="username" name="username" type="text" 
onblur="checkName(this.value,'')" /> 
<span class="hidden" id="nameCheckFailed"> 
This name is in use, please try another. 
</span> 

The CSS defines a class for hidden  and also one for showing the error. Call that one error. 

span.hidden{ 
display: none; 

span.error{ 
display: inline; 
color: black; 
background­color: pink; 
}

Handling the Input 

The checkName  function is used to handle the input from our form. Its job is to collect the input, 
decide which script on the server to present it to, invoke the HTTP functions to do the dirty work 
on its behalf, and then deal with the response. As such, this function has to operate in two modes. 
One mode receives input from the form, the other the response from the HTTP request. I'll 
explain the reason for this in the next section. 

function checkName(input, response) 

if (response != ''){ 
// Response mode 
message   = document.getElementById('nameCheckFailed'); 
if (response == '1'){ 
message.className = 'error'; 
}else{ 
message.className = 'hidden'; 

}else{ 
// Input mode 
url  = 
'http://localhost/xml/checkUserName.php?q=' + input; 
loadXMLDoc(url); 

Our response is going to be easy to deal with­­it'll be a string of either 1 or 0, with 1 indicating 
that the name is in use. Therefore, the function changes the class name of the error message so it 
gets displayed or hidden, depending. As you can see, the dirty work at the server is being done by 
a script called checkUserName.php. 

HTTP Heavy Lifting 

As we saw earlier, the HTTP work is being done by two functions, loadXMLDoc  and 
processReqChange. The former can remain totally as­is for the purposes of this example, with 
the only modifications needed to the latter being a quick bit of DOM work. 

You'll recall that by the time a successful response has been passed to processReqChange, we're 
no long in a position to pass any sort of return value back up the chain. Because of this, it's going 
to be necessary to make an explicit function call to another bit of code in order to do anything 
useful with the response. This is why our checkName  function has to run in two modes. 
Therefore, the main job of processReqChange  is to parse the XML coming back from the server 
and pass the raw values back to checkName. 

However, it is important that we keep these functions generic (we may have multiple items on the 
page that need to make use of XMLHttpRequest), and so hard­coding a reference to checkName 
at this point would be foolhardy. Instead, a better design is to have the server indicate the 
handling function as part of its response. 

<?xml version="1.0" encoding="UTF­8" 
standalone="yes"?> 
<response> 
<method>checkName</method> 
<result>1</result> 
</response>

Parsing such a simple response should be no problem at all. 
function processReqChange() 

// only if req shows "complete" 
if (req.readyState == 4) { 
// only if "OK" 
if (req.status == 200) { 
// ...processing statements go here... 
response  = req.responseXML.documentElement; 

method    = 
response.getElementsByTagName('method')[0].firstChild.data; 

result    = 
response.getElementsByTagName('result')[0].firstChild.data; 

eval(method + '(\'\', result)'); 
} else { 
alert("There was a problem retrieving the XML 
data:\n" + req.statusText); 


}

By using the responseXML  property of the XMLHttpRequest object, we have a ready­made XML 
object we can traverse with the DOM. By grabbing content of the method element, we know 
which local function to execute along with the result. Once you've finished testing, it's probably a 
good idea to dump the else clause from the above code, enabling the function to fail silently. 

The Server Script 

The final piece in our jigsaw is the script on the server to accept the request, process it, and return 
an XML document in response. For the purposes of our example, this script looks up usernames 
in a database table to determine whether a name is already in use. For brevity, my example PHP 
script below just checks against two hard­coded names, 'Drew' and 'Fred'. 
<?php 
header('Content­Type: text/xml'); 

function nameInUse($q) 

if (isset($q)){ 
switch(strtolower($q)) 

case  'drew' : 
return '1'; 
break; 
case  'fred' : 
return '1'; 
break; 
default: 
return '0'; 

}else{ 
return '0'; 


?> 
<?php echo '<?xml version="1.0" encoding="UTF­8" 
standalone="yes"?>'; ?> 
<response> 
<method>checkName</method> 
<result><?php 
echo nameInUse($_GET['q']) ?> 
</result> 
</response>

Of course, the logic used to verify the availability of the username in this script can be reused 
after the form is submitted to recheck that the name is available. This is an important step, since 
if JavaScript was not available at the client, this check would not have yet taken place. 
Additionally, on a busy site, a username which checked out OK at the time the user was filling 
the form in may have been taken by the time the form is submitted. 

Perhaps as a next step, if you're interested in playing with this some more, you could add the 
ability for the server to return a list of suggested alternative usernames if the suggested name is 
taken. 

In Conclusion 

This small example really only scratches the surface of the things achievable with 
XMLHttpRequest. Some other examples would include Google Suggest, which uses 
XMLHttpRequest to provide suggested search terms, and the Ta­da Lists application, which 
commits user data to the server in the background to provide a really fast list managing interface. 
The real challenge here is not figuring out how to make the code work but thinking of interesting 
ways in which it can be utilized. 

Related Reading 

No Nonsense 
XML Web 
Development 
With PHP 
By Thomas Myer 

Share your experience in our forums. 
(* You must be a member of XML.com to use this feature.) 
Comment on this Article 

Titles Only  Titles Only  Newest First

l  url problem 
2005­10­26 04:38:49 ramsee  [Reply] 
Hi, 
I am writing the same code but try to run that code i have to give Url. 
I have created test.txt on D: 
so what url i am supposed to give thax 

l  Probelm... 
2005­10­15 06:34:03 fretoune  [Reply] 

Hello there, 

I'm sorry to say that I'm just unable to make the script work. It's been a couple of hours 
since it's driving me crazy... I've read over and over again, everything looks like what is 
above. 
I've tried without the quotes around (response == '1'), I've tried to put my files in the same 
folders... No way to work (I've got Firefox 1.0.7 

Sorry to post all my code, but if you can help, I'd greatly appreciate... 

file : loadxmldoc.js : 
var req; 

function loadXMLDoc(url) { 
// branch for native XMLHttpRequest object 
if (window.XMLHttpRequest) { 
req = new XMLHttpRequest(); 
req.onreadystatechange = processReqChange; 
req.open("GET", url, true); 
req.send(null); 
// branch for IE/Windows ActiveX version 
} else if (window.ActiveXObject) { 
req = new ActiveXObject("Microsoft.XMLHTTP"); 
if (req) {
req.onreadystatechange = processReqChange; 
req.open("GET", url, true); 
req.send(); 


function processReqChange() 

// only if req shows "complete" 
if (req.readyState == 4) { 
// only if "OK" 
if (req.status == 200) { 
// ...processing statements go here... 
response = req.responseXML.documentElement; 
method = response.getElementsByTagName('method')[0].firstChild.data; 
result = response.getElementsByTagName('result')[0].firstChild.data; 
eval(method + '(\'\', result)'); 
} else { 
alert("There was a problem retrieving the XML data:\n" + req.statusText); 


function checkName(input, response) 

if (response != ''){ 
// Response mode 
message = document.getElementById('nameCheckFailed'); 
if (response == '1'){ 
message.className = 'error'; 
alert('ok'); 
}else{ 
message.className = 'hidden';
alert('pas ok'); 

}else{ 
// Input mode 
url = 'scripts/checkUserName.php?q=' + input; 
loadXMLDoc(url); 

file checkusername.php 
<?php 
header('Content­Type: text/xml'); 

function nameInUse($q) 

if (isset($q)){ 
switch(strtolower($q)) 

case 'drew' : 
return '1'; 
break; 
case 'fred' : 
return '1'; 
break; 
default: 
return '0'; 

}else{ 
return '0'; 


?>
<?php echo '<?xml version="1.0" encoding="UTF­8" standalone="yes"?>'; ?> 
<response>
<method>checkName</method> 
<result> 
<?php 
echo nameInUse($_GET['q']); 
?>
</result> 
</response> 
and the form has the span and the style required, with the call to the checkName function... 

Sorry for my incompetence... and thanks if you can help. 

Fred. 

PS : if I make an error in the name of the file checkusername.php, I've got the alert fine... 
so I guess my problem is in the response part ..? 

l  XMLHTTP and java 
2005­10­07 13:17:44 vivekst  [Reply] 

Hi, 

Im working on Java Servlets. How can I use XMLHttp with Servlets 

l  XMLHTTP and java 
2005­10­07 12:19:56 vivekst  [Reply] 

Hi, 

Im working on Java Servlets. How can I use XMLHttp with Servlets 

l  Thanks for the very good introduction, however, ...
2005­09­12 20:32:01 peterhf  [Reply] 

when I run the app, the following message appears in the JavaScript Console and the app 
halts: 

Error: uncaught exception: Permission denied to create wrapper for object of class 
UnnamedClass 

I have gone over my html and php code and have some confidence that I have entered it 
correctly. 

I am using an iMac 10.3.9 and Firefox 1.0.6. 

Any thoughts? 

l  Nice analysis 
2005­09­05 07:50:29 Crefordw  [Reply] 

I'm glad to see your logical program and analysis in this article. 
Cre (http://www.cutegd.com/blog/) 

l  I need help =( 
2005­08­22 22:29:43 chris99  [Reply] 

This is a revolution, no more waiting for requests!! 
I am totally new to this and the example is not working for me =( can someone help me?? 
pleaseeeee 
I created a file called revolution.html on my web server and another revolution.php. 
Mozilla doesn't do anything after I leave(onblur) the input form and explorer gives me a 
javascript error(it can't detect the object of the input box after I leave the box it says 
"Object expected")
HTML BELOW 

<!DOCTYPE html PUBLIC "­//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1­transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml" > 
<head> 
<title>This is a revolution</title> 

<style type="text/css"> 
<!­­ 

span.hidden{ 
display: none; 

span.error{ 
display: inline; 
color: black; 
background­color: pink; 

­­­> 
</style> 

<SCRIPT LANGUAGE="JavaScript">
var req; 

function loadXMLDoc(url) 

// branch for native XMLHttpRequest object 
if (window.XMLHttpRequest) { 
req = new XMLHttpRequest(); 
req.onreadystatechange = processReqChange; 
req.open("GET", url, true); 
req.send(null); 
// branch for IE/Windows ActiveX version 
} else if (window.ActiveXObject) { 
req = new ActiveXObject("Microsoft.XMLHTTP"); 
if (req) { 
req.onreadystatechange = processReqChange; 
req.open("GET", url, true); 
req.send(); 


function processReqChange() 

// only if req shows "complete" 
if (req.readyState == 4) { 
// only if "OK" 
if (req.status == 200) { 
// ...processing statements go here... 
response = req.responseXML.documentElement; 

method = 
response.getElementsByTagName('method')[0].firstChild.data;
result = 
response.getElementsByTagName('result')[0].firstChild.data; 

eval(method + '(\'\', result)'); 
} else { 
alert("There was a problem retrieving the XML data:\n" + req.statusText); 

function checkName(input, response) 

if (response != ''){ 
// Response mode 
message = document.getElementById('nameCheckFailed'); 
if (response == 1){ 
message.className = 'error'; 
}else{ 
message.className = 'hidden'; 

}else{ 
// Input mode 
url = 
'http://revolution.php?q=' + input; 
loadXMLDoc(url); 


</SCRIPT>
</head> 

<BODY > 

<input id="username" name="username" type="text" 
onblur="checkName(this.value,'')" > 
<span class="hidden" id="nameCheckFailed"> 
This name is in use, please try another. 
</span> 

</body> 
</html> 

PHP file 

<?php 
header('Content­Type: text/xml'); 

function nameInUse($q) 

if (isset($q)){ 
switch(strtolower($q)) 

case 'drew' : 
return '1'; 
break; 
case 'fred' :
return '1'; 
break; 
default: 
return '0'; 

}else{ 
return '0'; 


?>
<?php echo '<?xml version="1.0" encoding="UTF­8" 
standalone="yes"?>'; ?> 
<response> 
<method>checkName</method> 
<result><?php 
echo nameInUse($_GET['q']) ?> 
</result> 
</response> 

¡  I need help =( 
2005­08­23 12:18:54 jering  [Reply] 

You are missing a closing curly in processReqChange. After fixing that, you will 
encounter error in checkName so url should be without http:// to access a relative 
php. 

For some of my data not readily available in XML, I just use text on both ends. You 
can check Content­type in processReqChange and use responseText instead of 
responseXML. 
­­J
l  DWR 
2005­07­18 16:03:54 dmeany1  [Reply] 

This guy has done all the hard work with XMLHttpRequest() for you....if you use java. 

http://www.getahead.ltd.uk/dwr/ 

l  Microsoft.XMLHTTP vs. XMLHttpRequest 
2005­07­04 06:16:42 chrisward1  [Reply] 

This may be blinding obvious to everyone else ­ but I'd like to emphasise the importance of 
setting the header content type to "text/xml" if you are using the ActiveX XMLHTTP and 
want to get your hands on the DOM version of the returned XML. 

I've spent two days trying to track down why using Opera (using XMLHttpRequest) 
worked but using IE 6 (using Microsoft.XMLHTTP) didn't. 

My problem was that I'd done a copy/paste of an old servlet for my test and it set the 
content type to "text/html". In Opera this got through and the responeXML property 
returned with the expected DOM object, however IE6 did return the text (in the 
responseText property) but had a null responseXML. 

So don't forget... 

res.setContentType("text/xml"); 

... hope this helps someone out there!
¡  Microsoft.XMLHTTP vs. XMLHttpRequest 
2005­11­04 08:31:59 Gdawg  [Reply] 

I concur with this post 100%, it cost me alot of wasted time trying to get XML to 
work in IE. 

If you want Cross­Browser, make sure that header is sent with your XML doc. 

¡  Microsoft.XMLHTTP vs. XMLHttpRequest 
2005­08­05 09:05:39 js9777  [Reply] 

l  char encoding problem 
2005­06­27 05:24:29 saidka  [Reply] 

when requested server through XMLHttpRequest [open("GET","scr.php? 
par="+document.form.input.value,false)] i got (sorry for my english) next difficulty: 
FireFox converts values of form elements to utf­8 and sends as utf­8 when page opened 
directly by typing URL, otherwise (opened through link) sends as utf­8 without converting, 
ie6 don't convert at all. 

l  responseXML lost across windows? 
2005­06­09 10:42:10 JJG  [Reply]
I am trying to use XMLHttpRequest in a client­side firefox plugin. I want to open a sign­in 
dialog, and then use the user's input to send a GET request to the server for authorization. 

Unfortunately, the XMLHttpRequest's responseXML always comes in null if I let the 
dialog close before the server response is received. The call is being made on a global 
object which is created in the main plugin overlay, to which the request is attached. The 
actual request object is maintained (I verified that it was the same by setting the value of a 
property when the request is created and checking it in my request change listener), but the 
responseXML is nulled out. If I put in an alert that prevents the dialog from closing before 
the response is received, all is well. 

I tried the theadsafe version posted here, but no dice. My only guess is that the 
responseXML object is temporarily placed on the current window during processing, and it 
is getting lost when my dialog gets destroyed. Any insight, suggestions for workarounds, 
or examples of similar code would be appreciated. 

l  non­active x implementation for IE? 
2005­06­09 01:27:13 akrinsky  [Reply] 

What if your client doesn't want to enable ActiveX scripting? 

req= new ActiveXObject("Microsoft.XMLHTTP"); 

Has anyone implemented a pure DHTML/javascript version of this library for IE? 

¡  non­active x implementation for IE? 
2005­09­14 07:59:46 jjcorra  [Reply] 

yes 

http://weblogs.asp.net/mschwarz/archive/2005/08/24/423495.aspx
l  A threadsafe implementation for XMLHTTPRequest 
2005­05­27 12:48:37 brockweaver  [Reply] 

One of the things that pops out at most developers is the thread safety issues of the 
example code. While the example works fine for testing, the very nature of programming 
web apps in this manner means it is *extremely* likely multiple requests will be issued 
concurrently. 

The following is thread­safe code to do just that. I've used the Ajax moniker, as that is what 
a lot of people call this technique. Personally, I don't care if they call it furrycatofdeath, as 
long as it works. :) 

Essentially, this code uses a technique called inner functions. These are useful in this 
situation because the variables declared on the outer function are available to the inner 
function ­­ and do not fall out of scope until *after* the inner function has been executed. 
Since the request and callback variables (which contain function pointers to the good stuff) 
are declared locally, each call to the ajaxSend function creates a new copy, so the previous 
one is left intact. 

A great discussion and analysis of this methodology (and other similar methodologies) is 
described in detail at 
http://jibbering.com/faq/faq_notes/closures.html 

Mind you, I found this via a Google search and I am completely unrelated with its content, 
so that url may change without my knowledge. Hopefully it will not, as it is a very clear 
and well written article! 

At any rate, the source follows. If you have issues with it, please let me know, as I haven't 
had a chance to test many platforms yet. Thank you!
// threadsafe asynchronous XMLHTTPRequest code 
function ajaxSend(url, callback){ 

// we use a javascript feature here called "inner functions" 
// using these means the local variables retain their values after the outer function 
// has returned. this is useful for thread safety, so 
// reassigning the onreadystatechange function doesn't stomp over earlier requests. 

function ajaxBindCallback(){ 
if (ajaxRequest.readyState == 4) { 
if (ajaxRequest.status == 200) { 
if (ajaxCallback){ 
ajaxCallback(ajaxRequest.responseXML); 
} else { 
alert('no callback defined'); 

} else { 
alert("There was a problem retrieving the xml data:\n" + ajaxRequest.status + ":\t" + 
ajaxRequest.statusText + "\n" + ajaxRequest.responseText); 


// use a local variable to hold our request and callback until the inner function is called... 
var ajaxRequest = null; 
var ajaxCallback = callback; 

// bind our callback then hit the server... 
if (window.XMLHttpRequest) { 
// moz et al 
ajaxRequest = new XMLHttpRequest();
ajaxRequest.onreadystatechange = ajaxBindCallback; 
ajaxRequest.open("GET", url, true); 
ajaxRequest.send(null); 
} else if (window.ActiveXObject) { 
// ie 
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP"); 
if (ajaxRequest) { 
ajaxRequest.onreadystatechange = ajaxBindCallback; 
ajaxRequest.open("GET", url, true); 
ajaxRequest.send(); 

¡  A threadsafe implementation for XMLHTTPRequest 
2005­06­06 12:42:15 GoatMonkey  [Reply] 

Can you explain how to get data back from this function with the inner function? If I 
wanted to use this function to send different URLs to it and get back either XML or 
plain text as a response in a variable. 

When I tried it, it seemed to work, but I had to modify the function to just write out 
the xml to the screen within the inner function. It seems like it should be returned as 
a variable to whereever it was called from. 

Thanks. 

n  A threadsafe implementation for XMLHTTPRequest
2005­08­17 19:28:23 dsphitz  [Reply] 

n  A threadsafe implementation for XMLHTTPRequest 
2005­08­17 19:25:10 dsphitz  [Reply] 

I second that, I don't see how this is useful if you can't get the data out ... 

n  A threadsafe implementation for XMLHTTPRequest 
2005­08­05 09:08:18 js9777  [Reply] 

l  Why does the method take input and response? 
2005­05­17 11:58:36 tieTYT  [Reply] 

I still don't understand why this function: 
function checkName(input, response) 
needed to take an input and a response. 

Why couldn't it be broken up into 2 functions? 

¡  Why does the method take input and response? 
2005­05­17 12:20:44 drewmclellan  [Reply] 

You're right. It could be two functions. Making it one was simply a design choice. If 
you were to have lots of different actions on a page resulting in an xmlhttprequest 
call, it can be a lot tidier just to have a single function to handle each action. 

If using two functions works better for you, there's no reason not to do it that way. 

l  Great introduction, now what about refreshing lists? 
2005­05­11 08:10:09 acidbox  [Reply]
I found this article to be a great introduction to how the whole XML/JS interaction works. 
My question is, if I used this to insert a record into a database using PHP/MySQL, how 
would I go about refreshing a list of records with the newly inserted data appended to the 
list? 

¡  Great introduction, now what about refreshing lists? 
2005­05­11 12:52:31 sunnyO5  [Reply] 

How about the method described in "Data the other way 
round" (http://www.xml.com/cs/user/view/cs_msg/2750)? 

l  Knowledge Base Application 
2005­05­06 08:07:25 Julian Turner  [Reply] 

I have produced a simple example of AJAX use for a knowledge base. 

www.baconbutty.com 

In terms of history, my web page maintains the history, although it loses it when the 
browser is closed. 

l  Chess GUI 
2005­04­24 04:22:46 JOlsen  [Reply] 

Nice tutorial. 

I implemented this chess GUI after reading your article. 

http://www.JesperOlsen.Net/PChess/
Cheers 
Jesper 

l  Data the other way round 
2005­04­21 11:35:17 nGear  [Reply] 

This is data pulled by the client from the server. 
Is there a way to push data from the server to the client? 
(Without the client polling the server..) 
i.e. update the client without any requests from the client itself. 

¡  Data the other way round 
2005­04­30 22:56:19 Mahsood  [Reply] 

for example i want to have the stock market feed on my website.......... 

n  Data the other way round 
2005­05­03 09:55:58 sunnyO5  [Reply] 

Well, you can use polling: contact the server at regular intervals, say 1 minute, 
assuming some other process updates the stock information. If the server 
detects that there is a change (elaboration below), then it sends a new 
information in response; otherwise, old one stays on the user's screen. 

One way the server could detect a change is if you also send a time stamp 
(hidden input field could store this) when the user first browses the web page. 
The time stamp would have the time when the server information was last 
changed. So when you refresh stock information after a specified amount of 
interval, the time stamp is sent to the server, which compares it to the time 
stamp that it (server) has. If the server version is newer, then new stock is sent; 
else nothing. 

I haven't implemented this in practice, but this should work.
¡  Data the other way round 
2005­04­25 00:32:44 sunnyO5  [Reply] 

For most applications (I can think of), polling is adequate. What kind of applications 
do you have in mind? 

l  Concerns 
2005­04­03 07:00:05 sunnyO5  [Reply] 

I am excited about the possible applications of XMLHttpRequest Object but I have some 
concerns: 

1) Using XMLHttpRequest Object can save a lot of bandwidth but does it support caching 
of webpages in the browser? Webpages using XMLHttpRequest Object seem to loose the 
browser's history features; you can't use the Go back and forward buttons. Like in the 
Apple's example 
(http://developer.apple.com/internet/webcontent/XMLHttpRequestExample/example.html), 
one has to make the choices again to view the information. So can't view the information 
offline. 

2) In the Google Suggest example, for each key press a request is sent to the server. So if 
you have 50 users typing an average of 10 letters, you have more than 500 requests sent to 
the server. Is this a huge concern for developing applications with this sort of feature (like 
dynamic function lookup on php.net)? 

Nevertheless, XMLHttpRequest Object promises a better interaction with the user. 
Thanks. 

¡  Help please 
2005­04­07 17:23:52 rkhlin  [Reply] 

XMLHTTPRequest is really fantastic to use.
But I am having a problem at the moment. 
When I wrote a JS function which calls 1st url to change one div, then it calls 
another url to change another div. 
However only the 2nd url call is executed, the function simply ignore the 1st call (so 
only div2 got updated). 
Is there a way I can make sure it get the 1st url done and then the 2nd url 
sequentially, Since no multi­threaded is supported in current JS. 
I used window.setTimeout(1000); in between 2 calls, then it wont go at all. 

Please help! 

n  Help please 
2005­04­07 23:22:37 rkhlin  [Reply] 

Solved myself, use setTimeOut(func2,msec); 

n  Help please 
2005­04­21 11:27:32 nGear  [Reply] 

The second one is probably not coming through, because you donot wait 
for the first request to finish. (i.e. the readystate did not get to 4 in the 
eventhandler) 
So your current solution won't work if the server takes a long time to 
serve the xml for the first div. 

n  Help please 
2005­05­27 12:52:36 brockweaver  [Reply] 

See the response I just posted for a simple solution to this thread 
safety problem. I didn't notice this thread before I posted, sorry 
about that. 

The name of my post is something like "A threadsafe 
implementation of XMLHTTPRequest"
¡  Concerns 
2005­04­05 12:22:37 pandelic  [Reply] 

Google Suggest doesn't submit on each keystroke, but rather every set interval, 
which reduces the number of requests for fast typists but still provides good response 
time. 

l  Problem 
2005­03­24 14:35:49 Goonie  [Reply] 

I'd like to load an XML/HTML fragment from the server and replace a node in the 
document by that fragment. That way, I could periodically refresh a specific region of the 
page. 

Here is what I'm doing in the readyStateChange handler: 

e = document.getElementById('fragment'); 
e.parentNode.replaceChild(req.responseXML.firstChild, e); 

Unfortunately, an XML fragment that is fetched via XMLHttpRequest is not accepted as 
valid HTML by Gecko/Firefox: It only shows up as text­only, without any formatting. 
What's worse, getElementById() does not locate my fragment after it has been replaced 
once. 

Is it possible to convert an XML node to an HTML element/node before insertion into the 
DOM? 

Are there any good books on the matter that go well beyond this article?
Regards, 

Andreas 

¡  Problem 
2005­04­07 23:21:31 rkhlin  [Reply] 

Wondering anyone knows how to solve this: 
When I made a XMLHttpRequest, the returning HTML not only have HTML also 
some javascript functions. However the Caller page don't seem to understand the 
new javascript functions have been loaded in. So is there anyway we can force the 
Caller to understand the new javascript functions??? 

¡  Problem 
2005­04­06 23:00:56 mdchaney  [Reply] 

<blockquote>I'd like to load an XML/HTML fragment from the server and replace a 
node in the document by that fragment. That way, I could periodically refresh a 
specific region of the page.</blockquote> 

Use the "responseText" attribute to get at the html as text. Then use "innerHTML" to 
place it where you want it. 

If you don't need HTML, but you're just putting text in, you might also use the 
simple DOM methods to create a text node, stick it on a paragraph, then put the 
paragraph where you want it. Put your replaceable text in a div with a unique id so 
you can find it easily, clean it out and change the text. 

l  I realize that I'm on XML.com, but.... 
2005­03­23 07:09:49 mdchaney  [Reply] 

Please don't use XML for such a simple request. Actually, I'm not convinced that XML is
the best method for sending any data to JavaScript. I do a lot of work with 
XMLHTTPRequest, and I simply use the standard JavaScript object literal and array literal 
notations. 

Now, I know the above is a simple demonstration, but for a simple flag response you need 
to return only a 1 or 0. To keep with the example, though, you can return a JS object: 

{ method: 'checkName', result: 1 }; 

Then, the function is simplified: 
function processReqChange() 

// only if req shows "complete" 
if (req.readyState == 4) { 
// only if "OK" 
if (req.status == 200) { 
// ...processing statements go here... 

­­> eval('response = '+req.responseText); 

eval(response.method + '(' + response.result + ');'); 
} else { 
alert("There was a problem retrieving the XML data:\n" + req.statusText); 


Obviously, for such a simple example there's little gain. But imagine trying to traverse an 
entire DOM tree for a large document. Using literals, you can create native JS objects and 
use the much simpler constructs such as "for/in" to manipulate the data. You can also
directly address known data, as shown above. 

Make the choice between this: 

response.method 

or this: 

response.getElementsByTagName('method')[0].firstChild.data; 

It also probably goes without saying, but the backend code is also greatly simplified by not 
having to create an XML document. 

¡  I realize that I'm on XML.com, but.... 
2005­04­05 17:31:50 emdee1  [Reply] 

> Please don't use XML for such a simple request. Actually, I'm not convinced that 
XML is the best method for sending any data to JavaScript. I do a lot of work with 
XMLHTTPRequest, and I simply use the standard JavaScript object literal and array 
literal notations. 

That's great... until you want to reuse the logic for something that isn't JavaScript on 
the otherside. This is exactly the type of thing that XML is for. 

n  I realize that I'm on XML.com, but.... 
2005­04­06 23:06:21 mdchaney  [Reply] 

That's great... until you want to reuse the logic for something that isn't 
JavaScript on the otherside. This is exactly the type of thing that XML is for.
It's easier to parse the JavaScript object literal notation than it is to parse XML. 
Also, there are various libraries already available to do so, check 
www.json.org for more details. 

Given the simplification of using a simple object over using DOM methods to 
get at your data (again: "response.method" vs. 
"response.getElementsByTagName('method')[0].firstChild.data") it just seems 
unlikely that bloating your code and making it unreadable on the JavaScript 
side in the off chance you'll want to reuse this data elsewhere is the way to go. 
Particularly given that using DOM methods in any language is likely to be as 
painful. 

n  I realize that I'm on XML.com, but.... 
2005­04­26 15:58:43 krufty  [Reply] 

incidentally, a programmer mistake by parsing literals on a data feed 
could result in something like 

If your datafeed contained: 

alert("oops, thought i took this debug line out of here"); 

you'd execute it. The datafeed cannot accidentally cause the calling page 
to execute javascript code unless you eval the data coming back. 

n  I realize that I'm on XML.com, but.... 
2005­04­26 15:54:22 krufty  [Reply] 

I think the point is that if you have relatively complex data being 
returned, and relatively complex data being parsed, its easier to absorb 
the cost on the hardware side than the development side.
Sticking to XML when you can afford to makes it easier to validate 
common logic between different languages (think C, C++) .. if you have 
diff data formats, and diff parsers, and diff developers working on them, 
you're bound to have more problems than if you data feed is built from a 
consistant, human readable format. Sure, XML is expensive, but thats 
the whole concept of data abstraction. 

¡  I realize that I'm on XML.com, but.... 
2005­03­29 22:32:16 w_laks  [Reply] 

I got a question. How exactly do you return JS Objects in the response? What should 
be the document type. My server side php code is simply this: 
<?php 
echo "{ name: 'Lakshmi' }"; 
?>
This works but Mozilla keeps spinning forever I guess because it still expects more 
content or something. IE does not spin and on Opera this does not work at all 
presumably for lack of a HttpRequest object. 

n  I realize that I'm on XML.com, but.... 
2005­04­01 07:04:20 mdchaney  [Reply] 

How exactly do you return JS Objects in the response? What should be the 
document type? 

Your code looks fine. Just use "text/plain" for the document type. When I do 
this locally, I simply use ".txt" files. 

I just finished a simple application for a client which has a 2.5M data file, the 
entirety of which is a humongous JS object literal. Loading it locally, 
including file reading, parsing, and object creation, takes about 2­3 seconds on 
my computer here (1.8GHz with plenty of RAM). The application is
incredibly fast, particularly for dealing with a lot of data. 

Using XML DOM in such an application would bloat the data file by at least 
25­30% (just looking at adding end tags), and bloat the code by an obnoxious 
amount by having to deal with DOM instead of simple object properties. 

¡  I realize that I'm on XML.com, but.... 
2005­03­29 22:17:47 w_laks  [Reply] 

I tried your approach returning a JS Object within curly braces and it works. I am no 
fan of long­winded Java­style get/set methods either ... 

l  Working Example 
2005­03­14 03:28:27 Julian Turner  [Reply] 

If anyone is interested, I have used the XMLHTTP Request as the back­bone to my website 
www.baconbutty.com. 

The database/index for the web site is a series of linked XML flat files currently, which I 
access using a simple RegExp/String based XML reader I have written, to save server 
overheads in parsing the XML database. 

¡  Working Example 
2005­05­21 16:14:08 issue9mm  [Reply] 

Yeah, but your front­end interface seems to be written lazily. Make it work in 
Firefox and I might bother the next time I see the link. Until then, stop trolling for 
hits. 

l  The correct code 
2005­03­02 12:29:03 xmL  [Reply] 

You can find it here 
http://www.xmlhttprequest.net/forum/viewtopic.php?p=9#9
Fixed some bugs for this good example. 

xmL 

l  Re: Example 
2005­02­24 14:16:03 rk9728  [Reply] 

Does anyone have a working example that we could see online? It's a bit frustrating to see 
these great articles but not the actual *demo* itself :0 

¡  Re: Example 
2005­02­25 00:28:52 djaekimaar  [Reply] 

I would like to echo that point. I have tried to get this working several times and had 
no luck. I have a MS version working elsewhere but would rather use this tech. I am 
using Firefox 1.0 which I think should be ok. 
thanks 

n  Re: Example 
2005­02­26 01:06:41 djaekimaar  [Reply] 

To anyone else, if you follow the Apple link above it takes you to an example, 
a little more complicated than above, suing iTunes RSS, but works very well. 

l  Good Article! 
2005­02­19 18:08:08 DanielBThurman  [Reply] 

I have pretty much followed your article and converted the code presented to use ASP code 
and it works well. I do have one annoying issue.
When the name is typed and the onblur event is fired, a popup dialog on IE that warns the 
user with this message: 'This page is accessing information that is not under its control. 
This poses a security risk. Do you want to continue?' 

Is there some way to block this message or does all browsers have this sort of thing built 
in? 

The other question is, what about passing passwords ­ NON­SECURELY ­ using this 


code? I assume that this is easily handled via https:// connection, bypassing the need to do 
client­side encryption. 

Other than that ­­ server­side processing is done without a round­trip page refresh and there 
is no noticeable client­side renderering and the response appears quickly, which is 
impressive. 

Dan Thurman 

¡  Good Article! 
2005­02­28 10:18:17 jgraf  [Reply] 

This is a warning about cross­site scripting. Microsoft answers this same question in 
this Q&A (http://msdn.microsoft.com/msdnmag/issues/02/06/web/). The best 
solution is to have your web page and the XMLHTTPRequest URL in the same 
domain. 

l  XMLHTTP is Good but Needs WS­Security 
2005­02­18 13:40:55 ErikJ  [Reply] 

We use XMLHTTPRequest to send/receive SOAP in a couple of products we ship. Two 
other useful things we leverage: The Windows version knows how to handle NT 
Challenge/Response, so you can call sites running under Windows Integrated Security 
transparently. It also supports HTTP 1.1 compression, so you can GZIP your payload on
the server (SOAP usually compresses well). 

But what we really need is the ability to sign/encrpyt messages using WS­Security 
standards. In Microsoft's case, version 5 of the MSXML parser kit (which contains 
XMLHTTPRequest) has a few features, but you only get that version with Office 2003. 
Version 6 is coming, but I've heard Microsoft may have to pull out the signing/encrypting 
functions at least for now. 

I haven't reviewed Mozilla/Safari support for WS­Security yet, but having that 
functionality in genreal would be quite helpful. 

l  micro applet can work as well 
2005­02­16 09:59:42 jseller  [Reply] 

Reminds me of a project in which we ended up using a very small applet working in the 
background to co­ordinate between ecmascript in the browser (using 
com.netscape.javascript.*) and interacting with the server through a persistent connection 
(using java.net.*) No need from browser refresh for small updates, it handled the UI event 
handling and was less than 10kb. This was around 1998 so it's kind of fuzzy, but I 
remember it worked well. 
I definitely remember that it seemed sort of weird at the time getting the Netscape 
javascript classes to work in Internet Explorer on the Mac os9. 

l  DOM 3 & simplification 
2005­02­14 05:45:48 JimDabell  [Reply] 

Er, DOM 3 Load and Save isn't a "proposed specification". It was released as a 
Recommendation in April 2004 and has been implemented by multiple browsers already. 
It's never going to be as well­supported as XMLHttpRequest because, hey, Internet 
Explorer. that doesn't mean it isn't a stable, deployed specification though.
You can simplify the instantiation of the XMLHttpRequest object by simply including a 
little bit of generic Javascript before you use the native object method: 

if (typeof XMLHttpRequest != "object") { 
function XMLHttpRequest() { 
return new ActiveXObject("Microsoft.XMLHTTP"); 

That way you can simply call new XMLHttpRequest() for Internet Explorer in the same 
way that you do for all the other browsers. 

¡  DOM 3 & simplification 
2005­02­28 09:45:56 Lars Huttar  [Reply] 

Thanks for this helpful tip. Especially good to know that XMLHttpRequest is part of 
a public standard. 

But you still have to do branching code when you *use* the XMLHttpRequest 
object, right? E.g. looking at the sample code in the article, req.send() apparently 
takes no argument in IE but takes a "null" argument in other browsers? 

I guess you could handle this by writing more js helper functions. 

n  DOM 3 & simplification 
2005­03­04 02:34:59 JimDabell  [Reply] 

Actually, I take back what I said about DOM3LS. The "load" part of 
DOM3LS was present in drafts, but didn't make it to the final 
recommendation. Mozilla's documentation still lists it as part of DOM3LS
though, and Gecko/KHTML/Opera all implement it according to the draft 
description. 

https://bugzilla.mozilla.org/show_bug.cgi?id=284737 

While the MSDN documentation remains ambiguous with respect to what 
happens when you pass null for the request body, I haven't found any problem 
with doing so in practice. 

http://msdn.microsoft.com/library/default.asp?url=/library/en­ 
us/xmlsdk/html/xmmthsendixmlhttprequest.asp 

l  XMLHTTPRequest and Javascript to create web applications with very dynamic, smooth 
interfaces. 
2005­02­14 05:44:52 anand123  [Reply] 

I just had a doubt, will this method work if Javascript is disabled on the client side ?? also 
if the client does not have the latest version of MSXMLDOM (in case of IE) ?? Thanks in 
advance. 

¡  XMLHTTPRequest and Javascript to create web applications with very dynamic, 
smooth interfaces. 
2005­02­14 05:47:35 JimDabell  [Reply] 

No, this won't work if Javascript is unavailable on the client. 

http://jibbering.com/2002/4/httprequest.html has a more complex method that 
handles different versions of MSXML.
l  Coldfusion Server Script 
2005­02­11 08:05:06 makalu  [Reply] 

I re­wrote the server script in coldfusion to see if I could get it working on my cfmx box, 
here's the code from that, if anyone is interested... 

<cfcontent type="text/xml" reset="yes"> 
<cfscript> 
function nameInUse(q) 

if (isdefined("q")){ 
switch(lcase(q)) 

case 'drew': { 
return '1'; 
break; 

case 'fred': { 
return '1'; 
break; 

default: 
return '0'; 

}else 
return '0'; 

</cfscript> 
<?xml version="1.0" encoding="UTF­8" standalone="yes"?> 
<response> 
<method>checkName</method> 
<cfoutput><result>#nameInUse(url.q)#</result></cfoutput> 
</response>
¡  Coldfusion Server Script 
2005­04­25 14:10:04 Kanjoos  [Reply] 

I could not make it work in coldfusion. I keyed in exactly. 

I had two problems : 

req.onsteadystatechange = processReqChange; 

this does not call the function, it gives javascript error. It works when I change the 
above statement to 

req.onsteadystatechange = processReqChange(); 

But as a whole my script does not work. 

My email address is kanjoossulekha@yahoo.com, can you guys send me the 
working programs ?? 

Thanks, 
Kanjoos 

¡  Coldfusion Server Script 
2005­04­01 10:10:08 sk401k  [Reply] 

That looks cool. I really like the concept and i can vision it and see how far we can 
go to create more user friendly applicatoins but some how this example is failing in 
NS 7.2. It really irritates to see compatibility issues.
Thanks 
SK401k 

¡  Coldfusion Server Script 
2005­02­14 11:14:19 Sidvorak  [Reply] 

I had problems using the coldfusion code presented due to the <?xml?> declaration 
not being on the first line of the returned document. If whitespace suppression is not 
turned on in the Administrator you will have to use something like this. Notice that 
there is no hard return after the <cfcontent> tag. 

<cfprocessingdirective suppresswhitespace="yes"> 
<cfcontent type="text/xml" reset="yes"><?xml version="1.0" encoding="UTF­8" 
standalone="yes"?> 
<response> 
<method>checkName</method> 
<cfoutput><result>#nameInUse(url.q)#</result></cfoutput> 
</response> 

<cfscript> 
function nameInUse(q) 

if (isdefined("q")){ 
switch(lcase(q)) 

case 'drew': { 
return '1'; 
break; 

case 'fred': { 
return '1'; 
break; 
}
default: 
return '0'; 

}else 
return '0'; 

</cfscript></cfprocessingdirective> 

n  Coldfusion Server Script 
2005­02­16 05:41:31 makalu  [Reply] 

Good point Sidvorak...sorry to leave that out. 

l  XSL 
2005­02­11 02:13:32 redben  [Reply] 

I have been working in this style (XML Javascript XSL) for about 2 years now but only 
with ie. Mozilla had little xml support at that time. I know that now it fully does, and i'm 
happy for that :) since it will unlock me from developping for ms ie. 
But there is one thing a still don't know how is mozilla's XSL implementation ? somebody 
ever tried it ? i'd really like to go crossbrowser again. 

¡  XSL and XML in Mozilla 
2005­02­11 05:00:33 Martin_Honnen  [Reply] 

Mozilla 1.0 <http://www.mozilla.org/releases/mozilla1.0.html> was released June 5, 
2002 and already had support for XMLHttpRequest. 
As for XSLT 1.0 support, it is also there since Mozilla 1.0 though scripting it is 
supported since 1.2 I think. See the FAQ for details and differences if you want to do 
client­side XSLT in both IE/Win and Mozilla: 
<http://www.mozilla.org/projects/xslt/faq.html> 

There is also the Sarissa project: <http://sarissa.sourceforge.net/doc/> which aims to 
ease the task of XML/XMLHttpRequest/XPath/XSLT scripting across browsers.
l  Very nice article 
2005­02­10 18:47:27 robhudson  [Reply] 

I'd like to see more like this as I think this is a technology that's taking off. Maybe more 
complicated XML requests and responses, how to send data with POST, etc. 

¡  Very nice article 
2005­03­13 09:33:34 nicolash  [Reply] 

to POST instead of GET: 
xmlHttpRequestInitialize(); 
req.onreadystatechange = xmlHttpRequestProcessReqChange; 
req.open('POST', self.location.pathname); 
req.setRequestHeader('Content­Type', 'application/x­www­form­urlencoded'); 
req.send('Whatevername=wahatevervalue&Whatevername2=wahatevervalue2'); 

you need to set the header 
and put the data into the req.send. 
(obviously better to fill the req.send by a function instead of hardcoding it!) 

l  Don't forget www in the URL 
2005­02­10 09:29:16 ideawire_bb  [Reply] 

Good article, easy to follow. 

For some reason, in all browsers I tested (IE 6 Win, Safari Mac, Firefox Mac / Win) it only 
works if you utilize the root url, ie: 

http://www.domain.com/form.html 

The script simply won't work if you try and access it this way:
http://domain.com/form.html 

Hope this saves someone the time and frustration I experienced. 

¡  Don't forget www in the URL 
2005­02­12 07:53:25 ErnNJ  [Reply] 

For security reasons the URL must be fully qualified. I put the page in the same 
directory and did this: 

url = 'checkUserName.php?q=' + input; 

I am also curios about the “response == ‘1’” not working. I have always found 
JavaScript to be rather lax when it comes to data types and don’t understand why it 
is picky here. If anyone can explain it would be appreciated. 

n  Don't forget www in the URL 
2005­11­01 04:25:02 x3  [Reply] 

This happens because of security reasons and 
in IE (in other browsers i havent tested) it can be solved change 
window.domain property 
It can be change only to up level, so 
when page is loaded as "http://www.domain.com/form.html" the domain 
property contains string "www.domain.com" and changing it to "domain.com" 
will enable javascript to load files by url "http://domain.com/form.html" 
and other in this domain
(P.S. sorry for my english) 

l  Nice, but one small error 
2005­02­09 23:53:32 dzac  [Reply] 

I tried the example, and at least in Safari and FireFox 1.0 on the Mac, the function 
'checkName' should read: 

... 
if (response == 1) 
... 

rather than: 

if (response == '1') 

(note the quotes). 

With that change everything worked as advertised. 

¡  Nice, but one small error 
2005­09­09 06:08:34 PravinNirmal  [Reply] 

I am loading one HTML page content in a div tag, using XMLHTTP. But thsi 
content is having the Javascript function and one submit button calling this 
Javascript. Now what happens, when we load the content in the div, and then click 
on this Button, it does nto recognise the Javascript function and says 'Object 
Undefined' . This means the XMLHTTP loaded the content as notmal text or and not
as HTML or JS, hence that function is not found by browser. Please suggest if you 
are having any solutions. 

n  Nice, but one small error 
2005­10­26 07:40:08 Tien­Chih.Wang  [Reply] 

I did same thing, but that javascript function works fine in my case. 

I have another question about the xmlhttp responseText update. I retrieve two 
xmlhttp objects simultaneously. 
I try to keep one xmlhttp.responseText as static 
InnerHtml and still updating the other(Using setTimeout() ..). How to achieve 
this? 

Regards, 

Tien­Chih Wang 

­­­
Meta Job Search Engine 
http://www.onsofts.com/deepJobSearch.jsp 

Contact Us |  Our Mission |  Privacy Policy |  Advertise With Us |  Site Help | Submissions Guidelines 


Copyright © 2005 O'Reilly Media, Inc.

Potrebbero piacerti anche