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

342
Visualizações
How to pass FormData over XMLHttpRequest using GET method

When Method of the senderform is POST, everything works fine. However, as soon as I change the method to GET, I don't receive anything on the server.

function ajaxSubmit(destinationElement, senderform) {

    var xmlreq = new XMLHttpRequest();
    var params = new FormData(senderform);
    xmlreq.open(senderform.method, senderform.action, true);

    if (/\/content\.php$/.test(senderform.action))
        xmlreq.onreadystatechange = receiveTable;
    else xmlreq.onreadystatechange = receiveText;

    xmlreq.send(params);
}

I know that I could manually append key-value pairs at the end of Action address, but the problem is that I don't know which form is going to be passed with what fields.

I would prefer native javaScript if possible.

How can I send a GET request using XMLHttpRequest with key-value pairs from senderform which points to form Element (the same way as it already works for POST requests)?

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

In the end I came with this solution, which loads all key-value pairs from senderform form reference.

function ajaxSubmit(destinationElement, senderform) {
var xmlreq = new XMLHttpRequest();
var params = new FormData(senderform);

if (senderform.method == 'get')
{
    var firstRun = true;
    for (var key of params.keys())
    {
        if (firstRun)
        {
            senderform.action += '?';
            firstRun = false;
        }
        else senderform.action += '&';
      senderform.action += key + "=" + params.get(key);
    }
}
xmlreq.open(senderform.method, senderform.action, true);
if (senderform.action.indexOf('content.php')!==-1)
    xmlreq.onreadystatechange = receiveTable;
else xmlreq.onreadystatechange = receiveText;
xmlreq.send(params);
}

In combination with @tanc's answer and this article I was able to solve my problem.

over 4 years ago · Santiago Trujillo Relatório

0

Are you sure the problem is not the PHP script? I see no reference that https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest#send() with FormData needs POST to work, but if the PHP script takes the info from $POST or something (My PHP is rusty), the behavior would be different.

over 4 years ago · Santiago Trujillo Relatório

0

Since you can't create a useable body in a GET request (see below), then the other option is to use params in the url.

function buildGetUrlParams(baseUrl, paramsObj) {
  var builtUrl = baseUrl + "?";
  Object.keys(paramsObj).forEach(function(key) {
    builtUrl += key + "=" + paramsObj[key] + "&";
  });
  return builtUrl.substr(0, builtUrl.length - 1);
}

document.getElementById('finalUrl').innerText = buildGetUrlParams('http://test.url.com', { name:'James', occupation:'web design' });
<div id="finalUrl"></div>

An HTTP GET request can contain a body, but there is no semantic meaning to that body. Which means, in simple terms, that a server doesn't have any reason to, nor have any knowledge of how, to process the body of a GET request. If it's possible to write a server that could do this, it would be bad practice as per the HTTP/1.1 specs:

if the request method does not include defined semantics for an entity-body, then the message-body SHOULD be ignored when handling the request.

And that's basically why it's not working. If you want to send any sort of data that the server is able to respond to, then you'll need to use a different HTTP method.

This answer also explains this issue.

over 4 years ago · Santiago Trujillo 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