Facebook buys WhatsApp for $19 billion

What's App Logo, thanks to computerhoy.com and google image search.

What’s App Logo, thanks to computerhoy.com and google image search.

And I don’t care too much, really. I care that WhatsApp will be owned by a company that’s too big to fail, so that would guarantee me a long and prosperous lifeline with it, but overall, I don’t see any negatives. Of course, if Facebook decides to start adding ads, I will complain, but from what I gather, registering my wife up this morning with WhatsApp, it seems like they will charge me 99 cents per year to keep it going ad free. At least that’s what the news said too. WhatsApp will remain free of ads. I don’t mind that at all.

What’s really cool is that the guy that created WhatsApp, Brian Acton, applied to work for Twitter and Facebook and was denied, only have them pay him THAT much money. I guess that was a bad investment on their part. Karma’s a bitch!

Smart business decision? Definitely.

I’ve been saying this all along… Lazy programmers make for bad code

A link to an article about why code these days is so bloated.

I’ve been saying this for so long. Running a 3 mile race in 1 mile is not going to make you a faster athlete. It will weaken you as a performer. Get your ass off the couch, do the work, the right way, and always consider performance. Or, you get what’s coming to you. Adding frameworks and shortcuts to your development will only make you hurt later on.

Thoughts?

A New Way of Programming AJAX Style

As a programmer / web developer, I’ve been exposed to AJAX since before it was popular in jQuery. I remember creating my own $.ajax(); functions using XMLHTTP Requests, and other complicated javascript code and functions.

When exposed to jQuery, why reinvent the wheel? However, implementing the code to my current applications and websites was not that easy though. I wanted to create a sort of a system to integrate into a web app. Something that works for me. After many iterations, I came up with the following:

Where it all began

We need to trap the clicks to our app actions. In doing so, let’s look at the action buttons.

1
2
3
<body>
    <a href="#" class="btn" id="buttonone">Click Here</a>
</body>

And now, for the JS:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
$(document).ready(function(){
    $(document)on('click','.btn',function(e){
        // This makes sure we don't follow through on the click.
        // In essence, we cancel the initial click.
        e.preventDefault();
        // Now we make an ajax call.
        $.ajax({
            url: '/ajax/buttonactions.php?action=actionone',
            success: function(data) {
                // and we output our results
                console.log(data);
            }
        });
    });
});

And our complementing PHP action file.

1
2
3
4
5
6
7
8
9
10
11
12
// To make sure we set our action
$action = isset($_GET['action']) ? $_GET['action'] : '';

// call the function passed in from the ajax call
call_user_func($action);

// the function of the same name as the parameter
// as passed in from AJAX call.
function actionone() {
    // data to return
    return "data is back";
}

We don’t know what we’re going to do with our data yet, so let’s make it make some sense. We would like to return a JSON object from our PHP, because inside the JSON object, we can pass structured HTML, as well as other JSON data to be used by JS.

Our PHP has been updated with the following (Notice the JSON Encoded array returned at the end):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// To make sure we set our action
$action = isset($_GET['action']) ? $_GET['action'] : '';

// call the function passed in from the ajax call
call_user_func($action);

// the function of the same name as the parameter
// as passed in from AJAX call.
function actionone() {
    // data to return
    $retVal = array(
        "error" => false,
        "message" => "Data is back!"
    );
    return json_encode($retVal);
}

And now, to deal with the data on JS side. Make our AJAX call be of dataType JSON. We check to see if the data returned has the error variable equal to true or false. If false, continue.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
$(document).ready(function(){
    $(document)on('click','.btn',function(e){
        // This makes sure we don't follow through on the click.
        // In essence, we cancel the initial click.
        e.preventDefault();
        // Now we make an ajax call.
        $.ajax({
            url: '/ajax/buttonactions.php?action=actionone',
            dataType: 'JSON',
            success: function(data) {
                // and we output our results
                if (!data.error) {
                    console.log(data.message);
                } else {
                    console.log('data return error');
                }
            }
        });
    });
});

