Reputation: 1
The function rk() returns random key from an Ajax call, parameter l stands for length. My question is how can I take the return value from the Ajax result in my "k" variable?
var k = rk(6);
function rk(l) { //l stands for length
$.ajax({
url : 'ajax_lib.php',
type : 'POST',
data : 'k=1&l=' + l,
success : function(r) {
return r;
}
});
}
Upvotes: 0
Views: 113
Reputation: 651
A solution could be
function rk(myVariable, l) { //l stands for lenght
$.ajax({
url : 'ajax_lib.php',
type : 'POST',
data : 'k=1&l=' + l,
success : function(r) {
myVariable = r;
}
});
}
and instead of calling r=rk(l)
you can call rk(r, l)
Upvotes: 0
Reputation: 388316
Ajax uses asynchronous processing, means once the request is sent to the server, it will keep executing the remaining statements without waiting for the response.
So in your case once the request is sent to the server, rk
returns undefined
(since there is no return statement) value the variable k
will have value undefined
.
To solve this problem make use of the promise object returned by $.ajax
rk(6).done(function(r){
//do what ever you want to do with r
});
function rk(l) { //l stands for lenght
return $.ajax({
url : 'ajax_lib.php',
type : 'POST',
data : 'k=1&l=' + l
});
}
Upvotes: 2