Can we move the success function variable outside .ajax?

Can we move the success function variable outside .ajax?
0.0 0

#1

In the jquery example , is there anyway to use the suggest variable outside this $.ajax function?

    $.ajax({
        type: "POST",
        url: "http://localhost/file/fetch.php",
        data: {
            "dataA": string
        },
        cache: false,
        success: function(data) {
             var Suggest = JSON.parse(data);
        }
    });

For example i want to use the suggest variable outside like this i first have to somehow make it into a global variable to use it anywhere i want is there any easy method to achieve this?

 for (var i = suggest.length - 1; i >= 0; i--) { 
        for (var j = 0; j < arrString.length; j++) {
            if (suggest[i] === arrString[j]) {
                suggest.splice(i, 1);
            }
        }
    }

And i also want to use the variable like this.

   var suggestKey = "Suggested item";
    var suggestArray = [];
        obj[suggestKey] = suggest;
        suggestArray.push(obj);

#2

Sure, you can have a global variable declared outside the AJAX function.

var suggest

And then in the AJAX function you can store the value in it:

    $.ajax({
        type: "POST",
        url: "http://localhost/file/fetch.php",
        data: {
            "dataA": string
        },
        cache: false,
        success: function(data) {
             suggest = JSON.parse(data);
        }
    });

The only caveat (and this is very important) that variable will be undefined until after that AJAX function returns. If you are absolutely sure that variable will not be used until after the AJAX gets back, then it will work. You can also enforce it by disabling certain buttons, etc. But if you can’t do that, then it should only be referenced from inside that success method or something called from it. This is a very critical concept for dealing with AJAX.