Reputation: 23
I'm trying to access an item in an api so I can start getting data from the json file, but I can't seem to get anything to work. I'm unable to log any of the data I'm trying to access to the console.
$(function() {
$.ajax({
type: 'GET',
url: "xxx",
dataType: 'json',
success: function(data) {
return console.log('success', data);
return console.log(data[0].id);
},
beforeSend: function(xhr, settings) {
xhr.setRequestHeader('Authorization', 'Bearer ' + 'xxx');
}
});
});
Upvotes: 2
Views: 60
Reputation: 2125
1) You have a problem with returning before the Id is logged to the console, as you are returning it before your you logging your Id, a return statement ends the function execution. so removing the return will do the work
2) you don't really need to console.log() everything you can just put a 'debugger;' instead of return and you can reload the page with an open console window, it will pause the code execution at the debugger; and you can hover on the 'data' being received in the success function to see all the data being received on a successful AJAX call. hope this helps
Upvotes: 1
Reputation: 36309
It isn't working because you are returning before the second console.log
. the return
statement is used to exit a function at that line and return the value of the rest of the line. You are returning then trying to do something after the return which actually is never ran.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/return
Remove the return statements and it should work.
$.ajax({
type: 'GET',
url: "xxx",
dataType: 'json',
success: function(data) {
console.log('success', data);
console.log(data[0].id);
},
beforeSend: function(xhr, settings) {
xhr.setRequestHeader('Authorization', 'Bearer ' + 'xxx');
}
});
Upvotes: 1