But this is not too much fun. All of the processing and rendering would have to happen on the JS side if all we return is JSON data. Let’s put things in arrays, and nest them for future use. Also, use our Output Buffer to do the work for rendering things.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<?php
...
function actionone() {
   
    $htmlToBeReturned = '';
    ob_start();
    ?><div>This is a block of HTML!</div><?php
    $htmlToBeReturned = ob_get_contents();
    ob_end_clean();
   
    // data to return
    $retVal = array(
        "error" => false,
        "message" => "Data is back!",
        "htmls" => array(
            "#buttonone" => $htmlToBeReturned
        )
    );
    return json_encode($retVal);
}
...
?>

Notice how we are returning HTML content inside our JSON object. It works really well too. json_encode takes care of everything for us. Also notice how we put our HTML return code inside another array called “htmls”. This is a great way to handle multiple HTML blocks that require changing. The great part about this is that you’re returning all of your data with one HTTP Request, one database call, and you’re manipulating multiple DOM blocks / elements. Another notice is the htmls object will contain the “selector” to be changed in the front end. You can have a string of these selectors, specific selectors, or a group of selectors, just like jQuery.

Our new JS code will look something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
...
            success: function(data) {
                // and we output our results
                if (!data.error) {
                    console.log(data.message);
                    for ($html in data.htmls) {
                        $($html).html(data.htmls[$html]);
                    }
                    $('body').append();
                } else {
                    console.log('data return error');
                }
            }
...

And now we see how easy it was to manipulate the DOM via ajax. You can improve on this model by templetizing the rendering to be able to re-use the same tempalte, you can add data objects to the click element and pass them in as post parameters, etc.

This is how we templetize the rendering of the HTML:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<?php
...
function actionone() {
   
    $htmlToBeReturned = '';
    ob_start();
    renderHtmlBlockOne();
    $htmlToBeReturned = ob_get_contents();
    ob_end_clean();
   
    // data to return
    $retVal = array(
        "error" => false,
        "message" => "Data is back!",
        "htmls" => array(
            "#buttonone" => $htmlToBeReturned
        )
    );
    return json_encode($retVal);
}
...
function renderHtmlBlockOne() {
    ?><div>This is a block of HTML!</div><?php
}
...
?>

You can move the render functions inside a file to be included from anywhere so you can avoid duplicate render code.

Let’s make the click dynamic.

1
2
3
<body>
    <a href="#" data-action="actionone" class="btn" id="buttonone">Click Here</a>
</body>

And adjust the AJAX call to fit in any action:

1
2
3
4
...
        var $this = $(this);
        var $action = $this.attr('data-action');
...

We cached the clicked object so we don’t have to constantly refer to it via jQuery.

And the url:

