views:

300

answers:

2

when i make a AJAX request with this code, it returns the status as 0. what did i do wrong? Also, this code is only designed to work in Firefox for various reasons.

var ajax;

function connectToOtherServer(server,port,userid,password){

ajax=new XMLHttpRequest();
ajax.onreadystatechange=validateConnection;

params='userid='+encodeURIComponent(userid)+'&password='+encodeURIComponent(password);

alert('http://'+server+':'+port+'/ok.txt');

ajax.open('POST','http://'+server+':'+port+'/ok.txt',true);

ajax.setRequestHeader("Content-type","application/x-www-form-urlencoded");
ajax.setRequestHeader("Content-length",params.length);
ajax.setRequestHeader("Connection","close");

ajax.send(params);

}

function validateConnection(){
if(ajax.readyState===4){
if(ajax.status===200){

alert(ajax.responseText);

}else{
alert(ajax.status);
}
}
}
+2  A: 

If you try to connect to another server, the same origin policy will stop you:

The term "origin" is defined using the domain name, application layer protocol, and (in most browsers) TCP port of the HTML document running the script. Two resources are considered to be of the same origin if and only if all these values are exactly the same.

Jerome
huh?like, I can only use ajax to connect to the same url as the page i'm on?
Jcubed
No, same server/port: see http://en.wikipedia.org/wiki/Same_origin_policy
Jerome
ok, is there anyway i can get around this?
Jcubed
Use the method explained by tvanfosson, or use a proxy script on your server.
Jerome
A: 

link textYou can only connect to another server if you use JSONP and a callback. The other server will need to support the JSONP/callback mechanism. This method involves creating a new script tag then having the remote server return the callback code into this script tag. Look at the jQuery source code (or simply use it) to see it handles JSONP.

The basic idea is to create a script tag with the source as the remote URL. The remote method returns a "script" containing a function call using the callback and the resultant JSON data.

tvanfosson