Estoy tratando de enviar la solicitud de publicación a mi archivo PHP pero dice índice indefinido.
mi código js -
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"); }mi código PHP -
<?php if(isset($_POST['msg'])){ echo "set"; } else{ echo "not set"; } ?>También probé el método de solicitud del servidor pero no funcionó.
se muestra no configurado, y si trato de hacer eco de $_POST['msg']; dice índice indefinido 'msg'
En vez de
xhr.getResponseHeader('Content-type', 'application/w-xxx-form-urlencoded');desea establecer el encabezado de la solicitud
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');Leer más sobreXHR . Sin embargo, el enfoque actual es usar fetch() .
fetch("req.php", { method: "POST", headers: {'Content-Type': 'application/x-www-form-urlencoded'}, body: "msg=hello" }).then(response => response.text()) .then(console.log)