1

Im having a little problem making this work:

Here is my json array pulled via ajax:

{
    "message": [{
        "title": "Account",
        "id": 1
    }, {
        "title": "Content",
        "id": 2
    }, {
        "title": "Other",
        "id": 3
    }]
}

here is javascript:

var items = [];
$.get("settings.php", {
        getlink: 1,
    }, function(json) {
        $.each(json.message, function() {
            items.push(this);
        });

},"json");

console.log(items)

But for some reason items array is always empty [] I can see in firebug, json returned array, but I'm not able to push it.

2
  • The console.log might be happening before the get request is finished, try adding a timeout to test if it worked. Commented Nov 28, 2016 at 23:02
  • Add an oncomplete section and put the console.log there. Commented Nov 28, 2016 at 23:02

2 Answers 2

3

Use the index, value that $.each return :

$.each(json.message, function(index, value) {
    items.push(value);
});

NOTE : $.each() is different than .each().

Hope this helps.

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

2 Comments

Ok, I see my problem now. If I place console.log(items); within ajax get, then I can see the results, but I want to be able to access items array outside of ajax call.
Yes, you couldn't access the result immediately since $.get() is asynchronous, take a look to How do I return the response from an asynchronous call?.
3

You need to pass params to the $.each function and push that object to your array.

var json = {
    "message": [{
        "title": "Account",
        "id": 1
    }, {
        "title": "Content",
        "id": 2
    }, {
        "title": "Other",
        "id": 3
    }]
}

var items = [];
$.each(json.message, function(index, item) {
  items.push(item);
});

console.log(items)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

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.