I am a huge fan of Javascript -> Dynamic PHP. You could say it’s been my favorite underdog ever since I found a script on dynamicdrive.com
While browsing the internet, the best tutorial I found on using Jquery with JSON Requests was here – http://jhoyimperial.wordpress.com/2008/07/28/parsing-json-data-from-php-using-jquery/. It’s simple, straight forward, and shows a nice working example. In short, JSON allows you to return an array of data from your PHP request, so that you can update multiple elements at once.
I wanted to have the Javascript functions reside in the PHP, and use PHP to handle my Javascript functions. Then it would all reside in the request file. With this method of requesting (2 requests), everything is held on the PHP end, and I use the Javascript eval() function to run the returned string as a function to execute code. This way you don’t have a Javascript file that is 320k and ugly as hell. Instead, with a bit of work, you can have a nicely laid out PHP file with each Javascript function set into it’s own “case:” instance….. muy bien.
On to the code!
This file makes up the HTML page that will be making the request.
Pre-requisites – Jquery.
Note: This method is HIGHLY un-secure, but very interesting technology. The current pitfalls are that single quotes ‘, and/or double quotes “, will break the process due to improper escaping. Definitely a challenge.
UPDATE: 9/17/2011, both requests now using the $_GET method to simplify the php side.
UPDATE: 9/17/2011, now you can accomplish both ajax->ajax requests, and also ajax->json requests (called by either “a->a”, or “a->j”. I also log the time execution of both. Both methods allow for you to keep your javascript functions php side.
<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> <form name="user" id="user"> First Name:<br> <input name="firstname" value="John"><br> Last Name:<br> <input name="lastname" value="Doe"><br> Email Address:<br> <input name="email" value="john@lorem.com"><br> City:<br> <input name="city" value="Ipsum"><br> </form> <p><a href="#" id="loaduserdata-ajax-to-json">User Data via Ajax -> JSON</a></p> <p><a href="#" id="loaduserdata-ajax-to-ajax">User Data via Ajax -> Ajax</a></p> <table id="userdata" border="1"> <thead> <th width="100px">Method</th> <th width="100px">Time</th> <th>First Name</th> <th>Last Name</th> <th>Email Address</th> <th>City</th> </thead> <tbody></tbody> </table> <script> $(document).ready(
function () { $("#loaduserdata-ajax-to-json").click(function () { ajaxReq('a->j', 'getUsers', $('#user').serialize()); }) $("#loaduserdata-ajax-to-ajax").click(function () { ajaxReq('a->a', 'getUsers', $('#user').serialize()); }) });
function jsonReq(method, request, dataIn, reqData) {
switch (method) { case 'a->a': case '->a': mode = $.get; break;
case 'a->j': case '->j': mode = $.getJSON; break;
}
mode('json-request.php', { request: request, method: method, dataIn: dataIn, reqData: reqData }, function (data) { switch (method) { case 'a->a': case '->a': format = dataIn = data; break;
case 'a->a': case '->a': format = dataIn = dataIn; break; } eval(dataIn); });
}
function ajaxReq(method, request, reqData) {
$.get('json-request.php', { request: request, method: method, reqData: reqData }, function (data) {
switch (method) { case 'a->a': jsonReq('->a', request, data, reqData); break;
case 'a->j': jsonReq('->j', request, data, reqData); break; }
}); }
</script> </body> </html>
Here’s the PHP file (name it json-request.php) , we’ll be making all of our requests to.
<?php
switch ($_GET['request']) {
//**** START GETUSERS FUNCTION ****// case 'getUsers': switch ($_GET['method']) { //** BEGIN AJAX->JSON REQUESTS **// case '->j': $reqData = parse_str($_GET['reqData']); $data = '{ "userdata": [ { "firstname":"'.$firstname.'", "lastname":"'.$lastname.'", "email":"'.$email.'", "city":"'.$city.'" } ] }'; echo $data; break;
case 'a->j': $data = '$.each(data.userdata, function(i,user){ var tblRow = "<tr style=\"background:#fff;color:#000;\">" +"<td>'.$_GET['method'].'</td>" +"<td>'.microtime().'</td>" +"<td>"+user.firstname+"</td>" +"<td>"+user.lastname+"</td>" +"<td>"+user.email+"</td>" +"<td>"+user.city+"</td>" +"</tr>" $(tblRow).appendTo("#userdata tbody");});'; echo $data; break; //** END AJAX->JSON REQUESTS **// //** BEGIN AJAX->AJAX REQUESTS **// case 'a->a': $reqData = parse_str($_GET['reqData']); $data .= '<tr style="background:#000;color:#fff;">'; $data .= '<td>'.$_GET['method'].'</td>'; $data .= '<td>'.microtime().'</td>'; $data .= '<td>'.$firstname.'</td>'; $data .= '<td>'.$lastname.'</td>'; $data .= '<td>'.$email.'</td>'; $data .= '<td>'.$city.'</td>'; $data .= '</tr>'; echo addslashes($data); break; case '->a': $data = '$("'.$_GET['dataIn'].'").appendTo("#userdata tbody");'; echo $data; break; //** END AJAX->AJAX REQUEST **// } break; //**** END GETUSERS FUNCTION ****// }
?>
//////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
Notes:
#########################
Javascript Variables
method = The type of request method being used, either a->a, or a->j.
request = the request being sent to json-request.php, in this example it’s “getUsers”
reqData = This variable is the initial data sent with the request. In this example it’s $(‘#user’).serialize(), or in other words, a serialized string from the user form on the page.
dataIn = This variable is the data recieved from the ajaxReq() function, and sent to the jsonReq() function. In a a->j method request, this data is the javascript function being sent from json-request.php, while the “data” variable is the JSON array that will be processed. In an a->a (ajax to ajax) request, this variable is the data that is going to be processed, while the “data” variable holds the javascript functions to do so.
#########################
PHP Variables
$_GET['method'] = the method of the javascript request being sent. (a->j or a->a)
$_GET['request'] = the request being sent, in this example it’s “getUsers”.
$_GET['reqData'] = This variable is the initial data sent with the request. In this example it’s $(‘#user’).serialize(), or in other words, a serialized string from the user form on the page.
$_GET['dataIn'] = In a a->j method this data is the javascript function being sent from the ajaxReq() function residing in the case: instance of a->j in our PHP file it won’t generally do any good to use this variable, as it’s meant to be passed primarily via javascript. In an a->a (ajax to ajax) request, this variable is the data that is going to be processed. In this example, it’s a <tr> of user information that can be found in the AJAX->AJAX case: section of the PHP file.
////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////
I use the php switch() function to determine what kind of request is being received. First, I determine what requests it is, which is “getUsers” in this instance. By doing this, we can have all of our functions and responses much more organised. Next, I break it down into what kind of request for “getUsers” it is. If $_POST['request'] == ‘ajax’, I return the Javascript function for the request in string/text format. If $_POST['request'] == ‘json’, I return the array data to the JSON based function. Once JSON has it’s array data, this is then parsed by javascript using the eval() function that is sent from ajaxReq(), to get our result!
Much thanks to http://jhoyimperial.wordpress.com/2008/07/28/parsing-json-data-from-php-using-jquery/ for the original article. I hope you found this mod/hack useful!