2

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.

Image of JSON I'm trying to access

  $(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');
    }
  });
});
3
  • Looks like there is 2 data ... have you tried data[0].data[0].id ... still, provide the JSON as well Commented May 13, 2018 at 15:17
  • Your variable is called data which is an object that holds a data property. Try data.data[0].id Commented May 13, 2018 at 15:18
  • I removed the returns and changed it to data.data[0].id; Thank you so much! My console actually says something! ha Commented May 13, 2018 at 15:29

2 Answers 2

1

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');
    }
});
Sign up to request clarification or add additional context in comments.

2 Comments

Holy shit thank you so much. I spend 4 hours this morning googling this. Honest to God, if I could buy you a beer, I would.
@branhillsdesign if this answer worked could you please accept it to let others know
1

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

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.