Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

138
Visualizações
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?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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)
about 4 years ago · Juan Pablo Isaza Relatório

0

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.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda