Skip to content Skip to sidebar Skip to footer

Xmlhttprequest Throwing Invalidsateerror Saying "object State Must Be Opened"

The code - 'use strict'; var AJAX = function (params) { this.server ={}; this.url = params.url; this.method = params.method; this.dataType = params.dataType;

Solution 1:

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.");
            returntrue;
        }
    };

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

};

Solution 2:

You probably need to open the connection after the XMLHttpRequest call and before the setRequestHeader call Instead of:

this.server = new XMLHttpRequest();
        this.server.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

i think you need to do:

this.server = new XMLHttpRequest();
        this.server.open(this.method, this.url, true);
        this.server.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

also make sure you remove this line in the init(), like you have done above.

Post a Comment for "Xmlhttprequest Throwing Invalidsateerror Saying "object State Must Be Opened""