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>
1
  • The very first link in the Related sidebar is titled How to pass an array using PHP & Ajax to Javascript?. 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.) Commented May 5, 2013 at 16:19

1 Answer 1

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

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

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.