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!

Animated Gifs make me happy.

Every once in a while I stumble upon something from the past that makes me smile. It generally is something that’s ignored every day, that I push to the side or forget about until magically, it’s back in my life and bringing me more enjoyment than the latest gadget, gizmo, or dynamic ajax script.

I am speaking of course, about animated gifs, and so I’d like to share my recent finds with you. All courtesy of http://www.gifandgif.eu/

The dancers seem to love dancing along to Pendulum.


Technology is becoming a parent.

As technology seems to be at the forefront of every human’s life, we should really stop and ask ourselves what we are setting the future up for. A future where boyscouts are using google on their Android phones to find out which berries are edible. A future where the “Boyscouts of America” (the very supposed aspect of learning “survival”), embrace a computer as if it might be growing near a mushroom next to a waterfall somewhere.

We are slowly, but surely destroying the basis of human communication and knowledge, and replacing it with the cool, sleek modern interface of an operating system. We’re so “advanced”, that in about 5 years there will be children googling on how to tie their shoelaces because Mommy is chatting on Facebook all day while Daddy’s looking at porn in the basement.

Ultimately we should be asking ourselves what the true draw is. I would have to say it’s that everyone is somewhere at the same place, and you can talk to them all at the same time. Subconsciously it’s somewhat like this big party, just for you, where anyone and everyone in the world can talk with you, while the real-life repercussions are detachment from societal forms of communication due to lack of actually using it. The more that people work in “Yeah, here’s my e-mail”, the more that people begin to see it as a possible means of actually knowing who someone is. Here’s the psychological-psychotic kicker……

In reality when someone says something to your face, there will always be the judgement aspect of us that recognizes if they are being deceitful, or if what they say is the truth. Technology creates a “buffer”, where people no longer have to worry about such things. So you get people hooking up online all the time, and having “online relationships”. It’s similar to a romance novel, other than one pitfall. The responses might as well be a script from a shitty Hollywood movie. They’re thought-out, well organized, sardonic, but completely lame. While we revel in the ability to be “witty” on the internet, we lose the most important aspect of what it is to be a human being…. Shooting from the hip.

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>

Inner peace is a load of crap.

I truly hope that the many spiritual gurus and “walkers” of paths find a reason to debate my philosophy, to not only allow the disproving of the peace that supposedly exists in their teachings, but to also prove themselves ignorant enough to try and disprove a personal perception written up on a net blog.

In life, we often find ourselves needing to feel that we found something “right” in our lives, or an “answer”. The interesting fact is that I personally never wanted or needed this until I was told I needed it at a young age. We can’t simply let people live in contentment of life alone… No no no… That would be wrong to let someone simply enjoy their life on planet earth. We should instead create a story or belief that makes their lives feel small and inconsequential in comparison to something else.. But what? Let’s just call them “Gods”, and let’s say that you aren’t good enough just being you, but that you need to be “enlightened” or something. As if just being yourself would ever be enough…. Well hmm… I guess spirituality is run by people who don’t want me to be just me? Suddenly your carefree attitude and endless childhood days are shadowed a dark thought pattern.

Now there are these new things in your life that you can’t see, hear, or talk to, but they apparently have divine judgment, and everything you do is a tally mark on what they decide happens to you in the after life. Sad to say, this belief structure provides nothing but 1. the ability to shift blame onto something imaginary (a deity) 2. A scapegoat and excuse and/or cover for being “unique”/special 3. A reason to argue or disagree with others based not on principles, but “faith”. While contentment and mind relaxation/inner realizations can help us grow as individuals, ever since I have heard the term “inner peace” it’s been like a frickin foot race to see who the most fakey “spiritualist” is. It’s like a world full of actors who actually ACT spiritual.

The darker aspect of this spiritual cloud of crap are the people who are convinced that they need to “seek inner peace”. Well that’s funny…. I never received inner peace in the mail, but have been having a decent time without it. In fact, now that I think about it, I only felt bad when some piece of crap told me I didn’t have it. This is unfortunately the equivalent of pretending to have something special or different that elevates one’s self above others. In a supposed world where true spirituality is that we are all unified, living beings, you’d think that reverence would have gone away with the feudal ages and the inquisition, and we’d probably be cracking jokes with the pope more often.

To elevate one’s self above others in any way, shape or form is to simply (and subtly) be a part of the new breed of hate that exists in the world. It’s essentially a form of being upper class for people who can’t truly afford to be. Anything for any of us to be able to snub our noses at each other in some subtle way. God forbid if we all agreed on one common bond and mystery – life itself. Apparently it’s not enough anymore, and we need things like a dude on a cross, some prophet who can see the future, dragons, 8 armed elephant headed gods, and angels flying around with trumpets out their asses.

The true beauty is that we get *so* offended when someone insults these conceptual ideologies, that we have war, death, and argument, yet everyone fails to see that throughout it all, the “deities” haven’t showed up…. once.

Installing Ubuntu Using Virtualbox

This is a short tutorial for people who want to try out Ubuntu but don’t want to completely wipe out their OS (yet) to do so.

First thing’s first, download a copy of VirtualBox from http://www.virtualbox.org/wiki/Downloads

If you are having trouble seeing what you should download, it’s the links under the “VirtualBox Binaries” heading. Just match to your current Operating System (Windows, Mac, Linux).

**If you are already on Ubuntu, but need Virtualbox, go to your Ubuntu Software Center, and type “virtualb” into the search bar. Download and instal VirtualBox OSE.

