Tripping the JSON Dynamic – Using AJAX to send JSON Javascript functions

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!

CSS Center a div in a div. Make a div 100% height

There are two things that used to bug the crap out of me when I was designing a site. The first, was making a div layer take up 100% of the page, the other was centering a div in a div. The first thing you want to do is set the css html property to 100% height. This way, when you set the body element 100% height, it has something to relate the 100% to. Enough lollygagging. Here’s the code. You’ll also notice I included a centered div. This is accomplished by the “margin:0 auto 0;” setting. I hope someone finds this useful.


<style type="text/css">
html
{
height:100%;
}

body
{
text-align: center;
height:100%;
padding:0px;
margin:0px;
}

.mainDiv
{
margin: 0px auto;
height:100%;
background: #000000;
}

.insideDiv
{
margin:0 auto 0;
width: 300px;
height: 100%;
background: #FFFF00;
}
</style>

<div class="mainDiv">
<div class="insideDiv">
This div is in the middle of the parent div.
</div>
</div>

The death of websites, and the birth of web platforms.

You’ve probably noticed it via facebook, myspace, or the iphone. Slowly but surely the focus of software technology is shifting from creative thought & opinion to flexible platform development. If you create a website where people can recieve invitations and RSVP to a party or event, facebook can answer with “facebook invitations”. If you create a website where people can search for their favorite artists & play their music, myspace answers with “myspace artist/music search”, and the ability to “add songs”.

No longer is the internet a blossoming tundra of revolutionary ideas, but instead a collective corporate think tank that you never signed up for. Websites with one function are becoming a thing of the past, and multi-user platform flexibility has taken center stage. What happens to eBay if facebook comes out with an auction API and starts advertising it? Chances are they could easily buy ebay at this point.

Centralization of multi-faceted aspects of technological living is inevitable, yet the question remains as to who will hold all of the cards? While facebook is doing wonderful in the social arena, they pale in comparison to the depth and far-reaching arms of the google network.

The blunder of Google’s starting kick into the social realm can be attributed to their prominence as a search provider. It’s similar to if eBay announced they were “also covering local sports news”.

The sad part is that programmers and developers spend less time thinking of innovative platforms that run a function, and spend more time immersed in a sandbox with rules, predefined functions, and “second-to-market” dreams. Take for example the extreme drop-off in popularity of “myspace apps”, and the sudden surge of “facebook apps”. All that is happening is essentially a platform shift, and companies or individuals simply re-invent the wheel to appeal and run on the “new” platform – facebook.

The ultimate flaw in this model is the lack of support and communication between platform entities. Why couldn’t I import myspace apps directly into facebook, or vice versa? For that matter, whay are they not all using a similar app platform to begin with? What happens is that someone attempts to create a harmony between the two, and if one of the parties’ changes their architecture, the entire cross-platform compatibility crumbles to dust. The ultimate question in these situations is – “Ok, so who’s the bitch who does all the work to make this always work?”, and the other question being “Who’s the bastard who’s going to sabotage what I am doing by ruining compatibility?”. We see this all the time in SDK’s and API’s that “integrate with platform X”, yet you run into 256 bugs when you go through a tutorial using the latest version. This comes from one side not really giving a shit what the other side is trying to accomplish, or for that matter mayb not knowing about it. If you have 25 software apps trying to mesh with your SDK, and you change one bug to work better with one of them, you may have completely screwed up the other 24 apps. This is why centralization occurs.

Let’s take Google for the perfect example. You may have a website that uses a search string format such as – “http://www.website.com/search=tomatoes&menu=food”, but if you know anything about google, you’d know they absolutely despise search strings, even though they are an accepted standard throughout coding. So what happens? Rather than the programmer appealing to their first nature, and having the search string exist in his site, suddenly he or she is forced to learn mod_rewrites to make every page of the site appear as a *.html extension. While this can provide slight security through obfuscation, is it essential, or is it bending over and taking it from the big G?

Over time, we begin to see that creativity is being tunneled by rules, parameters, and platforms. You can’t simply make a decent website and expect something to happen. Now, you have to make the iphone app version, the facebook app version, the ipad version, the android version, the facebook profile for the app, the twitter update profile for the app, and that’s even before you look into how to advertise it. What happens because of this model is that one person can hardly make this happen alone, and so the corporations, once again hold the flag. What good are small business loans if they are within a fixed business model?

The only thing truly untainted and not for sale are your personal thoughts (*exception: unless you are a paid blogger) . The website of the future will more than likely be a module that rarely shows up in a search on “omninet.com”… Wait.. It is already kinda like that. :|

RE: Is WordPress destroying web design?

This post is primarily directed at you web designers out there. Not so much the “Graphic Designers”, but the all-encompassing designers who not only come up with the initial look, but also create the guts of the website itself. Last night, after I was finished with work, I was googling around and found a video titled “Is WordPress killing web design”. Quite an interesting perspective on web design in relation to WordPress.

For me, it was a no-brainer. The answer was clear as day – “kinda”. There is never going to be an absolute answer to any question like this, but we can all definitely agree that CMS systems have definitely changed the face of the internet. As designers & implementers, there is generally an all-around feeling of being under appreciated and/or not receiving credit where credit is due. We must, however, remember that our jobs as designers are to simply build systems for people, and improve them in all ways possible for our employers.

Regardless of how much we attempt to deny it, the matter at hand is personal pride in creating something from the ground up. If you start with a graphical concept, it’s simply a matter of modifying css & code within WordPress to attain the vision. With this being true, we can see that the real problem comes down to the bells and whistles (and how fickle your client is). WordPress is great for creating a website where you know the client may want to change page content now & again and/or post blogs on occasion. I’d almost say it’s ideal for that purpose. The hurdle of the situation is when your client says something like “I want a search engine so when they click on this thing it changes this list based on what they pick, then loads this image into that box”. I am talking of course about ajax requests & database actions.

Now while it’s possible to have php support & ajax functionality work great within WordPress, you suddenly have a new dimension of complexity to the site. Are you going to spend the extra time to make the search form into a plugin with a shortcode? What if they decided they wanted to change the layout of the search form down the road? The extra difficulty presented in these situation has to do with the conveniences of modular adaptability vs native coding. In the video above, one of the best points mentioned is that sometimes it’s simpler to build an entirely custom CMS than it is to hack the hell out of wordpress. I actually tend to agree, yet with the simplicity of SEO optimization and social aggregation built in to WordPress, I can’t help feel wanting.

In my personal opinion, WordPress *can* destroy a web designer if they are in web design for the wrong reasons. If you actually use WordPress as a creative tool rather than a means to an end, it can become invaluable, but if you are after immediate gratification and/or only monetary result, you’re a schmuck.