2

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 redirectFlag boolean, is data.rows[0].redirectFlag the proper way of obtaining the value for my variable?; and
  • What do I initialize shouldRedirect to before the AJAX is kicked off (how do I say "create a variable but don't give it a value yet!")?

Thanks in advance!

5
  • 2
    Your asynch property is wrong, it should be async. This is never going to work if the request is asynchronous, so you will need to change that. Commented May 2, 2012 at 11:13
  • @JamesAllardice: I'd say it's good. sync requests are bad anyway :) Commented May 2, 2012 at 11:16
  • @ThiefMaster - Agreed, they are bad, but in this case it's the only way to do what the OP is trying to do (use a value returned by the AJAX request outside of the success event handler). Commented May 2, 2012 at 11:18
  • 1
    @ThiefMaster, the specific problem here is that the 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. Commented May 2, 2012 at 11:19
  • Yeah, but he should rather put the code inside that handler. Commented May 2, 2012 at 12:20

4 Answers 4

1

You can declare uninitialized variables by simply doing the following:

var shouldRedirect;

If your logic requires it you can of course initialize it to false:

var shouldRedirect = false;

This might not be what you desire though. You can check if a variable was initialized by strictly comparing it to undefined:

if (shouldRedirect === undefined) // do something

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 yield false, 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 value null. 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, eg if (shouldRedirect === true).

Also, if data.rows[0].redirectFlag is 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:

{ rows: [ {redirectFlag: true}, {redirectFlag: false} ] }

If your JSON looks like the following though

{ redirectFlag: false }

then you have to access redirectFlag simply with data.redirectFlag.

Sign up to request clarification or add additional context in comments.

Comments

0
  • What do I initialize shouldRedirect to before the AJAX is kicked off (how do I say "create a variable but don't give it a value yet!")?

    You could just do: var shouldRedirect;

However, I would do var shouldRedirect = false; to ensure shouldRedirect is not undefined

  • Is data.rows[0].redirectFlag the proper way of obtaining the value for my variable?

Depends what you send back from the AJAX request. Usually responses are in JSON so if you send a JSON object back with a value true then you could do:

shouldRedirect = data.redirectFlag;

Comments

0

For part #1 to declare a variable with it having a value use: var shouldRedirect. This way you can just do a if (!shouldRedirect) {}.

For part #2. How to get the value from redirectFlag is based on the formation of the data returned from the ajax call. data... would be the starting point for you to get the value.

Comments

0

As mentioned in the comments section, setting the shouldRedirect flag isn't going to help as the if statement that follows the $.ajax request will be evaluated before the result is fetched from the server - this is a common problem faced in asynchronous code execution. Although you can, in theory, force jQuery.ajax into syncronous mode via the sync parameter, I wouldn't recommend doing so as it will lock up the browser UI whilst the request is made.

You need to move your redirection code into the $.ajax success function like so:

$.ajax({
    url: 'http://example.com',
    // ... other options omitted for brevity

    success: function(data) {
        // This code block gets executed when the operation completes.
        var shouldRedirect = data.rows[0].redirectFlag
        if (shouldRedirect) {
            // Your redirection code goes here.
            window.location = "...";
        }
    }
});

If you using of jQuery 1.7 or greater, you can make use their Promises/A implementation via the defered object. Defered object's allow you to execute one or more functions when an operation completes and makes the async code easier to read.

$.ajax({ url: 'http://example.com' })
    .done(function(data) { 
        // This code block gets executed when the operation completes.
    });

Instead of passing a function closure to done, you can also pass a reference to a member function, eg:

$.ajax({ url: url }).done(onDataLoaded);

function onDataLoaded(data) {
    // This function gets called when the ajax operation completes.
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.