0

I have retrieved data from database and parsed it like this javascript

var categories = <?php echo json_encode($categories); ?>;

in source code categories variable has following values:

var categories = [{"id":"27","name":"john"},{"id":"8","name":"jack"}]

now I'm trying to loop through this array like this

$(document).ready(function(){
//alert(categories);
cats = jQuery.parseJSON(categories);

for (x in cats)
{
    alert(cats.name);
}
}

but I'm getting nothing. Where is the problem?

3 Answers 3

2

Try this.

$(document).ready(function(){
    for (x in categories)
    {
        alert(categories[x].name);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

Even though you're using json_encode what you are actually creating is a Javascript object. (JSON is a string that represents a Javascript object.) Since JSON syntax is valid Javascript syntax, this works fine.

Just remove the call to jQuery.parseJSON and loop through categories directly.

Comments

0

here is another working example, copy paste and try...

$(document).ready(function () {
        var categories = ['{ "id": "27", "name": "john" }', '{ "id": "8", "name": "jack"}'];
        for (i = 0; i < categories.length; i++) {
            var c = jQuery.parseJSON(categories[i])
            alert(c.name);
        }
    });

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.