logo   Ajax05 -




PHP-array til klient med `json_encode()`


PHP


<?php

/* set out document type to text/javascript instead of text/html */
header("Content-type: text/javascript");
/* our multidimentional php array to pass back to javascript via ajax */
$arr = array(
    array(
       "first_name" => "Darian",
       "last_name" => "Brown",
       "age" => "28",
       "email" => "darianbr@example.com"
    ),
    array(
       "first_name" => "John",
       "last_name" => "Doe",
       "age" => "47",
       "email" => "john_doe@example.com"
    )
);
/* encode the array as json. this will output [{"first_name":"Darian","last_name":"Brown","age":"28","email":"darianbr@example.com"},{"first_name":"John","last_name":"Doe","age":"47","email":"john_doe@example.com"}] */
echo json_encode($arr);
?>


global js


<script type='text/javascript'>
    $(document).ready(function(){
       /* call the php that has the php array which is json_encoded */
       $.getJSON('json_encoded_array.php', function(data) {
       /* data will hold the php array as a javascript object */
       $.each(data, function(key, val) {
          $('ul').append('<li id="' + key + '">' + val.first_name + ' ' + val.last_name + ' ' + val.email + ' ' + val.age + '</li>');
       });
    });
    });
</script>


HTML


<!-- this UL will be populated with the data from the php array -->
<ul></ul>






















x
x