Soy novato en AJAX. Mi objetivo es abrir en JavaScript un archivo php.
function checkCorrect(userEntry, solution) { return fetch("checkSolution.php", { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8", }, body: `userEntry=${userEntry}&solution=${solution}`, }) .then((response) => response.text()) .then((res) => (res)) .catch(err => console.log("checkCorrect: " + err)); } function checkSolution() { result = checkCorrect(userEntry, solution); alert(result) }Mi problema es que alert() en checkSolution muestra " [promesa de objeto] "
y no el valor real proveniente de php. En php solo hay un
echo "hola";
Gracias, BM
De hecho, fetch es asíncrono. no lo sabía En mi caso, estoy buscando un método síncrono.
XMLHttpRequest es el enfoque correcto en mi caso.
Y aquí está la solución:
function checkCorrect(userEntry, solution) { var ret_value = null; var xmlhttp=new XMLHttpRequest(); xmlhttp.onreadystatechange=function() { if (this.readyState==4 && this.status==200) { ret_value = xmlhttp.responseText; } } xmlhttp.open("POST","checkSolution.php",false); xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xmlhttp.send("userEntry="+userEntry+"&solution="+solution); return ret_value; }El tercer parámetro de xmlhttp.open() es la parte importante:
si es verdadero = asíncrono, si es falso = síncrono
Gracias, BM
Debe usar async antes de la declaración de la función para que JS sepa que se trata de una función asíncrona, también debe usar await para esperar a que se resuelva la promesa. Aquí hay un ejemplo:
function async checkCorrect(userEntry, solution) { try { const requestParams = { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8", }, body: `userEntry=${userEntry}&solution=${solution}`, } const result = await fetch("checkSolution.php", requestParams) .then((response) => response.text()) .then((res) => (res)) return result; } catch(e) { handleYourError(e); } } function checkSolution() { result = checkCorrect(userEntry, solution); alert(result) }