I'm trying to return value via AJAX. Below is the code that I put together based on some examples I found and it seems to work, but I think there's a better way of doing it?
(async () => {
const url = new URL("/ajax-page", window.location.origin);
const headers = new Headers([
[
"Content-Type",
"application/x-www-form-urlencoded; charset=UTF-8"
]
]);
const body = new URLSearchParams([
["sl", slug]
]);
const res = await fetch(url, {
method: "POST",
headers,
body
});
if (res.ok) {
let mkr = await res.text();
crd = mkr.split("|");
lat = crd[0],
lon = crd[1];
console.log(lat ' ' lon);
}
})();
PHP (ajax-page)
// php magic gets values
echo $mar['lat'].'|'.$mar['lon'];
Do I even need to use (async () => {...})(); anymore?
CodePudding user response:
These lines:
lat = crd[0],
lon = crd[1];
are not variable declarations (because there's no let
keyword). It's using the comma operator, so it's equivalent to:
lat = (crd[0], lon = crd[1])
The comma operator returns the value of the second expression, so both lat
and lon
are being set to crd[1]
.
The cause of this problem is that you ended the previous two lines with ;
rather than ,
. The whole declaration should be:
let mkr = await res.text(),
crd = mkr.split("|"),
lat = crd[0],
lon = crd[1];
If you use your IDE's auto-indent feature it would have shown that this isn't grouped the way you intended.
CodePudding user response:
await can be used only inside an async function. You cannot avoid it. Asynchronous functions implicitly return a promise, so other async functins can await their results.