'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
Solution 1:[1]
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)
}
Solution 2:[2]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Mario Perez |
| Solution 2 |