Once you have VirtualBox Installed, it’s time to get the image for Ubuntu. Since we want Ubuntu to be installed, and also have fullscreen enabled, we’re going to use the 10.10 build.

Go to this address to begin the download of Ubuntu 10.10 – http://releases.ubuntu.com/10.10/. If you have a 64 bit processor, be sure to get the 64 bit version.

Next, create a directory for your VirtualBox images. You can place them wherever you like (ie: C:\Virtualbox\ or maybe C:\User\Uname\Desktop\My Stuff\VirtualBox.. ). Move your downloaded iso to this directory.

Next, start up VirtualBox, and click the “new” star-like icon in the top-left area. If you need to, click the “Next” button to get past the intro. On the next screen, in the name field type “Ubuntu 10.10″ select “Linux” as the Operating System, and “Ubuntu” as the Version, click “Next”.

Next, we have to set the Ram Size. Set it to something reasonable based on how much RAM you currently have. Ubuntu runs great with even 1 gig. Click the “Next” button.

Next, we have to create a virtual Hard Disk. Click Next to begin the Hard Disk wizard. Click “Next” Again to skip the intro. I’d set it to default (dynamically expanding) simply because the hard disk can grow to accommodate your info on the virtual OS. Click next, and set it to something reasonable like 10 – 35 gigs.
Click “Next”, and it will tell you it created a .vdi hard drive. Next click “Finish”.

You’ll see the VirtualBox area update with the OS we are creating. Now we want to go into the settings to set the iso image as our boot media. Click on the “Settings” icon. In the left control column, click “Storage”. Now we want to add a cd-rom image to boot from. Click the small plus over the round cds located at the bottom of the pane, then select “Add CD/DVD Device”. Select “Choose Disk”, and browse to the location of your iso file. Once it’s been selected, click “OK” to close the Settings.

Now we can boot up and install Ubuntu. Just click the green “Start” Icon to boot up. You’ll be greeted with a black screen with a little keyboard at the bottom, at this point, hit a key on the keyboard. This simply tells Ubuntu you want to boot from the cd. Now you can install ubuntu.

For instructions on making Ubuntu 10.10 run fullscreen (after you have installed), proceed here – http://www.unixmen.com/linux-tutorials/1157-install-guest-addition-in-ubuntu-1010-maverick-meerkat-fix

Mornings

Waking up this morning was not as fun as it usually was. It was one of those days that you wake up to find out it’s freezing cold outside, and hate to even move outside of the perimeter of the blanket. When I am waking up, I have one of two instant destinations. I am either heading straight for the shower, or I am heading straight for my instant coffee (yes, I like instant coffee), and then for the shower. Unfortunately, this morning was so cold that neither could save me. I woke up grumpy. Sure, I’m packed pull of caffeine now and didn’t have any road-rage incidents, but it’s just one of those days where you want to stay in bed and nap all day.

I think my room mate must have gone running last night, as I saw his running shoes by the door (new). I completely forgot to wash my breakfast dishes this morning. Whoops. I wonder if anyone else is feeling like today is extremely lazy feeling.

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.

Hierarchical Idiocracy

In our now-failing United States economy, the true groundwork of the country is beginning to finally shine through. Now of course, the large business firms remain primarily unscathed, although the illusion of a “company collapse” may provide a “clean out” for the fatcats behind the excel spreadsheet numbers. The true disgust of this business model is that manual, physical labor has completely vanished from the elite management spectrum. Sure they make make an angry phone call, or offer their sacred opinions, but primarily attempt to rule psychologically and with information control.

This shift in the way that humanity operates has not only created an even wider rift between social classes, but it’s created an illusion of power. The term “power” in itself is a conceptual explanation for availability and apparent exercise of control over resources. Given that this fails, the individual is considered a failure with it. Constant maintenance and establishing possible outcomes of uncontrollable variables is the central operating force of this ideology. The failure of it is decentralization of the parties responsible for this. In layman’s terms – Where corporate structure and capitalism failed was in delegating tasks they couldn’t accomplish themselves. But they sure are good at crunching numbers.

Earlier in this century, kings of industry knew the parameters of any job they had assigned to anyone under them, or at a minimum hired a management position to delegate and maintain these positions. Innovation, industrialization, and creation flourished, then along came “micro-management”. The term “micro-management” is simply the most idiotic concept to date. We all find the term familiar, but what does the core of it convey? Let’s examine –

Micromanagement (via wikipedia.com):
micromanagement is a management style where a manager closely observes or controls the work of his or her subordinates or employees. Micromanagement generally has a negative connotation.

The problem?

Well, the “problem” is that workers spend X amount of minutes they could be using for labor creating a report, or tracking their statistics. Not only is the mind of the employee pre-occupied with tracking details for someone who is too fucking lazy to track it themselves, but productivity is cut annually due to the idiots spending X amount of days firing the guy who just happens to hate wasting his time on reports for lazy people, and keeping the lazy bastard who “just needs to focus more”. It’s asking you to fill the void of being a “manager” (subtley called something like “team leader”, because the coporation believes in “family”) , while milking the money you make for them. Kind.

Now of course, the economists argument for this is that “it rounds out”, or that “there is a balance to it”, yet no one’s been able to find that balance. The balance seems to be smooth talking slimeballs who are freaking out because of the crumble of their schemes. It’s actually quite ironic. As the American economy finally becomes focused and controlled by the few powerful elites, the people who can’t manage to live simply freak the hell out and grasp at straws, while people used to living simply don’t even seem to flinch. Strange.

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. :|