clarkk
clarkk

Reputation: 27689

jQuery - send external var parameter into ajax success function

how can you send an external variable into the success function?

I want to send this.test into the success function

function Ajax(){
    this.url = null;
    this.data = null;
    this.success = null;

    this.timeout = JSON_TIMEOUT;
    this.cache = false;
    this.dataType = 'json';
    this.type = 'post';

    this.send = function(){
        var jqxhr = $.ajax({
                url : this.url,
                data : this.data,
                timeout : this.timeout,
                cache : this.cache,
                dataType : this.dataType,
                type : this.type
                }
            )
            .success(this.success);
    };
}

function Login(){
    this.client = null;
    this.user = null;
    this.pass = null;

    this.test = 'test';

    this.send = function(client, user, pass){
        var Obj = new Ajax();
        Obj.url = 'json.action.php?action=login';
        Obj.data = {
            client : this.client,
            user : this.user,
            pass : this.pass
            };
        Obj.success = function(response){
            alert(this.test);
            alert(response);
            //window.location.href = window.location.href;
            };
        Obj.send();
    };
}

Upvotes: 1

Views: 2094

Answers (1)

Hogan
Hogan

Reputation: 70513

You can access a closure by making a variable local. Simple case:

function Login(){
    this.client = null;
    this.user = null;
    this.pass = null;

    this.test = 'test';

    var closureVar = 'test';

    this.send = function(client, user, pass){
        var Obj = new Ajax();
        Obj.url = 'json.action.php?action=login';
        Obj.data = {
            client : this.client,
            user : this.user,
            pass : this.pass
            };
        Obj.success = function(response){
            alert(closureVar);
            alert(response);
            //window.location.href = window.location.href;
            };
        Obj.send();
    };
}

Complex case:

function Login(){
    this.client = null;
    this.user = null;
    this.pass = null;

    this.test = 'test';

    var closureVar = this;

    this.send = function(client, user, pass){
        var Obj = new Ajax();
        Obj.url = 'json.action.php?action=login';
        Obj.data = {
            client : this.client,
            user : this.user,
            pass : this.pass
            };
        Obj.success = function(response){
            alert(closureVar.text);
            alert(response);
            //window.location.href = window.location.href;
            };
        Obj.send();
    };
}

Upvotes: 1

Related Questions