views:

223

answers:

2

I have the following function which works great, i used JSONP to overcome cross-domain, wrote an http module to alter the content-type and didn't append a callback name in the url.

function AddSecurityCode(securityCode, token) {
var res=0;
$.ajax({ url: "http://localhost:4000/External.asmx/AddSecurityCode",
    data: { securityCode: JSON.stringify(securityCode),
        token: JSON.stringify(token)
    },
    dataType: "jsonp",
    success: function(json) {
        alert(json); //Alerts the result correctly
        res = json;
    },
    error: function() {
        alert("Hit error fn!");
    }
});
return res; //this is return before the success function? not sure.

}

the res variable is alwayes comes undefined. and i can't use async=false with jsonp. so how can i return the result to outside the function?? and i sure need to do that for subsequant calls.

Please advice, thanks. The problem is i can't return the result value outside this function

+3  A: 

You simply cannot do this.

You have to rewrite your code flow so that AddSecurityCode takes a callback parameter (i.e. a function to run) that you then invoke inside your success callback:

function AddSecurityCode(securityCode, token, callback) {

    $.ajax({
        ....
        success: function(json) {
            alert(json); //Alerts the result correctly
            callback(json); // HERE BE THE CHANGE
        }
        ....
    });
}
Crescent Fresh
Thanks, seems this is like the only way, i was going to call a function inside success, and chain calling like that, but passing a function like you did is more cleaner.
Adel
A: 

You have res declared inside the function, making it's scope local to that function. So there's a start. Declare res outside the function and see what happens.

idrumgood