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!

The origination of my hobby Soup Website

So I had a long stretch of time where I had *absolutely* nothing to do. I didn’t have a room mate, a girlfriend, or any friends really for that matter. I’d come home, and make myself a soup out of whatever weird stuff I felt like, then go to sleep. Then I’d get up in the morning, make myself some liquid crack (aka coffee), then develop websites all day.

Whenever I checked in with my boss, she’d notice how I had an odd routine of watching X-Files, and having the same soup every day. Suddenly, the idea came to me to make a website for people who make soups out of stuff around their kitchen. The minute it came to mind, I laughed because I knew how unsuccessful and unpopular it would be, BUT it gave me something to do for the times when I had nothing to do, which was exactly what I needed, and occasionally it’s nice to share a soup that is tasty with other people who like soups. It was named “OopSoup” after the freaky spicy imitation crab based Matzo soup that had become my daily monotony lifeblood. I have since renamed it to “Matzo Crab Soup”, to be a bit more descriptive of what it contains. I may have to create a superior soup to dub “Oop Soup”, but have been eating a lot of hummus and veggies lately instead of soup.

Within a few months of coding in my spare time, I had a stable beta running online. I *only* worked on it when I felt like it, which was amazingly nice, so there was little to no stress involved (heavenly). I notice today that people who worry too much go bald way too fast because they are stressed out all the time about being the first to succeed or make something (I win! I win!) . I had lived like this in the past, and my hair has totally thinned from it, so now I shave my head all sexy-like, but this makes me work out, or the bald-thing FAILS on me.

So there was a point I was working on OopSoup where the thought crossed my mind to have a gnome throughout the site. I attribute this to watching “David the Gnome” on Nickelodeon every day, and thinking how cool he was for riding a Fox around, (who was also his friend) and tricking or capturing Trolls that were up to no good. I also collected gnome statues for a while.

The future plans for it are in development, and surprisingly I managed to rank top on Google for the phrase – Matzo crab soup, …. and the mild interest builds in suspense. :p

For those of you who have visited my website, and possess James-Bond-like detecting skills, you will have notice that the logo contains the soup from the actual photo of the soup. I’d give you a “super sleuth” button, but I’m all out.

I am not going to use a closing statement in an attempt to try and entice you to visit it all the time and post your failed soup inventions, but if you have nothing better to do, it’s kind of fun if you like sharing your rebellion against conventional cooking rules like me.

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.