basically I'm having issues making my program wait for the AJAX request to be completed. I cant seem to get the return value to be anything besides undefined in the test() function in the example code below where it calls getFriends(). I can make it works fine setting async to false in the ajax call but as this is deprecated I want to avoid this solution.
I have tried using deferred to solve the issue and so many other options that I have found on stack overflow with no luck so I have come to the conclusion that I am likely using deferred wrong or (less likely) deferred is not an option here and so I am hoping one of the talented people on this site can help me!
Check out my code below; its a simple version of what i have running. Thanks in advance!
//function that shows how the function with issue should be called/used
function test(){
var result = getFriends(127, 1); //this is getting a result returned before ajax is done so the result is undefined
//do stuff with result data
console.log(result);
}
//function that creates a data object and calls my custom ajax function
function getFriends(user_id, page_no){
//create data object containing given parameters and a data type parameter
var data = {
page_no: page_no,
profile_id: user_id,
request_type: 'get_friends'
};
//call friendAjax to get users friends
var response = friendAjax(data, 'kv_people_feed');
return response;
}
//Used for all friend related ajax requests. Accepts a data object to be sent as parameters and otional url.
function friendAjax(data, url){
url = typeof url !== 'undefined' ? url : 'friendsLibrary'; //allows optional url param
$.ajax({
// async: false,
url: Config.home + '/' + url + '/', //dynamic url
data: data,
dataType: 'jsonp',
success: function(response){
console.log(response);
return response;
}
});
}