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.

Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
Alko
  • 1,421
  • 5
  • 25
  • 51

2 Answers2

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.

Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
  • 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. – Alko Nov 28 '16 at 23:26
  • 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?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call). – Zakaria Acharki Nov 28 '16 at 23:42
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>
Brett DeWoody
  • 59,771
  • 29
  • 135
  • 184