My AJAX script wasn’t working before (it wouldn’t send data) but setting the request headers solve the problem. It’s great that it works but I want to understand why they are needed for it to work. Thanks 🙂
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
javascript
function request(elm, type, url, str, fn) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange=function()
{
if (xhr.readyState==4 && xhr.status==200)
{
if (!fn) elm.innerHTML=xhr.responseText;
else fn(xhr);
}
}
xhr.open(type, url, true);
//yay it works with this :-)
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(str);
}
var form = document.getElementById("form_login")
var btnLogin = form.getElementsByClassName("btn")[0];
addEvent(btnLogin, "click", function(e)
{
preventDefault(e);
var post ="",input,inputs = form.getElementsByClassName("input");
for (var i=0, l=inputs.length; i<l; i++)
{
input = inputs[i].getElementsByTagName("input")[0];
post += input.name + "=" + encodeURI(input.value) + "&";
}
post = post.substr(0,post.length-1);
var help = form.getElementsByClassName("help")[0];
request(help, "POST", "user/login-exe.php?dt='" + new Date() + "'", post);
});
and if its all valid it will log the user in that bit isn’t shown though.
This isn’t strictly a requirement, PHP will just automatically populate
$_POSTwhen the request specifies content-type of"application/x-www-form-urlencoded".You can still get access to the values with
In fact, any server should allow you to get access to the raw request body.
The other headers are not doing anything, the browser will not allow you to change them as is specified. If you were able to change them, you would probably report the wrong
Content-Lengtheverytime. Because.lengthcounts UTF-16 code units where asContent-Lengthmust be in bytes.Reference: http://www.w3.org/TR/XMLHttpRequest/#the-setrequestheader-method