0

I made this JavaScript (JQuery) to load the data from an API call but it gives me an undefined. This is how it looks:

$(document).ready(function(){
    //Autocomplete for Person
    $(function() {
        $.ajax({
            type: 'GET',
            url: urlReq+'/api/persons/1',
            success: function(response) {
                let modelArray = response;
                let dataModel = {};

                for (let i = 0; i < modelArray.length; i++) {
                    dataModel[modelArray[i].first_name] = null;
                    console.log('data is: '+modelArray[i].first_name);
                }

                $('input.autocomplete_person').autocomplete({
                    data: dataModel,
                });
            }
        });
    });
});

where my urlReq+'/api/persons/1' returns something like this:

{"452":{"id":452,"reference":"20190528155926096","first_name":"John","middle_name":"Smith","third_name":null,"family_name":"Doe"}}

but my problem is that my console gives me this: data is: undefined

2 Answers 2

1
 {"452":{"id":452,"reference":"20190528155926096","first_name":"John","middle_name":"Smith","third_name":null,"family_name":"Doe"}}

This is not an array so you can’t iterate over it.

Sign up to request clarification or add additional context in comments.

6 Comments

Yes that’s a JSON format but there is no array inside of that. Please update the response exactly as it comes from the API so I can help
Now the result is something like this: [{"id":1,"reference":"20190214134326044","first_name":"Alicia","middle_name":"Duncan","third_name":null,"family_name":"Frank"}] but i still get the undefined result.
Is it because i have more than a thousand data in my database?
You are doing something wrong then. console.log('data is: '+modelArray[i].first_name) should work
No it’s not because of that because the database didn’t fail and you received data from the API
|
0

You can remove the for loop and just assign the response directly:

let firstName = response[0].first_name; // "John"

1 Comment

But i have more than 1000 records.

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.