This might be one of the few valid use cases for a synchronous AJAX request.
If you're using XMLHttpRequest
directly, you can make a synchronous request by passing false
as the third parameter to the .open()
method:
var request = new XMLHttpRequest();
request.open('GET', '/bar/foo.txt', false); // `false` makes the request synchronous
request.send(null);
if (request.status === 200) {
console.log(request.responseText);
}
(Example code from the MDN page linked above.)
If you're using jQuery, you can make a synchronous request by passing the option async: false
to jQuery.ajax()
. See jQuery: Performing synchronous AJAX requests for more details.
However, note that, in general, synchronous AJAX requests are almost always a bad idea. As long as your server (and your Internet connection) handles requests very quickly and reliably, it might work acceptably well, but if your server experiences heavy load, or your connection starts dropping packets, having to wait even a few seconds for any mouse click to have an effect could quickly get annoying.