0

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;
        }                     
    });            
}

2 Answers 2

2

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                 
    });  

}
Sign up to request clarification or add additional context in comments.

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.