I have this link with an onclick that's supposed to execute before the href
<a class="btn btn-primary" href="?mode=full" onclick="req('name=vmode&value=full','POST','/cookie')">Promeni rezim prikaza</a>
And the relevant parts of the called js function looks like this:
function req(data='',method='GET',url='',lang='',el='null'){
const Http = new XMLHttpRequest();
Http.open(method,url);
...
const e = document.getElementById(el);
if (e && e.value != '' || !e)
Http.send(msg);
or return false whatever
Now this only works when I set
Http.open(method,url,false);
But I get warned from my browser's console about how doing this on the main thread is deprecated and it straight up doesn't allow half of my script to work even if I'm not calling that part(weird)
How does one properly do this? i.e make it await the async function
Pass then event
of the click to your function: onclick="req(event, 'name=vm....
Then your function can event.preventDefault()
it, so that the default action of the click is not executed.
Now wait for your network request to return (probably want to use fetch()
, that's much simpler than the old XMLHttpRequest
).
Once the promise resolved, trigger the redirect to the target URL:
<body>
<a href="?mode=full" onclick="req(event, 'name=vmode&value=full','POST','/cookie')">Promeni rezim prikaza</a>
</body>
<script>
function req(event, data='',method='GET',url='/index.html?test') {
console.debug(event);
event.preventDefault();
fetch(url, {method: "POST"}).then(() => {
location.href = event.target.href;
});
}
</script>
But consider that your users may have to wait for the request in the background and don't understand what is going on.
If you only want to send some statistics data, you may want to consider using the new sendBeacon()
API. It sends data (POST
only) async in the background, so that the link target can be loaded for the user, while the browser works on the sendBeacon()
requests in the background.