Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

256
Views
JavaScript: AJAX espera el valor de retorno de PHP

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

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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

over 4 years ago · Santiago Trujillo Report

0

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

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!