In my research, I've been unable to find examples of an ajax function that does not include depreciated jquery functionality. I need a v3.4.1 / 2020 solution.
The problem:
I can get the function to correctly output the data to the console.log()
before a return
. My expectation is for the console.log()
to display the returned data.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
function getData (url, privateToken) {
$.ajax({
'crossDomain': true,
'url': url,
'method': 'GET',
'headers': {
'PRIVATE-TOKEN': privateToken
}
})
.done(function (response) {
console.log(response[0].id); // works correctly
// ===================================
var test = response[0].id;
console.log(test); // works correctly
// ===================================
return response; // does not work, `[object object]`` when function is called
// ===================================
return response[0].id; // does not work, `undefined` when function is called
// ===================================
var test = response[0].id;
return test; // does not work, `undefined` when function is called
// ===================================
var test = response;
return test; // does not work, `[object object]` when function is called
// ===================================
return $(response).id; // does not work, `undefined` when function is called
});
}
$(document).ready(function(){
console.log(getData("https://example.com/rest/api/xyz", "<private token>"));
});
Note that I know the code will stop at the first return
. I just wanted to display what was tried in an easily digestible manner.