views:

113

answers:

2
+1  Q: 

weird AJAX error

why won't this work?

function login(){

if(window.XMLHttpRequest){
ajax=new XMLHttpRequest();
}else if(window.ActiveXObject){
ajax=new ActiveXObject("Microsoft.XMLHTTP");
}

ajax.onreadystatechange=validatelogin;

params='name='+escape(document.getElementById('name').value)+'&pass='+escape(document.getElementById('pass').value);

/*IT FAILS HERE*/
ajax.setRequestHeader("Content-type","application/x-www-form-urlencoded"); 

ajax.setRequestHeader("Content-length",params.length);
ajax.setRequestHeader("Connection","close");

ajax.open('POST','login.php?login=true',true);
ajax.send(params);

}

function validatelogin(){
if(ajax.readyState===4){
if(ajax.status===200){
alert(ajax.responseText);
exit(0);
}else{
alert("FAIL!!!!!");
}
}
}

Firefox error consol complains about

Error: Component returned failure code: 0x80004005 (NS_ERROR_FAILURE) [nsIXMLHttpRequest.setRequestHeader]

+4  A: 

It happened to me once.

You must call the "open" method before you call "setRequestHeader"

w35l3y
woah! sweetness! thanks!
Jcubed
+2  A: 

In case it's useful, all of that code you have written could be replaced by this tiny bit of jQuery script:

$(document).ready(function() {
    $.post('login.php?login=true', {name: $('#name'), pass: $('#pass')}, 
            function(response) {
                alert(response);
            }
    );
});

See jQuery.post

karim79
+1: less code => less opportunity for error
Greg Hewgill
Less opportunity maybe, but there's still a missing-close-quote error!
bobince
@bobince - You could have fixed that you know. Thanks for the snarky comment.
karim79
no one asked for a jQuery solution...
Hippo
@Hippo - The beginning of my answer says 'In case it's useful', and not 'this is your solution'. Thanks for down-voting.
karim79