Search code examples
javascriptxmlhttprequest

XMLHttpRequest sends meta data but no form data


I have a XMLHttpRequest which I want to use to send data from my form. Here is my code:

var mc_xhr = new XMLHttpRequest();
mc_xhr.open(
  "POST",
  "https://webhook.site/58493d5a-9b8d-4300-875b-8f4d5ec6665b"
);
mc_xhr.setRequestHeader("Content-Type", "application/json");
mc_xhr.send(JSON.stringify("test-string"));

This actually does send a request with meta data such as the origin and referer, but it does not contain the specified string of text.

Does anyone know what I need to do to send the textual string with the request?


Solution

  • You can do it like this too. The xmlHttp function handles creating the XMLHttpRequest object which will work in older browsers just as fine. The second function, fetchTask, is what actually does the sending. To use it simple supply your form object as the argument.

    function xmlHttp() {
        if (window.XMLHttpRequest) { // Mozilla, Safari, ...
            xhr = new XMLHttpRequest();
        } else if (window.ActiveXObject) { // IE
            try {
                xhr = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {
                try {
                    xhr = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (e) {}
            }
        }
    
        if (!xhr) {
            console.log('Giving up :( Cannot create an XMLHTTP instance');
            return false;
        }
    }
        
    // The function that takes the xmlHttp function, send your data and uses the response
    function fetchTask(frmElement) {
            xmlHttp();
            xhr.onload = function() {
                const
                    rsp = JSON.parse(xhr.responseText)
            }
            xhr.open(frmElement.method, frmElement.action, true)
            xhr.send(new FormData(frmElement))
            return false
        }
    
    // Grab the form to be sent
    taskForm = document.querySelector('#task-form')
    
    // Do the actual sending
    fetchTask(taskForm)