1
2
3
4
5
...
        $.ajax({
            url: '/ajax/buttonactions.php?action='+$action,
            dataType: 'JSON',
...

Now, your only worries are to make sure that you assign the data-action to the clicked element to call the proper action in PHP. HTML -> JS -> PHP -> back to JS -> back to HTML. Pretty clever, huh? Input -> controller -> model -> controller -> output.

And now, for the promised bells and whistles of passing data through data attributes. We already passed in one data attribute, the action, now, we just have to add more data, and change the type of the AJAX call to post.

1
2
3
<body>
    <a href="#" data-action="actionone" data-data="id=1&type=active" class="btn" id="buttonone">Click Here</a>
</body>

In the code above, we pass in a string of data that can be dynamically generated when generating the page with PHP. In essence:

1
2
3
<body>
    <a href="#" data-action="actionone" data-data="id=<?php echo $id; ?>&type=<?php echo $type; ?>" class="btn" id="buttonone"><?php echo $actionTitle; ?></a>
</body>
1
2
3
4
5
...
        var $data = $this.attr('data-data');
...
            type: 'POST'
...

And in our PHP code,

1
2
3
4
5
6
<?php
...
    $id = $_POST['id'];
    $type = $_POST['type'];
...
?>

And that’s it. You can always improve on the code, but this is the general idea to keep things simple and expandable.

The HTML File:

1
2
3
<body>
    <a href="#" data-action="actionone" class="btn" id="buttonone">Click Here</a>
</body>

The JS file, assuming you’ve loaded jQuery:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
$(document).ready(function(){
    $(document)on('click','.btn',function(e){
        // This makes sure we don't follow through on the click.
        // In essence, we cancel the initial click.
        e.preventDefault();
        // Now we make an ajax call.
       
        var $this = $(this);
        var $action = $this.attr('data-action');
        var $data = $this.attr('data-data');
       
        $.ajax({
            url: '/ajax/buttonactions.php?action='+$action,
            dataType: 'JSON',
            type: 'POST'
            success: function(data) {
                // and we output our results
                if (!data.error) {
                    console.log(data.message);
                    for ($html in data.htmls) {
                        $($html).html(data.htmls[$html]);
                    }
                    $('body').append();
                } else {
                    console.log('data return error');
                }
            }
        });
    });
});

And the AJAXed PHP code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
<?php
// To make sure we set our action
$action = isset($_GET['action']) ? $_GET['action'] : '';

// call the function passed in from the ajax call
call_user_func($action);

// the function of the same name as the parameter
// as passed in from AJAX call.
function actionone() {

    $id = $_POST['id'];
    $type = $_POST['type'];
   
    $htmlToBeReturned = '';
    ob_start();
    renderHtmlBlockOne();
    $htmlToBeReturned = ob_get_contents();
    ob_end_clean();
   
    // data to return
    $retVal = array(
        "error" => false,
        "message" => "Data is back!",
        "htmls" => array(
            "#buttonone" => $htmlToBeReturned
        )
    );
    return json_encode($retVal);
}
...
function renderHtmlBlockOne() {
    ?><div>This is a block of HTML!</div><?php
}

?>

Happy coding!

Bounce Effect in CSS Only Using CSS3

Ever wanted to have a nice bouncy effect when hovering over something without the use of javascript or hard to learn advanced code?
Use this for your HTML:

1
2
3
    <div class="bounce-cnt">
        <div class="bounce-r" id="the-button">asdf</div>
    </div>

And complement with this for your CSS:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
@keyframes hover-over {
    0% {padding: 10px; left: 0px; top: 0px; opacity: 0.7; }
    50% {padding: 16px; left: -6px; top: -6px; opacity: 1; }
    100% {padding: 13px; left: -3px; top: -3px; opacity: 1; }
}
@-webkit-keyframes hover-over {
    0% {padding: 10px; left: 0px; top: 0px; opacity: 0.7; }
    50% {padding: 16px; left: -6px; top: -6px; opacity: 1; }
    100% {padding: 13px; left: -3px; top: -3px; opacity: 1; }
}
@keyframes hover-out {
    0% {padding: 13px; left: -3px; top: -3px; opacity: 1; }
    50% {padding: 16px; left: -6px; top: -6px; opacity: 1; }
    100% {padding: 10px; left: 0px; top: 0px; opacity: 0.7; }
}
@-webkit-keyframes hover-out {
    0% {padding: 13px; left: -3px; top: -3px; opacity: 1; }
    50% {padding: 16px; left: -6px; top: -6px; opacity: 1; }
    100% {padding: 10px; left: 0px; top: 0px; opacity: 0.7; }
}

.bounce-cnt {
    position: relative;
}
.bounce-r {
    animation-name: hover-out;
    animation-duration: 0.2;
    animation-timing-function: linear;
    animation-fill-mode: forwards;
    -webkit-animation-name: hover-out;
    -webkit-animation-duration: 0.2s;
    -webkit-animation-timing-function: linear;
    -webkit-animation-fill-mode: forwards;
    position: absolute;
    top: 0;
    left: 0;
}
#the-button {
    border: 5px solid #000;
    background: #eee;
}
.bounce-r:hover {
    animation-name: hover-over;
    animation-duration: 0.2;
    animation-timing-function: linear;
    animation-fill-mode: forwards;
    -webkit-animation-name: hover-over;
    -webkit-animation-duration: 0.2s;
    -webkit-animation-timing-function: linear;
    -webkit-animation-fill-mode: forwards;
}

But you might say to yourself… “That’s a lot of CSS for one little effect”. That’s fine. Here’s why.
1. You’re not tying up the JS processing.
2. All you have to do is add class to a parent and child pair to make it look and work great, every time, without making the effort of re-writing bouncy code for every element.

Cheers!

What Makes a Solid Web Dev. Team?

Or for that matter, what makes a solid software development team? Let’s start with the product in mind. Whenever you look at a product, you really need to understand its purpose. Every team member has to. It’s a requirement, I think. You can’t just black box everything.

The Basics:
This is your fire team!

For starters, you need a solid squad. Yes, like in the military. You need highly trained specialists in 4 different areas:

  • Design
  • UI/UX
  • Product
  • Dev

With those four roles in mind, yes, you can have cross overs. A designer can do UI, but not as well as a specialist in UI.

Let’s see the roles as they play out:

Product: The key role in understanding what they product is, and why it will be useful to the audience. A product owner has to be an awesome communicator. He has to explain to design why certain things will be added, removed, or modified. He has to be sharp when it comes to technology usage. Has to understand SEO requirements, and the most important, has to keep the product simple enough for the end user. The product most likely will have to have an added benefit, not increase the workload of the end users. Need marketing? Someone to put out fires? Talk to the public? This is your guy! There could be several people playing a few roles on the product team, but essentially, product means business.

UI/UX: User Experience is what will make the product work for the user, not against. Working closely with the product owner, the UI specialist has to understand that red buttons don’t work, orange ones do, but not too many on one page. Place the OK and Cancel button far apart so the end user doesn’t have an “accidental” click. UI also comes in very handy for mobile devices where a touch of a small button could spell disaster. Keeping buttons consistent, such as OK and Cancel pop ups is pretty crucial to end user experience. It makes the end user more comfortable if they see the same flow all over the site instead of having Yes and No buttons appear from time to time, unless there’s a logical reason to use them. All this and more in the day of a UI/UX Developer.

Designer: Having a creative person on your team, keeping up with the latest trends and designs is great. Everyone is using the Windows 8 Metro theme because it’s nice, but also because it’s light for the web. Simple colors, non rounded corners, no drop shadows or gradients all make for a quick loading site. Little white icons on top can be placed in a sprite that only loads once, or can be included in as a special font. In any case, this guy needs to be able to provide awesome designs, and great looking interfaces, without sacrificing speed or ease of use for end users.

Developer: Last, but definitely not least, the guy or guys to glue it all together, the developer. This is your heavy machine gunner. He carries over all of the requirements and glues them together in a nicely and smoothly working product. He’s the Goldie Locks of the team. There has to be a balance of speed, performance, reliability, maintainability, and of course, design, UX and many more factors. This team can consist of other sub specialists depending on your application requirements. Maybe a server guy, with a database guy, a back-end server-side script developer and a front-end specialist to handle all of the bells and whistles. Very rarely will you find someone with all these experiences.

So, now you have your fire team armed and ready, locked and loaded, locked cocked and ready to rock. Set your missions, and go out there and conquer ground! Get an idea going, build a start-up, get funding and take over the world!

SEO for WordPress: Rank VS Tank

Definitely a not so discussed topic in my blogs. The ever evolving monster known as Search Engine Optimization is a huge consideration when driving traffic to your site… at no cost. Free. How much better does it get?

Recently, I started using some cool new tools from Google and the results are still standing by. Other than using Google Analytics to check visits to your site, using Google Webmaster Tools in combination with Google Page Speed developer tool, should help you not only achieve a cleaner and clutter less site, but rather a site that doesn’t get negative ratings from Google.

As we know, Google is still the most popular engine out there, and we want to make them happy. Recently, I like Google’s push towards more related content. Long gone are the days where losangeleslawyers.com was a good domain for SEO because the domain name had the three most searched terms when someone looked for Los Angeles Lawyers in google. Nowadays, it’s about branding. LoAnLa.com would rank much higher if the description of the site had to deal with LA Lawyers, and the content of the homepage was kept to a less than 200 words page all about the lawyers in Los Angeles.

Because I’ve mentioned them several times in this post, I might actually get dinged by Google since I’m not really talking about them in particular, but I’m only using them as an example. It’s good to keep relevant text on your site, and chose ONE subject to talk about. Don’t put all three of your businesses on one website hoping that you can do cross promotion or something crazy like that.

I hope this can help some of you out there to better rank your pages, rather than tank your pages.

Oh, and for goodness’ sake, clean up your HTML folks. If it doesn’t look good in IE8, it’s probably your fault. I had to spend an entire day tracking down an extra double quote in one of the ads I used. Valid HTML is definitely a plus when Google checks your site. Not only it makes your website faster to load (milliseconds), but visually, more attractive to IE visitors, and there’s about 13% of those around the web as stated by w3schools.com.

One last note. Stop saying SEO Optimization. You sound like a damn fool!

“Search Engine Optimization Optimization”, yes, that’s what you’re saying.

Happy Optimizing.

Site Migration Plugin for WordPress

I’m in the process of finishing up the first version of the plugin that will make site migration really easy for anyone who wants to migrate their sites entirely from one environment to another. This is a great tool for someone setting up their environments initially. Messing around with the database is not a great idea, so this plugin will handle all of the table copying, etc. The requirements are to have a repository in SVN. A future version will have other repository features, such as GIT.

And here’s the first version for your amusement. Modify to your heart’s content, and send me some notes. I know a lot can be fixed and re-factored to make it better.

okm-sitemover

How to Migrate a WordPress Project

When working on WordPress projects, and you need to migrate, let’s say from LOCAL to DEV, or DEV to STAGING, or STAGING to LIVE, whatever the case may be, you need to keep a lot of things in consideration.

Here’s my setup:

  • SVN holds any custom themes or plugins, not the core files, or config files.
  • Multi-tier environment with dropbox backing up local files. (LOCAL, DEV, STAGING, LIVE)
  • LAMP dev environment.

Before you migrate, setup WordPress:

  • Create an entry in the hostfile if necessary
  • Setup the vhosts file
  • Unzip WordPress in the new folder in all environments
    • public_html/newsite.com/dev
    • public_html/newsite.com/stg
    • public_html/newsite.com/www

Let’s go through the basic list:

  • Make sure core is not in SVN. Only keep changes, and new development in SVN.
  • Make a list of plugins used.
  • Extract WordPress in the folder you want to install the website.
  • Copy database to new database.
    • Change DB URL
    • 1
      UPDATE wp_options SET option_value = REPLACE (option_value,'old.domain.com','new.domain.com');
    • Typically from dev.website.com to stg.website.com for staging
    • And dev.website.com to website.com for live.
  • Copy wp-config file to new folder if settings are the same.
    • Change db login credentials.
  • Do a checkout of SVN project in doc root.
  • Re-install all plugins.
    • Configure plugins.

This should be it. I wouldn’t mind working on a custom plugin to handle all this. Maybe add some custom code to do svn updates on the other tier levels as well, so all I would have to do is click a button, and BAM, svn updates to next level.

I might even dedicate a page for this. Standby for this feature.

Clear floats with overflow: hidden

Lately, I’ve seen a trend of programmers adding on new elements to pages in order to add a class to them to clear all of the floated elements in a container. Why? Simply use overflow hidden on the parent, and like a miracle, bam! The container becomes aware of all of the children elements.

The old way:

1
2
3
4
5
6
7
<ul>
    <li><a href="/">Text</a></li>
    <li><a href="/">Text</a></li>
    <li><a href="/">Text</a></li>
    <li><a href="/">Text</a></li>
    <li class="clearfix"></li>
</ul>
1
2
3
4
5
6
li {
    float: left;
}
.clearfix {
    clear: both;
}

The old way is not as effective, since we have to add additional elements that do not show anything. Their only purpose is to fix a css style. Why not do it in css? This method also adds what seems like an additional line that makes it seem like you have bottom margin, or padding. Too much to maintain and fix. Additionally, I believe at the time of this writing, google looks for empty elements and dings you if you don’t put anything in them. Validate your HTML. Be a good programmer.

The new way:

1
2
3
4
5
6
<ul>
    <li><a href="/">Text</a></li>
    <li><a href="/">Text</a></li>
    <li><a href="/">Text</a></li>
    <li><a href="/">Text</a></li>
</ul>
1
2
3
4
5
6
ul {
    overflow: hidden;
}
li {
    float: left;
}

Who’s JSON?

J. S. O. N. Actually

Not sure where I’m going with this, but here we go. I like JSON (JavaScript Object Notation). What’s that, you say? You mean, who’s that? Oh, wait. No, it’s ‘what’s that’.

What I’d like to start with is something experimental. Let’s focus on the idea that there is a back-end, and a front-end to any development, especially web development, and especially web application development. What if both sides could simply just communicate with itself via JSON. Why JSON? Because JSON is super light weight for transferring data. What kind of data, you ask? Any kinds. Sure, we could render out code via an AJAX call as HTML, but all those little extra tags are overhead. JSON keeps it simple with only one or two additional characters per variable or value. Let me show you what I mean.

1
var myObject = { "person" : { "fname" : "John ", "lname" : "Donson"} };

Notice what happens in the block of code above. I’ve specified an object with enough information to arrive at the conclusion that this data is related to a person, and their name is John Donson.

jQuery can easily do this JSON encoding from arrays, strings, etc. You just need to pass it the variable:

1
var myObject = $.parseJSON( '{ "person" : { "fname" : "John ", "lname" : "Donson"} }' );

Please note that I’m using double quotes inside the object itself. This is proper JSON format. Escape any single quotes with backslashes. This gives us an object that we can easily inspect in the console log of Firefox.

All right, now that we understand who JSON is, let’s have fun with him.

HTML5 Kicks in

Wouldn’t it be great if we could use HTML5 to send some data to JavaScript who can in turn send the data to the backend (PHP), who can then get some data from a database and return back some JSON code that we can use back in JS to manipulate elements in HTML5?

Wow, I mean, why even go down this road? Simple. Large amounts of data to be processed. PHP may be fast at 300 requests per second, but HTML is even faster, with 1000 requests per second. The idea is to develop for online applications. Such as, a game, or management systems.

Let’s start from the top. Here come’s < a >.

1
<a href="javascript:void(0);" class="jsonCall" data-get='{"url":"/ajax/main.php","data":{"var1":1,"var2":2}}'>Click me!</a>

Whoa, why all this? Let me break it down.

– The void call in the JS call is to make sure older browsers don’t show a white page when clicked.
– We’ve added a class because we want to identify any element with an action. Doesn’t have to be an < a > element.
– data-get is our HTML5 way of introducing data that we will need. This is our JSON data that we will send from JS through our AJAX call.

Let’s see where this takes us.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
$(document).ready(function(){
    $('.jsonCall').on('click',function() {
        var queryVars = $(this).attr('data-get');
        var qJSON = $.parseJSON(queryVars);
        var qString = "internal=true";
        for (data in qJSON.data) {
            qString += "&"+data+"="+qJSON.data[data];
        }
        $.ajax({
            url: qJSON.url,
            type: 'post',
            data: qString,
            dataType: 'JSON'
        });
    });
});

This is the entire code we need to parse out our data-get attribute value and send it out for processing. Let’s put what we did into practice.

Practice Makes Improvement, Because No One is Perfect

Let’s say we want to load a list o thumbnails with descriptions and links to another page. So, let’s set up the scenario.

What we need:
– link
– thumb
– text

There’s the classic way and try to render everything out on the backend, and spew out some static html that can be placed inside our “container” whatever that container will be.

Why not make it smarter, and just send a request for the items you need. Let’s say you need 16 thumbs because that’s how many thumbs will be on the page at once. Yes, you can always change this number, but 16 is perfect for a 4×4 display of thumbs.

First, we need to understand what our content might look like. It will probably look something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<ul>
    <li>
        <a href="">
            <img src="" />
            <span></span>
        </a>
    </li>
    <li>
        <a href="">
            <img src="" />
            <span></span>
        </a>
    </li>
    ...
</ul>

Ok, it will be a little more intricate than that, but here’s the reason to load your content with JSON. All of this above is simply overhead. None of our data has been loaded yet. There IS no data! So, with all this effort of rendering out, we got back a big fat nothing.

Why not templat-ize the results? It would make much more sense. Why not load the template HTML content inside our current document so we can just use it? Since it will be used anyway on the page, load it up, but keep it hidden.

1
2
3
4
5
6
7
8
<script id="content-list-item" type="text/x-jquery-tmpl">
    <li>
        <a href="[[url]]">
            <img src="[[thumb]]" />
            <span>[[text]]</span>
        </a>
    </li>
</script>

This would allow us to get the content via the jQuery.html() function, replace the values inside the double brackets, and append this element to the container.

Doesn’t make sense yet? Let’s compare the old way we used to do things. If we had a loop of items on a page, we would render everything at the php level right after we got the data.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?php
$qty = $_POST['qty'];
$retVal = array();

for ($itemCount = 0; $itemCount < $qty; $itemCount++) {
    ?>
    <li>
        <a href="http://www.motortrend.com/roadtests/oneyear/coupe/1302_2013_scion_fr_s_arrival/">
            <img src="http://i2.squidoocdn.com/resize/squidoo_images/-1/lens10584771_1271704447MARIO_thumbnail.jpg" />
            <span>2013 Scion FR-S Arrival</span>
        </a>
    </li>
    <?php
}
?>

This would be fine, if the data would remain minimal, but where are your alt tags, title tags, what if you use itemprops for SEO results. All that is additional overhead.

Our template contains almost the same amount data returned as JSON. The reason being is that we’re not returning

1
<a href="

as data, but we’re most likely returning

1
{"

instead. Less code already.

But, you say, the difference is not that great. We went from 236 bytes to 258 bytes. It’s not a huge difference. It’s about 9%. I’m not impressed.

Ok, what if you do add those additional items, like title, alt, propitem, etc… And what if you have additional wrappers and other overhead HTML that repeats? Your template only includes this once. The rendered version of your code returns this 16 fold. Let’s see the difference between.

235 to 305!!! How’s 30% increase in your data for a significant enough number?

In Conclusion

So, when comparing the two methods, you notice that our template has been increased by a few bytes.

1
2
3
4
5
6
7
8
<script id="content-list-item" type="text/x-jquery-tmpl">
    <li itemprop="stuff">
        <a href="[[url]]" itemprop="url" title="[[text]]">
            <img src="[[thumb]]" itemprop="image" title="[[text]]" alt="[[text]]" />
            <span>[[text]]</span>
        </a>
    </li>
</script>

Our JS has not increased since we’re just reusing the same references for the alt, title, etc tags.

While the oldmain.php rendering file has increased a bit more than the template file, this repeats several times, significantly increasing the size of data transferred back to the client.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?php
$qty = $_POST['qty'];
$retVal = array();

for ($itemCount = 0; $itemCount < $qty; $itemCount++) {
    ?>
    <li itemprop="stuff">
        <a href="http://www.motortrend.com/roadtests/oneyear/coupe/1302_2013_scion_fr_s_arrival/" itemprop="url" title="2013 Scion FR-S Arrival">
            <img src="http://i2.squidoocdn.com/resize/squidoo_images/-1/lens10584771_1271704447MARIO_thumbnail.jpg" itemprop="image" title="2013 Scion FR-S Arrival" alt="2013 Scion FR-S Arrival" />
            <span>2013 Scion FR-S Arrival</span>
        </a>
    </li>
    <?php
}
?>

Another benefit is that the template can be changed as an individual file. So, if designs change, you never have to bother the back-end developers, unless new data is necessary for the items retrieved, but that’s a data issue, not a design issue.

Updates to the other files:

The call is being made from here

1
2
3
<a href="javascript:void(0);" class="jsonCall" data-template='#content-list-item' data-container='#my-container' data-qty='16' data-action='getmario'>Click Me!</a>

<div id="my-container"></div>

The JavaScript updated file

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
    $('.jsonCall').on('click',function() {
        var template = $(this).attr('data-template');
        var container = $(this).attr('data-container');
        var action = $(this).attr('data-action');
        var qty = $(this).attr('data-qty');
       
        $.ajax({
            url: '/ajax/main.php',
            type: 'post',
            data: 'qty='+qty+'&action='+action,
            dataType: 'JSON',
            success: function(data) {
                $(container).html('');
                var templateCode = $(template).html();
                for (var itemCount = 0; itemCount < qty; itemCount++) {
                    templateCode = templateCode.replace(/\[\[url\]\]/gi, data[itemCount].url);
                    templateCode = templateCode.replace(/\[\[thumb\]\]/gi, data[itemCount].thumb);
                    templateCode = templateCode.replace(/\[\[text\]\]/gi, data[itemCount].text);
                    $(container).append(templateCode);
                }
            }
        });
    });

The ajax called JSON returning php file

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<?php
// a sort of a controller to get the right function to run
if (isset($_REQUEST['action'])) {
    switch ($_REQUEST['action']) {
        case 'getmario':
            getMario();
            break;
    }
}

function getMario() {
    // normally would make a database connection to populate the data,
    // but that's not what we're testing here.
    // We only made one connection per call anyway.
    $qty = $_POST['qty'];
    $retVal = array();

    for ($itemCount = 0; $itemCount < $qty; $itemCount++) {
        array_push ($retVal, array(
            'url' => 'http://www.motortrend.com/roadtests/oneyear/coupe/1302_2013_scion_fr_s_arrival/',
            'thumb' => 'http://i2.squidoocdn.com/resize/squidoo_images/-1/lens10584771_1271704447MARIO_thumbnail.jpg',
            'text' => '2013 Scion FR-S Arrival'
        ));
    }
    $retValJSON = json_encode($retVal);
    echo $retValJSON;
}

?>

Just to show once again that the more complex your html will be, the more data you are returning the old way, whereas the new way, you are barely adding anything at all to the data coming back. In the long run, you will benefit significantly from the template way of doing things.

Changed the oldway file:

1
2
3
4
5
6
7
8
// from
...
<li itemprop="stuff">
...
// to
...
<li itemprop="stuff" id="item_<?php echo $itemCount; ?>">
...

Changed the template file:

1
2
3
4
5
6
7
8
9
10
11
12
// from
...
<li itemprop="stuff">
...
// to
...
<li itemprop="stuff" id="item_[[id]]">
...
// and added this line to our array of data
...
'id' => $itemCount,
...

Minor changes, HUGE difference. The new results are in, and the new way has gone up to 268 bytes, while the old ways have gone up to 353 bytes. Now we’re at 31.7% increase which goes to show you that we went from just under 30% difference to 31.7% (almost a 2% increase in bandwidth, just from a single change). This might be nothing when considering the small size of data, but for multi million user websites this number can be real significant. And it separates your code better.

Yes, you will use up more space initially when loading the templates. About 115 bytes more, but in the long run, there are greater benefits.