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

09-17-2011, 05:19 AM

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.

<title>Using an Ajax Request to pass javascript functions to JSON </title>
<script src="../jquery-1.6.2.min.js" type="text/javascript">
<a href="#" id="loaduserdata">User Data</a>
<table id="userdata" border="1">
<th>First Name</th>
<th>Last Name</th>
<th>Email Address</th>

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

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

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


php side (json-request.php)


switch ($_GET['request'])

case 'getUsers':
switch ($_GET['method'])
case 'json':
$data = '{
"userdata": [
echo $data;

case 'ajax':
$data = '$.each(data.userdata, function(i,user){
var tblRow =
$(tblRow).appendTo("#userdata tbody");});';
echo $data;



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.