Friday, January 28, 2011

Ajax Json Php Example

Ajax Json Php example
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<script type="text/javascript">
$('document').ready(function() 
{ 
    $('#mylist a').click(function ()
    {
        var id = $(this).attr('rel');

        $.getJSON('/return.php', {'id' : id}, parseInfo);
    });
});

function parseInfo(data)
{
    $('#info').html(data.name +', '+ data.email);
}
</script> 
</head>
<body>
<ul id="mylist">
   <li><a rel="3" href="#">Dave's email address</a></li>
    <li><a rel="4" href="#">Erik's email address</a></li> 
</ul>

<p id="info">&nbsp;</p> 
</body>
</html>

 
<?php

// see if we have a GET variable 'id' set
$id = (isset($_GET['id']) && !empty($_GET['id'])) ? $_GET['id'] : 0;

// pretend this is a query to a database to fetch the wanted users.
$users[3] = array('name' => 'Dave', 'email' => 'dave@adeepersilence.be');
$users[4] = array('name' => 'Erik', 'email' => 'erik@bauffman.be');

// only if an ID was given and the key exists in the array, we continue
if(!empty($id) && key_exists($id, $users))
{
    // echo (not return) the wanted record from the users array
    echo json_encode($users[$id]);
}

?>

No comments:

Post a Comment