There was an AJAX post error that occurred due to the refusal to set an unsafe header with the name "Connection"

My custom ajax function sends data to a PHP file, but I'm encountering two errors each time the data is posted:

Refused to set unsafe header "Content-length"
Refused to set unsafe header "Connection"

Here is my 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);
}

I'm wondering what I might be doing wrong. Any insights?

Answer №1

Eliminate the following two lines:

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

It is important to note that XMLHttpRequest is not permitted to set these headers manually because they are automatically handled by the browser. This restriction exists to prevent potential security vulnerabilities that could occur if these headers were manipulated to trick the server into accepting unauthorized requests through the same connection without undergoing proper security checks.

Answer №2

According to Section 4.6.2 of the W3C XMLHttpRequest Level 1 specification, there are certain headers that are considered to be controlled by the user agent and cannot be set using the setRequestHeader() method. Two examples of such headers are Connection and Content-length.

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Top method for independently scrolling overlapping elements in both the x and y directions

Sorry if this is repeating information. I have a structure of nested divs like this: -container -row In order to enable scrolling without the default scrollbar appearing, each container and row has an additional container. My goal is to be able to scrol ...

Generate an array of objects using the values from a different array of objects

I have an array of objects: const users = [ { name: 'Alice' }, { name: 'Eve' } ] However, I want to transform it into an array like this: const updatedUsers = [ { key: 'Alice', value: 'Alice', text: 'Al ...

Creating an interactive map on an image using HTML and drawing circles

I've been experimenting with drawing circles on images using the map property in HTML. I have an image set up, and when clicking on the image in JavaScript, I'm adding the area coordinates for the map property. However, I keep encountering a null ...

Tips on enhancing SauceLabs javascript queries in your selenium testing for faster speeds?

My experience running Selenium tests on the Chrome browser in SauceLabs has been quite frustrating due to the sluggish performance. One of the major issues I have encountered is the significant delay in javascript queries, taking about 200ms to return res ...

Leveraging Python to authenticate on a website using JavaScript and secure HTTPS connection

I am looking to utilize python for logging into a website that utilizes javascript and https encryption. The specific site I'm referring to is: My goal is to create a python script that successfully logs in, with the intention of later translating th ...

What is the most effective approach to integrating socket.io as a submodule into the ExpressJS framework?

In my current project, I am working on developing an application using ExpressJs and following the submodule architecture recommended by tjholowaychuk. Furthermore, I also want to incorporate real-time socket interactions into the app by integrating socke ...

What is the best way to pass a variable between different routing functions?

I am currently developing a server-side parser for an API. Each GET request made to my website must first initiate a request to the API, and since this request is always the same, I would like to encapsulate it within its own function. What is the best wa ...

Switch out the URL in npm's build process

While developing, I am using a mock REST service but for the public release, I intend to switch to a real backend. Is there a method to update the endpoint URL during the npm build process? ...

Find the time interval between two timestamps and output the difference in UNIX timestamp format

Is there a way to determine the time difference between two dateTime values? One date is provided by the user, while the other is the current time: User-submitted time - current time = difference in Unix timestamp The format for the user-submitted time i ...

Ways to Implement an Origin's First-Party Cookies While Using it as a Third-Party

Imagine I am the owner of a website called "treat1creator.com". I want my clients, who are also website owners, to send HTTP requests to my server that contain cookies I have generated. Here is how it works: User "Sally" visits my site at treat1creator.co ...

Initiating a node request utilizing the value of the array index as the req parameter

I created a method to insert a series of documents into a mongoose collection, with each entry containing the value corresponding to the next index in a range specified by upper and lower bounds. The current implementation works seamlessly when the lower ...

Narrow down an array of objects by matching a specific property and value to a separate array of objects

I am facing a challenge with two sets of arrays - one for the headers (columns) of a table and the other for the rows. const headers = [ { text: 'Dessert (100g serving)', align: 'left', sortable: false, value: 'n ...

What methods can I use to obtain negative numbers through swipe detection?

In my code, I am using three variables. The first one is x which serves as the starting point, followed by myCount which counts the number of swipes a user performs, and finally, dist which calculates the distance from the initial point. I want to set myC ...

Error alert: $.simpleWeather function not found

Currently, I am attempting to incorporate simpleWeather.js from the website simpleweatherjs.com into my own website. However, upon inserting the html code onto my website, an error message pops up: Uncaught TypeError: $.simpleWeather is not a function ...

Exploring the Potential of SEO with Ajax in Asp.net MVC

I'm a bit confused about how to make Ajax content indexable by Google. Let me try to clarify my understanding by posting here until I fully grasp it: It seems we need to provide Google with a "pretty" URL to index, like /content/contentdetail#!id ...

Utilizing a captured group from a regular expression as a key in replacing a string

Looking for help understanding the behavior displayed in this NodeJS 12 console code snippet. I'm attempting to replace a portion of a string with the result from a capture group. While it does work, using that capture group result as a key in an obje ...

What are the steps for transmitting an array of data to Parse Cloud Code?

Trying to send an array of contact emails as a parameter in Cloud Code function for Parse, here is how I am doing it: HashMap<String, ArrayList<String>> params = new HashMap<>(); ArrayList<String> array = new ArrayList<>(); a ...

Node: effectively managing SQL scripts with dynamic variable replacement

My SQL statements have grown quite large, and I want to store them as separate files with syntax highlighting. The solution I found on StackOverflow is perfect for my needs. In my case, I write SQL queries in JavaScript using Template Literal syntax for v ...

How can I utilize jQuery to save a simple text string in a mySQL database?

Seeking guidance on this jQuery code snippet: $('.bggallery_images').click(function () { var newBG = "url('" + $(this).attr('src'); var fullpath = $(this).attr('src'); var filename = fullpath.replace('im ...

Is utilizing React function components the most effective solution for this problem?

export default function loginUserUsing(loginType: string) { const [state, setState] = useState(loginType); function login() { // body of the login function } function oauth() { // body of the oauth function login(); ...