JSFiddle - React, Tailwind, and code Playground

by Will Stott

HTML

<form method="post" action="https://listen.tidalhifi.com/v1/login/username?token=sSa0ezMKgcYMYbaQ">
    Username:<br>
    <input id="usr" type="text" name="username"/><br>
    Password:<br>
    <input id="pas" type="password" name="password"/>
    <input id="btn" type="button" value="Submit"/>
</form>

JavaScript

var btn  = document.getElementById("btn");

function encodeData(data) {
    return Object.keys(data).map(function(key) {
        return [key, data[key]].map(encodeURIComponent).join("=");
    }).join("&");
}

var tryLogin = function () {
    var loginUrl = "https://listen.tidalhifi.com/v1/login/username?token=sSa0ezMKgcYMYbaQ&c=aiosdfubh";
    var headers = {
        "Content-Type": "application/x-www-form-urlencoded"
    };
    var options = {
        "method": "POST"
    };
    var data = {
        "username": document.getElementById("usr").value,
        "password": document.getElementById("pas").value
    }
    
    var XHR = new XMLHttpRequest();
    var urlEncodedData = "";
    var urlEncodedDataPairs = [];
    var name;
    
    // We turn the data object into an array of URL encoded key value pairs.
    for(name in data) {
        urlEncodedDataPairs.push(encodeURIComponent(name) + '=' + encodeURIComponent(data[name]));
    }
    // We combine the pairs into a single string and replace all encoded spaces to 
    // the plus character to match the behaviour of the web browser form submit.
    urlEncodedData = urlEncodedDataPairs.join('&').replace(/%20/g, '+');
    // We setup our request
    XHR.open('POST', "https://listen.tidalhifi.com/v1/login/username?token=sSa0ezMKgcYMYbaQ");
    
    // We add the required HTTP header to handle a form data POST request
    XHR.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    //XHR.setRequestHeader('Content-Length', urlEncodedData.length);
    
    // And finally, We send our data.
    XHR.send(urlEncodedData);
}

btn.addEventListener("click", tryLogin);