0

I have links in a notifications menu (kind of like on facebook, or here on SO) and when the notification is clicked I want to make an AJAX call to mark the notification as 'read' and then follow the link.

My question is, if I make a click handler such as this:

$(".elements").on("click", function() {
    // make AJAX request
    return true;
});

Can I be assured the click handler will be fully executed (and the AJAX request made to the server) before the browser follows the link?

I think the answer is yes, since adding this attribute to links:

onclick="return false;"

Prevents the link from being followed, but I've been searching and haven't been able to find a concrete answer to my question, and I want to be 100% sure.

Nate
  • 26,164
  • 34
  • 130
  • 214
  • 2
    You'll have to make a non-asynchronous AJAX request, otherwise it'll likely be cancelled by the browser before it could execute. – SeinopSys Aug 09 '14 at 00:34

2 Answers2

1

"Fired off" is not well-defined. You certainly cannot guarantee that the AJAX will have gone far enough along that the server will see it, which is the key point.

If you are making any asynchronous calls, like a AJAX call, you should cancel the click event before making the call, and then when the call completes, follow the link manually.

Michael Lorton
  • 43,060
  • 26
  • 103
  • 144
  • I updated my question to clarify. I don't need a response from the server, but I do need to guarantee the data in the AJAX request will make it to the server. – Nate Aug 09 '14 at 00:41
  • Doesn't change the answer: if you don't have positive acknowledgment, you don't know what has happened and the browser isn't making any guarantees. In your case, you can attach a listener to the onstatechange event of the XHR object and continue as soon as it reaches at least as far as state 2 (HEADERS_RECEIVED). – Michael Lorton Aug 10 '14 at 01:00
1

Here's another thread that touches on this (tangentially)

Adding return false in a Jquery event handler is the same as calling preventDefault() and stopPropagation() which will stop it from following links, and bubbling up the DOM, respectively.

I would add return false to your click handlers, make the AJAX call inside the handlers, and then you'll be able to supply a callback function that will execute after the AJAX has finished firing. I believe that's achieved through the done property of an AJAX object.

AJAX documentation for JQuery

Community
  • 1
  • 1
Morklympious
  • 1,065
  • 8
  • 12