Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

138
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda