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

230
Vistas
JavaScript - AJAX wait for Return Value from PHP

I am newbie in AJAX. My goal is to open in JavaScript a php file.

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)
}   

My problem is, alert() in checkSolution shows "[object Promise]"

and not the real value coming from php. In php there is just a

echo "hi";

Thanks, BM

over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

In fact fetch is asynchronous. I didn't know. In my case I am looking for synchronous method.

XMLHttpRequest is the right approach in my case.

An here is the solution:

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;
}

The 3rd parameter of xmlhttp.open() is the important part:

if true = asynchronous, if false = synchronous

Thanks, BM

over 4 years ago · Santiago Trujillo Denunciar

0

You need use async before the function declaration so JS knows this is an async function, also you need to use await to wait for the promise to resolve. Here is an example:

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)
}

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