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

136
Visualizações
using POST in ajax in vanilla js

I am trying to send the post request to my PHP file but it is saying undefined index.

my js code -

document.getElementById("btn1").addEventListener('click', xh );

function xh(){
    xhr = new XMLHttpRequest();
    //xhr.open('GET', 'req.php?msg=hello bro', true);
    xhr.open('POST', 'req.php');
    xhr.getResponseHeader('Content-type', 'application/w-xxx-form-urlencoded');
    
    xhr.onprogress = function () {
       // document.getElementById("loading").classList.remove("dis");
    }
    xhr.onload = function () {          
        console.log(this.responseText);
    }
    
        xhr.send("msg=hello");        
    }

my PHP code -

 <?php
        if(isset($_POST['msg'])){
            echo "set";
        }
        else{
            echo "not set";
        }
    ?>

I also tried the server request method but it didn't work

it is showing not set, and if I try to echo the $_POST['msg']; it says undefined index 'msg'

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

0

Instead of

xhr.getResponseHeader('Content-type', 'application/w-xxx-form-urlencoded');

you want to set the request header

xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

Read more about XHR. The present approach it to use fetch() though.

fetch("req.php", {
  method: "POST",
  headers: {'Content-Type': 'application/x-www-form-urlencoded'},
  body: "msg=hello"
}).then(response => response.text())
  .then(console.log)
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