PDA

View Full Version : How To - Using an Ajax Get Request to feed a javascript function to JSON



Falkon303
09-17-2011, 05:19 AM
Hi,

I thought this was a nice use of the eval() function, and thought i'd share it with you all. Requires Jquery and PHP.


index file.


<html>
<head>
<title>Using an Ajax Request to pass javascript functions to JSON </title>
<script src="../jquery-1.6.2.min.js" type="text/javascript">
</script>
</head>
<body>
<a href="#" id="loaduserdata">User Data</a>
<table id="userdata" border="1">
<thead>
<th>First Name</th>
<th>Last Name</th>
<th>Email Address</th>
<th>City</th>
</thead>
<tbody></tbody>
</table>
<script>
$(document).ready(

function () {
$("#loaduserdata").click(function () {ajaxReq('getUsers', 'ajax');})
});

function jsonReq(request, method, dataFunctions) {
$.getJSON('json-request.php', {
request: request,
method: method
}, function (data) {
eval(dataFunctions);
});
}

function ajaxReq(request, method) {
$.get('json-request.php', {
request: request,
method: method
}, function (data) {
jsonReq('getUsers', 'json', data);
});
}

</script>
</body>
</html>


php side (json-request.php)


<?php

switch ($_GET['request'])
{

case 'getUsers':
switch ($_GET['method'])
{
case 'json':
$data = '{
"userdata": [
{
"first":"Ciaran",
"last":"Huber",
"email":"elementum.purus@utdolordapibus.edu",
"city":"Mayaguez"
}
]
}';
echo $data;
break;

case 'ajax':
$data = '$.each(data.userdata, function(i,user){
var tblRow =
"<tr>"
+"<td>"+user.first+"</td>"
+"<td>"+user.last+"</td>"
+"<td>"+user.email+"</td>"
+"<td>"+user.city+"</td>"
+"</tr>"
$(tblRow).appendTo("#userdata tbody");});';
echo $data;
break;
}
break;

}

?>


a detailed writeup on it is up at my blog - http://falkon303.wordpress.com for those of you into it. I'd like to hear some opinions on the security issues/benefits if any of you have the time. The original json + jquery tutorial is from here - http://jhoyimperial.wordpress.com/2008/07/28/parsing-json-data-from-php-using-jquery/. I just tweaked it to enable the javascript/php connection through a GET request.