Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AJAX request status returns 0

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);
}
}
}
like image 366
John Stimac Avatar asked Jun 01 '26 14:06

John Stimac


2 Answers

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.

like image 146
Jerome Avatar answered Jun 04 '26 13:06

Jerome


jquery.com You 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.

like image 31
tvanfosson Avatar answered Jun 04 '26 11:06

tvanfosson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!