Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
175
rated 0 times [  179] [ 4]  / answers: 1 / hits: 99175  / 10 Years ago, sun, february 15, 2015, 12:00:00

The code -



use strict;

var AJAX = function (params) {
this.server ={};
this.url = params.url;
this.method = params.method;
this.dataType = params.dataType;
this.formData = params.formData;

this.init = function(){
if(typeof XMLHttpRequest != 'undefined'){
this.server = new XMLHttpRequest();
this.server.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
this.server.setRequestHeader('Content-length', this.formData.length);
this.server.setRequestHeader('Connection', 'close');
console.log(XMLHttpRequest created.);
return true;
}
};

this.send = function(){
if(this.init()){
this.server.open(this.method, this.url, true);
this.server.send(this.formData);
}
};

};


It is throwing following error :



Error in event handler for contextMenus: InvalidStateError: Failed to execute 'setRequestHeader' on 'XMLHttpRequest': The object's state must be OPENED.


How it's being used -



var data = new FormData();

data.append('user', 'sachin');
var params = {
url : 'example.com',
method : 'post',
dataType: 'json',
formData : data
};

var backgroundWindow = chrome.extension.getBackgroundPage();

var ajax = new backgroundWindow.AJAX(params);

ajax.send();


I can't seem to figure out what's the reason behind.


More From » ajax

 Answers
22

The error is straight forward:




Error in event handler for contextMenus: InvalidStateError: Failed to execute 'setRequestHeader' on 'XMLHttpRequest': The object's state must be OPENED.




You need to call .open(..) before setting the request headers.









Given your code, I believe the best way would be to move the call to open in the init(..) function.



var AJAX = function (params) {
this.server ={};
this.url = params.url;
this.method = params.method;
this.dataType = params.dataType;
this.formData = params.formData;

this.init = function(){
if(typeof XMLHttpRequest != 'undefined'){
this.server = new XMLHttpRequest();

//Open first, before setting the request headers.
this.server.open(this.method, this.url, true);

//Now set the request headers.
this.server.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
//this.server.setRequestHeader('Content-length', this.formData.length);
//this.server.setRequestHeader('Connection', 'close');
console.log(XMLHttpRequest created.);
return true;
}
};

this.send = function(){
if(this.init()){
this.server.send(this.formData);
}
};

};

[#67817] Thursday, February 12, 2015, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
richardaydenc

Total Points: 148
Total Questions: 125
Total Answers: 98

Location: Seychelles
Member since Mon, Jun 28, 2021
3 Years ago
richardaydenc questions
Fri, Dec 4, 20, 00:00, 4 Years ago
Thu, Jul 2, 20, 00:00, 4 Years ago
;