I’m working with some AJAX calls, which connect properly, however if I attempt to use a ternary operator in the initialization of the call, the operator does not set properly. Specifically, I’m trying to dynamically set the async parameter. The AJAX call refuses to accept the ternary version of the async unless it’s specified beforehand. This is specific to Firefox. Here’s an example:
Server receives the async call as true, regardless if I specify the async = false;.
function(url, type, async) {
$.ajax({
url: url,
type: type,
async: async ? async : true
});
}
Works correctly:
function(url, type, async) {
var async = async ? async : true;
$.ajax({
url: url,
type: type,
async: async
});
}
Although the code is working when I specify it beforehand, I do not understand why a ternary operator won’t work in this situation. I would love an explanation as to why it is required to be specified beforehand and not in the call itself.
Thank you,
Ben
Your line
…says: If
asyncis truthy, useasync; otherwise, usetrue. So of course it’s always truthy.If your goal is to default to
async: truewhenasyncisn’t given at all, do this:That will use the value of
asyncif it’s notundefined, ortrueif it is.All due respect, I don’t think the second version does anything differently to the first version, I think that must be observational error. This code emulates what you’re doing, and always shows
obj.baras beingtrue:Live copy | source
(It’s probably worth noting that the
varpart of thevar asyncin your second example — and thevar barin my emulation of it — is ignored. Novaris created, the argument is used directly.)