user1852596
user1852596

Reputation: 21

jQuery methods, variable scope in JavaScript

I've got a code like that:

function some_func_validate(some_id) {
    var variable_to_return = false; // i wanna use that
    $.ajax({
        type: 'GET',
        url: '/something/'+some_id+'/check',
        success: function(response){
            variable_to_return = true; // in this place
        }
    });
    return variable_to_return;
}

So, code'll return false value. How i can assign a value to a variable without using DOM of HTML document, such as assign a value to an html attribute of some tag and then get that via jQuery ???

How to use any 'global' variables in JavaScript?

Upvotes: 1

Views: 901

Answers (3)

PatrikAkerstrand
PatrikAkerstrand

Reputation: 45721

jQuery has, since version 1.5, utilities to handle management of callbacks and asynchronous invocations using objects called Deffered. Using these types of objects, it is easier for a client to add callbacks to be called when some background work has been completed. Here is an example using your code:

function some_func_validate(some_id) {
    var deferred = $.Deferred(),
        context = {
           id: some_id,
           success: false
        };

    $.ajax({
        type: 'GET',
        url: '/something/'+some_id+'/check'
    })
    .done(function(response){
       context.success = true;
       context.content = response;
       deferred.resolveWith(context);
    })
    .fail(function() {
       deferred.rejectWith(context)
    });

    return deferred.promise();
}

Example usage:

some_func_validate(5).then (
    function (context) {
      // Handle successful validation.
      console.log(context);
    },
    function (context) {
      // Handle failed validation.
      console.log(context)
    }
);

Another usage example:

function logger (context) {
   console.log(context);
}

function onSuccessfulValidation (context) {
   // Handle successful validation.
   // context contains {id, content, success}
}

function onFailedValidation (context) {
   // Handle failed validation.
   // context contains {id, success}
}

some_func_validate(3).then (
    [logger, onSuccessfulValidation],
    [logger, onFailedValidation]
);

Upvotes: 0

nxtwrld
nxtwrld

Reputation: 2052

You cannot do this while doing the asynchronous call. You can force synchronous call, but this will result in the freezing you page before the server return response. Add async: flase switch to your call.

function some_func_validate(some_id) {
   var variable_to_return = false; // i wanna use that
   $.ajax({
       type: 'GET',
       async: false,
       url: '/something/'+some_id+'/check',
       success: function(response){
           variable_to_return = true; // in this place
       }
   });
   return variable_to_return;
}

But I would still recommend refactoring your code and using the variable in the callback only.

Upvotes: 0

Johan
Johan

Reputation: 35194

Since ajax is asynchronous, you need to do something like this

function some_func_validate(some_id, cb) {

    $.ajax({
        url: '/something/'+some_id+'/check',
        success: function(response){
            cb(response);
        }
    });

}

And call it using

some_func_validate(some_id, function(response){
    //handle response here
});

Upvotes: 1

Related Questions