0

I get undefined when i try to console.log it

var farr = [];
$.ajax({
    url: "https://whispering-cliffs-33347.herokuapp.com/employees",
    type: "GET",
    contentType: "application/jsonp"
}).done(function(employees) {
    for(let i in employees){
        farr.push(employees[i]);
    }
})
console.log(farr[8]);

Any ideas?

5
  • First console employees. Know whether it is array or object. If it is array, you may need to parse the JSON. And use console in .done function. Commented Feb 4, 2018 at 5:24
  • 1
    Move the console.log call into your .done() callback. Remember that $.ajax is asynchronous and any return values or variables you're setting in the callback will be undefined outside of the callback. Commented Feb 4, 2018 at 5:27
  • 3
    Possible duplicate of How do I return the response from an asynchronous call? Commented Feb 4, 2018 at 5:29
  • just use async:false Commented Feb 4, 2018 at 5:30
  • 1
    No, do not use async:false. It's deprecated, it's lazy and it's poor programming practice. Commented Feb 4, 2018 at 5:32

2 Answers 2

1

console.log(farr[8]); will be executed even before the response is available.So in first done push all the elements in the local array & once that is done in the next done log the value

var farr = [];
    $.ajax({
        url: "https://whispering-cliffs-33347.herokuapp.com/employees",
        type: "GET",
        contentType: "application/jsonp"
    }).done(function(employees) {
        employees.forEach(function(item){
            farr.push(item)
        })
    }).done(function(elem){
        console.log(farr[8]);
    })
Sign up to request clarification or add additional context in comments.

Comments

0

You can not iterate the object with standard for loop. To be able to do that, you should first get object keys in an array and iterate over that.

const keys = Object.keys(employees);
keys.forEach((i) => {
     farr.push(employees[i]);
 }
 console.log(farr[8]);. // You should put this in the call back itself

Or you can directly iterate over the object using lodash's forEach.

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.