Adam Scot
Adam Scot

Reputation: 1409

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?

Upvotes: 0

Views: 326

Answers (2)

tyazeez
tyazeez

Reputation: 335

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)

Upvotes: 1

Saeed Shamloo
Saeed Shamloo

Reputation: 6574

If you want to send a json to server you should provide a valid json structur for xhr.send method like this:

let xhr = new XMLHttpRequest();
let body= JSON.stringify({
  name: "Saeed",
  family: "Shamloo"
});
xhr.open("POST", '/targetURL')
xhr.setRequestHeader('Content-type', 'application/json; charset=utf-8');
xhr.send(body);

If you want to send values form a from, you can use built-in FormData object. like this:

<form name="person">
  <input name="name" value="Saeed">
  <input name="family" value="Shamloo">
</form>

<script>
  // pre-fill FormData from the form
  let formData = new FormData(document.forms.person);
  // add one more custom field
  formData.append("middle", "middle-name");
  let xhr = new XMLHttpRequest();
  xhr.open("POST", "/targetURL");
  xhr.send(formData);
</script>

You can check the browser network developer tool to determine which values has sent to server.

Upvotes: 0

Related Questions