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

153
Visualizações
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

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

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

about 4 years ago · Juan Pablo Isaza Relatório

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

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