I have a situation where I need to initialize/assign variables from the results of a jQuery AJAX call, and then re-use those variables further on down the script:
var shouldRedirect = ???
$.ajax({
url: 'http://example.com',
type: 'GET',
data: 'blah',
asynch: false,
timeout: 1800,
success: function(data) {
shouldRedirect = data.rows[0].redirectFlag
}
});
if(shouldRedirect)
window.location = "...";
Two issues I’m having:
- Assuming the resultant JSON will contain a
redirectFlagboolean, isdata.rows[0].redirectFlagthe proper way of obtaining the value for my variable?; and - What do I initialize
shouldRedirectto before the AJAX is kicked off (how do I say “create a variable but don’t give it a value yet!”)?
Thanks in advance!
You can declare uninitialized variables by simply doing the following:
If your logic requires it you can of course initialize it to false:
This might not be what you desire though. You can check if a variable was initialized by strictly comparing it to
undefined:Note though, that you must use the triple equal operator (aka strict equality) or your results will not be as expected. On the other side, an undefined variable will yield a falsy result. This means that when checking a variable with a simple
if (shouldRedirect)and the variable is undefined then it will yieldfalse, as if it was set to false. This is also true for a couple of other values in JavaScript, eg the empty string""or the valuenull. You can see a complete list of falsy values here. If you want to check explicitly for true or false and want to omit other falsy or truthy values, then you should check with triple equality, egif (shouldRedirect === true).Also, if
data.rows[0].redirectFlagis the correct way to access the value is highly dependend on how the data structure you receive from your AJAX call actually looks like. If it is something like the following it would be correct:If your JSON looks like the following though
then you have to access redirectFlag simply with
data.redirectFlag.