1

I am trying to permanently change some values from inside the $.ajax.done() scope, so that it is available to other parts of my code outside this scope. The variable duplicate is a global variable within a module I have written and I want to be able to use the updated boolean value in other functions after running done().

The function duplicateFile is set up to return a block of $.ajax({ url:... }); code.

// Callback function
duplicateError = function() {
        console.log(duplicate); // prints 'true' if a duplicate is found
        if (duplicate) {
            errors.create("duplicateFile");
        }
    };

// AJAX call
duplicateFile(fileData).done(duplicateError);

If a duplicate is found after running the AJAX call, console.log prints true. But if I try to call console.log after the AJAX function call as follows, the value is false regardless:

duplicateFile(fileData).done(duplicateError);
console.log(duplicate); // always prints 'false'

Is there any way to work around this and get the duplicate value to change permanently after calling the request? I know I could set async: false in the AJAX request, but I would like to avoid that.

EDIT: duplicate is getting changed in the callback function that is passed to the success method in the$.ajax({ url:... }) .

Rishad Bharucha
  • 129
  • 1
  • 1
  • 8
  • 1
    Check this out: http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call – helllomatt Apr 15 '16 at 20:11
  • Where is `duplicate` getting changed? It is not clear through your code. The most probable cause of this behaviour is the asynchronous nature of Ajax. – puelo Apr 15 '16 at 20:14
  • @puelo `duplicate` is getting changed in the callback function that is passed to the `success` method in the`$.ajax({ url:... })` . I'll update the original post with that. – Rishad Bharucha Apr 15 '16 at 20:22
  • @helllomatt I am using callbacks in my code as shown above, but I'm not sure what's going wrong. If I'm modifying code (setting values, etc) in my callbacks, why isn't it becoming permanent? – Rishad Bharucha Apr 15 '16 at 20:27
  • @RishadBharucha did you check out hellomatt's link? The problem is that the success function is executed when the Ajax request is finished. Ajax is asynchronous and this means, that the `console.log` gets executed before the Ajax request is finished (most of the times). It is not a problem of a value becoming permanent, it is a question of execution order. – puelo Apr 15 '16 at 20:28

0 Answers0