1

I am returning the data below from a PHP script:

[{"Town":"Mancetter"},{"Town":"Manchester"},{"Town":"Mancot Royal"}]

I basically just want to loop through the results and display the town, here is my jQuery:

function search_town(){


var keyword = $('.town_s').val()


    $.ajax({
        type: "GET",
        url: "class/ajax.php",
        data: { "town_search" : keyword },
        success: function(data){

            var data = $.parseJSON(data);

            for (var i = 0, l = data.length; i < l; i++) {

                    alert(i + ': ' + data[i]);
                }


        }
});

        }

I'm not getting the results desired... what is alerted is 0:[object Object]

Any ideas where I may be going wrong?

Thanks

1 Answer 1

4

You need to specify the property to get

data[i].Town

by looping you are going through each object in the array.. so the first iteration will get you

{"Town":"Mancetter"}

Which you can access the property in the loop by using data[i].Town

and so on

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

2 Comments

And as if by magic, it works, you rock! So data[i] selects the object within the array?
Yes. According to your data structure.. You have an array of 3 objects.. So each loop returns each object

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.