AJAX post error : Refused to set unsafe header "Connection"
JavascriptAjaxJavascript Problem Overview
I have the following custom ajax function that posts data back to a PHP file. Everytime the post of data happens I get the following two errors :
> Refused to set unsafe header "Content-length"
> Refused to set unsafe header "Connection"
Code :
function passposturl(url1, params, obj)
{
//url1 = url1+"&sid="+Math.random();
xmlHttp = get_xmlhttp_obj();
xmlHttp.loadflag = obj;
xmlHttp.open("POST", url1, true);
//alert(url1);
//alert(params);
//alert(obj);
//alert(params.length);
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.setRequestHeader("Content-length", params.length);
xmlHttp.setRequestHeader("Connection", "close");
xmlHttp.onreadystatechange = function ()
{
stateChanged(xmlHttp);
};
xmlHttp.send(params);
}
What am I doing wrong?
Javascript Solutions
Solution 1 - Javascript
Remove these two lines:
xmlHttp.setRequestHeader("Content-length", params.length);
xmlHttp.setRequestHeader("Connection", "close");
XMLHttpRequest isn't allowed to set these headers, they are being set automatically by the browser. The reason is that by manipulating these headers you might be able to trick the server into accepting a second request through the same connection, one that wouldn't go through the usual security checks - that would be a security vulnerability in the browser.
Solution 2 - Javascript
Section 4.6.2 of the W3C XMLHttpRequest Level 1 spec lists headers that "are controlled by the user agent" and not allowed to be set with the setRequestHeader() method. Both Connection and Content-length are in that list.
Accept-Charset
Accept-Encoding
Access-Control-Request-Headers
Access-Control-Request-Method
Connection
Content-Length
Cookie
Cookie2
Date
DNT
Expect
Host
Keep-Alive
Origin
Referer
TE
Trailer
Transfer-Encoding
Upgrade
User-Agent
Via