1

How to pass my php array to this jquery code ? i have tried json_encoding but couldnt use it in my jquery function. my json string looks like this:

{"1":{"id":"1","league":"england","team1":"Arsenal","team2":"Chelsea"},"2":{"id":"2","league":"spain","team1":"Deportivo","team2":"Real Madrid"}}

JS:

 <script type="text/javascript">
            $(document).ready(function(){
                var shownIds = new Array();
                setInterval(function(){     
                    $.get('livescore_process.php', function(data){
                        for(i = 0; i < data.length; i++){
                            if($.inArray(data[i]["id"], shownIds) == -1){
                                if(data[i]["league"]=="england"){
                                    $("#eng").append("id: " + data[i]["team1"] + " [ "+data[i]["team1"]+ " - "+data[i]["team1"]+" ]"+ data[i]["team2"] +"<br />");
                                }
                                shownIds.push(data[i]["id"]);
                            }
                        }
                    });
                }, 3000);
            });
        </script>
Tamil Selvan C
  • 19,913
  • 12
  • 49
  • 70
Reminisce
  • 101
  • 2
  • 14
  • The *very first* link in the Related sidebar is titled [How to pass an array using PHP & Ajax to Javascript?](http://stackoverflow.com/questions/7263052/how-to-pass-an-array-using-php-ajax-to-javascript?rq=1). Is it really not applicable to your problem? (Edit: also, since your data is not a real array but an object, it won't have a `length` property.) – DCoder May 05 '13 at 16:19

1 Answers1

0

try $.getJSON instead of $.get and use php json_encode:

$.getJSON('livescore_process.php', function(data){...

however the response data is not an array but a json object, so to handle it you can try:

$.each(data, function (index, item) {
    if (item.hasOwnProperty('id')) {
        if (item.league == "england") {
            $("#eng").append("id: " + item.team1 + " [ " + item.team1 + " - " + item.team1 + " ]" + item.team2 + "<br />");
        }
        shownIds.push(item.id);

    }
});

jsfiddle

razz
  • 9,770
  • 7
  • 50
  • 68