0

My code is:

$(document).ready(function() {

    var catArr=[];
    $.get("viewData.php?action=getCat", function(json) {
        if(json.catArr.length>0)
            $.each(json.catArr, function() 
            {
                catArr.push(this.category);
            });
    }, 'json');

    $.each(catArr, function(index, el) {
        console.log(el);
        $("#category_selector").append($('<option>', { 
            value: el,
            text : el
        }));
    });

});

I've ensured that the array catArr[] is filled by using console.log(). Here's a screenshot of that:

contents of catArr

But I don't get any output due to console.log(el);. Doesn't this mean that $.each() isn't executing? Why is that, and how do I fix it?

Somenath Sinha
  • 1,174
  • 3
  • 16
  • 35

2 Answers2

2

I think you should have your $.each inside your $.get...

$(document).ready(function() {

    var catArr=[];
    $.get("viewData.php?action=getCat", function(json) {
        if(json.catArr.length>0)
            $.each(json.catArr, function() 
            {
                catArr.push(this.category);
            });

        $.each(catArr, function(index, el) {
            console.log(el);
            $("#category_selector").append($('<option>', { 
                value: el,
                text : el
            }));
        });
    }, 'json'); 
});
John Boker
  • 82,559
  • 17
  • 97
  • 130
  • That worked! But why? catArr is a variable whose scope exists throughout $(document).ready. So why wasn't $.each working? – Somenath Sinha Dec 18 '16 at 06:14
  • $.get executes and goes to the next lines. when the web request is complete the callback gets called with your data from the get request. It's not synchronous so your $.each is running before you get the data from the $.get. – John Boker Dec 18 '16 at 06:15
1

It seems that you're fetching data from server, but your javascript runs as soon as it runs the code, it means your $.each() is running before the data comes from the server, you should do it like this:

$.get("viewData.php?action=getCat", function(json) {
    if(json.catArr.length>0) {
        $.each(json.catArr, function() 
        {
            catArr.push(this.category);
        });

        $.each(catArr, function(index, el) {
            console.log(el);
            $("#category_selector").append($('<option>', { 
                value: el,
                text : el
            }));
        });
    }
}, 'json');

You should manipulate on your data when it receives from server

Hope this helps!

Saumya Rastogi
  • 13,159
  • 5
  • 42
  • 45
  • @SomenathSinha - If you find this answer correct and helpful then accept & upvote this answer as it motivates me to give answers to other questions like this and helps others to quickly find the correct answer! – Saumya Rastogi Dec 18 '16 at 06:15
  • @SomenathSinha - :D I know, that's OK.!! – Saumya Rastogi Dec 18 '16 at 06:46