This is my code:
<script>
function sendFieldData() {
var email = document.getElementById('EmailComprador').value;
var telefone = document.getElementById('TelefoneComprador2').value;
var nome = document.getElementById('NomeComprador2').value;
var data = {
CostumerEmail: email,
CostumerName: nome,
CostumerPhone: telefone,
};
if (email) {
let curfetchUrl = `${window.location.pathname}?handler=SaveAbandonedCart`;
fetch(curfetchUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'RequestVerificationToken': document.querySelector('input[name="__RequestVerificationToken"]').value
},
body: JSON.stringify(data)
})
.then(response => {
if (!response.ok) {
return response.text().then(text => { throw new Error(text); });
}
return response.json();
})
.then(responseData => {
console.log('salvo com sucesso', responseData);
})
.catch(error => {
console.error('erro:', error);
});
}
}
window.addEventListener('beforeunload', function (event) {
setTimeout(sendFieldData, 0);
});
</script>
At first it only calls the method on the IndexModel when I reload the page, but that’s not what I want. I want when the user clicks on close tab to trigger the event to the backend as well.
Obs.: I already used unload, it didn’t work.
I’m using Razor, Js and C#