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!
asynchproperty is wrong, it should beasync. This is never going to work if the request is asynchronous, so you will need to change that.successevent handler).if (shouldRedirect) [...]will be executed before the ajax call returns, thereby never actually doing anything. So while it is true that async operations are the proper way to do things, this particular piece of code only works in sync mode.