Stop request with Jquery when refreshing the page or clicking on a link

1

I'm using long polling with PHP + JQuery, when the user logs in the website opens a background connection to the server via Jquery like this:

var req  = $.post //(resto do codigo aqui).

This connection is open for 20 seconds and then closed automatically.

As you can see, I'm writing a variable to abort the request with req.abort();

But I wanted to abort it only when the user refreshes the page or clicks a link on the page, because when it does, the site only "responds" after the request is finished, so the user would have to wait 20 seconds + the time that the site could take for example to upload an image after the end of the request, so I would like to know if you can not make a new request when it updates it?

Ps: I used as a test the setTimeout putting it to give a req.abort(); after x seconds, and the request was canceled normally, then since there was no new connection open with the server waiting for response, when the page was updated it did not take 20 seconds to come, but this is not feasible, since I'm doing real-time checks rsrs

Current js file code below:

$(function(){
pegaNotificacoes();
});

var totalnot = 0;
var totalparc = 0;

function limpatotal()
{
totalparc = 0;
$('#notifinum').html("");
}

function pegaNotificacoes(timestamp)
{

var data = {};

if (typeof timestamp != 'undefined')
	data.timestamp = timestamp;

var req  = $.post('controllers/longpolling.php', data, function(res){
	
	for(i in res.notificacoes)
	{
		
		if (totalnot == 0)
		{
			$('#notificacao').html("");
			$('#notificacao').prepend("<div style='height: 60px;' class='notificacao'><a href='"+res.notificacoes[i].not_link+"&notid="+res.notificacoes[i].not_codigo+"'>"+res.notificacoes[i].not_assunto+"</a></div>");
		}
		else
		{
			$('#notificacao').prepend("<div style='height: 60px;' class='notificacao'><a href='"+res.notificacoes[i].not_link+"&notid="+res.notificacoes[i].not_codigo+"'>"+res.notificacoes[i].not_assunto+"</a></div>");
		}
		
		totalnot = totalnot + 1; 
		totalparc = totalparc + 1; 
		$('#notifinum').html("").fadeOut('slow', 'linear');
		$('#notifinum').html(totalparc).fadeIn('fast', 'linear');
		
		if (totalnot > 1)
		{
			if ($("#notificacao").height() < 350)
			{
				var altura = ($("#notificacao").height()) + 55;
				$("#notificacao").height(altura);
			}
		}
	}
	
	pegaNotificacoes(res.timestamp);
	
}, 'json');

}
    
asked by anonymous 19.07.2016 / 20:41

1 answer

0

As I understand it, you can check if the reload event occurred, as the example:

if(location.reload)
{
    req.abort();
}

So if it happens you call your function that aborts the request.

If you click a link, you can add a class to the <a> tag in the html, for example:

<a class='abortar'> Aborte a requisição </a>

And using jquery you can get the click of this tag with the example:

$('a').on('click','.abortar',function()
{
   req.abort();
});
    
19.07.2016 / 21:14