I’ve been working on a script recently where it would add warnings when a user clicked on certain URLs.

I attached an event to a link like so (simplified):

I was passing the URL to a function that would then do an AJAX call and check if the URL was in a database table, listing all websites I wanted to warn against.

It was at this stage that I had issues with the code. AJAX, by its nature are sent asynchronously. This means that the browser redirects the user to the link before completing the AJAX request. Whilst it fires, it doesn’t have time to complete and check the database as I wanted.

Javascript / jQuery has:

Which will stop the browser redirecting – but really, I wanted it to. Also, once you’ve called this, you can’t then call anything to then trigger the event. The fact is, that this isn’t needed at all. In fact, the key lies in the AJAX request. jQuery includes a facility to make queries synchronous – meaning that the browser will wait for the function to complete, and then return – triggering the redirect to the link.

In order to run an AJAX request as synchronous, you just need to add async:false (as asyc is true by default).

It’s useful to point out that JSONP AJAX requests can’t be synchronous.

Image Credit: chrisotruro