XMLHTTPRequest onreadystatechange not working

481 views Asked by At

Im trying to send an asynchronous post request to my "server" in my electron application but the callback function onreadystatechange does not get called after any change. I suspect that the problem is the event-handler for the html button click event or the scope of the variable xmlHttp.

const ipcRenderer = require('electron').ipcRenderer;

var xmlHttp = new XMLHttpRequest();

document.getElementById('bttnAddUser').addEventListener('click', () => {
    let user = {
        firstname: 'name',
        lastname: 'name',
        username: 'username',
        created: Date.now().toString(),
        lastLogin: Date.now().toString()
    }

    xmlHttp.open('POST', 'http:/localhost:3000/add', true);
    xmlHttp.setRequestHeader("Content-Type", "application/json");

    xmlHttp.onreadystatechange = function() {
        // does not get called
        console.log('accessed change callback');
        console.log(this.readyState + this.status);
        if (this.readyState === 4 && this.status === 200) {
            ipcRenderer.send('open-new-window', 'index2.html');
        }
    }

    xmlHttp.send(JSON.stringify(user));
});
0

There are 0 answers