Toggle Functionality for Clean PHP

Requirements:
* jQuery
* Font Awesome
* AJAX capabilities
* .hidden = display: none;

So, I decided that just controlling the front end via the back end wasn’t enough. I debated for a long time and was reluctant to add new functionality to the ajax controller… then I realized that I’m using a lot more of this functionality, so, I caved in.

This complements the ajax functionality by adding a toggle feature for either items that toggle out (2 state on/off), or items that toggle other elements on or off; still 2 state.

The first thing I did was to add some classes to the elements that will perform the toggling. I added a wrapper around two elements (the togglers) and proceeded to play around with them.

1
2
3
4
<span class="trigger-wrapper" data-trigger="toggle">
    <a href="" class="tmbtn trigger hidden" data-action="test_toggle"><i class="fa fa-toggle-on"></i> Active</a>
    <a href="" class="tmbtn trigger" data-action="test_toggle"><i class="fa fa-toggle-off"></i> Inactive</a>
</span>

The trigger-wrapper class was added to wrap everything in one molecule.

I added the data-trigger attribute to the wrapper because this is what will determine what toggle type to perform… Is it a straight toggle of two items, show / hide an element, or both?

The trigger classes are what determines what triggers the toggle. These trigger elements will swap out their hidden classes. That’s how they toggle.

Here’s two more HTML examples of the content pieces:

1
2
3
4
5
6
<div class="trigger-wrapper reset" data-trigger="dropdown">
    <a href="" class="tmbtn trigger" data-action="test_toggle"><i class="fa fa-ellipsis-h"></i></a>
    <div class="target hidden init-hidden">
        [Content]
    </div>
</div>

… and…

1
2
3
4
5
6
7
<div class="trigger-wrapper reset" data-trigger="dropdown-toggle">
    <a href="" class="tmbtn trigger hidden init-hidden" data-action="test_toggle"><i class="fa fa-chevron-up"></i> Show Less </a>
    <a href="" class="tmbtn trigger" data-action="test_toggle"><i class="fa fa-chevron-down"></i> Show More </a>
    <div class="target hidden init-hidden">
        [Content]
    </div>
</div>

Notice how these last two items had the “init-hidden” class added, and the togglable content has “target” on it.

Now, for the JavaScript (jQuery) that drives the whole thing… (Assuming that .hidden already exists in your CSS as display: none).

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
...
var _toggle_type = '';
...
var $parent = $this.parent();
...
if (typeof($parent.attr('data-trigger')) !== 'undefined') {_toggle_type = $parent.attr('data-trigger');}
...
// In the ajax call of the JavaScript file (data is what comes back in the success function) ...
data._toggle_type = _toggle_type;
data.$parent = $parent;
postAjax(data);
...
// And of course, the switch case for the different toggles...
switch (data._toggle_type) {
    case "toggle":
        data.$parent.find('.trigger').toggleClass('hidden');
        break;
    case "dropdown":
        data.$parent.find('.target').toggleClass('hidden');
        break;
    case "dropdown-toggle":
        data.$parent.find('.trigger').toggleClass('hidden');
        data.$parent.find('.target').toggleClass('hidden');
        break;
}
...

So now, we have a lot of the functionality to handle our togglability.

This completes our addition to the Clean PHP code that I’ve been working on here: https://github.com/gbutiri/cleanphp

PHP Frameworks Suck

It’s kind of funny. After trying to understand Zend 2, I decided that I was happier with Core PHP. I noticed that anyone can pick up any framework and learn it in a few days, or even a few weeks, but to master it, you really need to spend a lot of time with it. I’ve spent 11+ years with PHP at the time of this writing. I know PHP.

Why have any framework? For most do it yourself type projects, just build a website from the ground up. You already have 4 great layers (Apache or server, MySQL or Database, PHP or backend language, and HTML, CSS, JS all in one). This looks like a LAMP stack to me. Why do I like keeping it this simple? Well, you don’t “need” anything else. Really. This is all you need to build anything. And I do mean, ANYTHING! You name your project, and i can build it.

My only caveat is jQuery. I’ve gotten used to it over the years, and in a way I wish I could go back to plain JS. I mean, for the most part, I still use JS, I just use jQuery for selectors / DOM manipulation, events, and the ever so simple to use ajax function. The main reason I use jQuery is because, otherwise, I would just write my own functions to do all these things. jQuery just makes sense to use.

My next task is to convert all my jQuery into JS at some point. Why? Because that’s what the browsers understand. The browsers don’t understand jQuery, or angular, or LESS or SASS on their own. They need pre-processors and libraries to convert all that.

This brings me to my other point. The backend should be no different. PHP is what is already installed on the server. Running PHP code in your files speaks directly to the PHP installation on Apache. You don’t need additional overhead to make things work better. Write PHP, done. You can structure your PHP in logical functions to make it work for you, such as getMeSomeData(), or renderThisHtmlBlock(). But that’s it. At its core, PHP is a great and most opened and powerful framework of all. Why add so many layers of abstraction on top of it?

My next good practice is to write MySQL directly into my php code. Why not? That’s the fastest processing you’re ever going to get without involving overhead. Use propell? Why? Just so you can stack php functions that eventually build out what you meant to say with MySQL anyway? Again, more layers of abstraction? What’s the point? Because it doesn’t “LOOK” like SQL? Is that really a valid excuse? Learn some damn MySQL like a good programmer, and remove all those PHP overhead functions to keep your site optimal.

It’s not what you use, it’s how you use it. Developers have become so lazy over the years, and no one cares about code itself. They treat it like they’re bored of it and just need to add layers of complexity.

The only thing that matters is how the client side performs. All of my projects’ pages load faster than 2 seconds, out of which most load under 1 second. In the end, that’s what matters. And, the turnaround time for most of my development is minutes, not days like most projects dependent on builds.

And I simply don’t want to discuss things like memcached, composer, ruby (for SASS), or any other dependency that’s simply not necessary. Are your websites fast? Then, that’s what matters. I worked at this one company where they would be concerned with micro optimizations such as to use array brackets instead of array_push function. At the same time, they were using propel that would run through dozens of php functions to get data, and their pages were loading in over 4 seconds, with unoptimized images, and over a hundred http requests. I just don’t understand this sort of mentality. These things should matter no matter if you are running an SEO site, or a private LAN intranet. Users will complain when your site loads in over 2 seconds. That’s a rule.

I’ve built many systems over and over and over only to come to the same conclusion. Simplicity just works better. Ask Steve Jobs.

The reason Angular JS will fail

ANGULAR JS WILL FAIL UPDATE: 2/25/2017

Another reason why Angular js will fail. Not even a year later and the 4th version is already being discussed and developed. Are these guys morons? I suppose angular 1, 1.5 and 2 has failed so badly, that they made an even worse version that was never even released. That’s right, completely skipped angular 3. And now we’re onto 4. By the time I get done writing this update, I might have blinked and missed angular 20. I should hurry up.

I would love to see all those defenders of the past versions come see how stupid (I can’t find any other words) their defensive comments really were. It’s like a sick joke. Within the time it takes to go through college, angular has changed dramatically through its 4 iterations. How are true developers supposed to take angular serious anymore?

Going from JavaScript to typescript and then ECMA 6 or 7 does not help its case to be a great framework. Meanwhile, I’ve completed about half dozen applications / CMS systems on my own using good old JavaScript, jQuery and my good ol’ dispatcher, found here at dispatchjs.com. I still use php 5.6 and mysql 5.6 to manage logic and data. I’m still trying to wrap my head around the complexities of angular 1.x.

Yes, I understand that technology needs to move forward, but you have to follow design rules, even in development. Creating a door without a handle may look trendy, but your average person won’t know what to do when they come face to face. Same with development. Creating a framework that only a few elite can understand is bad practice for the whole development community. Please learn a few lessons from this.

I would love to see angular succeed, but at the pace it’s going… it’s never going to happen. They develop the framework like nothing will change around it, and in one or two years, standards change, morph, or even go away altogether. Perfect example is jQuery. JavaScript has changed a lot since jQuery first came out, but instead of fighting it, jQuery embraced it. You can still use an older version or jQuery, or a new version of jQuery. The compatibility is still there on any major browser. And yes, jQuery might have made some weird decisions along the way, but it’s still standing strong.

Note to the angularjs team: You claim you’re smart, so learn something from this. They won’t. For this reason,¬†Angular js will fail.

ANGULAR JS WILL FAIL UPDATE: 11/19/2016

So, angular 2 is out and it’s not as easily accepted, even into the angular 1 community. A lot of programmers that I know don’t like the additional constraints. Some swear by its ability to handle data on the client side, but for me, it’s still not usable for the web. So, I went ahead and attempted something else. I’ve started work on Dispatch JS. It’s a tool I’ve had around for years, but never really realized the amount of help it provides until just recently when one of my devs came up to me and actually told me that this made his life much easier, since he just doesn’t like to code in JavaScript. Read up on it, and you’ll be surprised by its simplicity.

On a sadder note, I understand why all of these libraries and frameworks are coming out and gaining popularity. Developers that don’t like to code (oxymoron, I know) create these bulky and complex libraries that only benefit certain scenarios, and then they get evangelized by additional lazy developers. I keep running into these developers that just don’t like to write code. No one wants to do the hard work of not only writing code, but writing proper code. Everything has to be abstracted because there’s nothing exciting about writing good quality, properly structured code. It amazes me that these developers survive in the development world. They develop so many constraints that removes all flexibility of developing web pages. I could go on for ever, but this is one of the reasons the angular fan base will be split up between 1 and 2, and then both groups will only get weaker and weaker.

ANGULAR JS WILL FAIL UPDATE: 12/18/2015

Angular JS will fail, if it hasn’t already. It’s almost the end of the year, and the more I see defendants of Angular, the more I think to myself that they have something there. All of my side projects (about a dozen) including a management application found here at ActingShowcase.com do not have a single piece of code from Angular, and I have not suffered. Had I not had something like jQuery, development might have taken me a bit longer. I simply have not seen the need to use Angular at all. The world didn’t end. And, that’s another reason that Angular has failed. It has been losing popularity ever since I brought up the subject. It has been replaced by other “frameworks”, and overall, a lot of people have abandoned it.

The main reasons Angular js will fail are still: too difficult of a learning curve, and uselessness.

ANGULAR JS WILL FAIL UPDATE: 4/3/2015

I feel like I have to clarify for the people who keep trying to explain that jQuery is not angular.js. No duh! I’ve learned that over the years. However, what people don’t seem to understand is that I’m not comparing angular.js to jQuery. I’m comparing the difficulty to lean angular.js to the difficulty to learn jQuery. With difficulty in mind, I read an interesting quote the other day: “More entrepreneurs than ever before will enter this booming market with limited coding ability and they will need something other than [insert preferred framework / language here]”.

And now for the original post…

Angular JS will fail

I’m all about new technology, but just like Steve Jobs had put it, it has to be intuitive. It has to feel comfortable, and easy to learn. This is reference to another one of my posts done here:¬†Angular JS Kinda Sucks. The main reason Angular JS will fail is because it’s too difficult. Honestly, who likes to make their lives more difficult? Not this guy. That’s not to say I’m looking for the easy way out. I believe in hard work paying off, but to make things difficult just for the sake of saying that I did something difficult that I could have done with ease, other ways? That’s just ridiculous. Yes, I can take a boat across the English channel, but why not make it harder and swim it? Other than getting into the book of world records, there really is no practical reason to do so.

Angular JS will fail

Angular JS vs other frameworks vs jQuery usage

Which brings me to the pattern of ever failing technologies. Remember Moo Tools? Prototype? I do too, and sadly, I use NONE of them in any of my projects. jQuery has evolved with the times. It has gotten better and better, and even with its 2.0 release, revolutionized. All while keeping its key ingredient of keeping itself simple to use and logically understandable. Any one of us who struggled with JS before jQuery came along created our own JS libraries to handle mundane tasks of JS. Class lookups, selecting elements, animation, AJAX, etc. We all wondered if there was an easier way to do repetitive work like that. jQuery came along and helped us out in that department. That’s why Angular JS will fail.

Prototype and moo tools tried to be innovative, but they just made things harder. Not only were they not intuitive to use, but referring to the documentation was even worse. Would take hours what jQuery could accomplish in mere minutes.

Don’t look at how many companies use those other tools right now. Wait for it and see how many companies will use those same tools in the future. 5 years, 10 years… jQuery has stood the test of time. And the reason they keep winning is because they cater to the developer, the people who are using the tool the most, and making their lives easier to deal with. It’s a complement to code, not a spaghetti nightmare filled with complexities and high learning curves. Another reason Angular JS will fail.

I remember the first time I built a web page using jQuery. It was easy. It was instinctive. It was amazing. It made want to use more of it. AngularJS unfortunately, did not have that same effect on me.

In the end, I guess it’s to each their own, but too many times I’ve come across reviews that are not so pleasant to read about Angular JS. Even doing a google search on “jQuery sucks” vs “AngularJS sucks” shows that there are more results for the latter, and AngularJS has only been around for a few years, while jQuery, almost a couple of decades. You’d think that there would be more results for jQuery since it’s been around for longer, and that AngularJS has been harbored by Google.

What are your thoughts?

ANGULAR JS WILL FAIL UPDATE: 7/18/2014

As promised, here it is. The first update of my attempt to compare angular vs jQuery. Before you jump in and start yelling at me about how they’re apples and oranges, I wanted to compare the ease of use of angular and jQuery to do something simple. Here are the three tests:

* Load elements onto a page
* User clicks on stuff
* Use AJAX calls to…
* Manipulate DOM elements.

Basically, this explains any sort of application that I’ve ever worked with.

* Program loads
* User clicks around
* A call is made to the “controller” which calculates some things, and returns some “views” to be rendered by the front end
* Swap out HTML elements, add classes, remove classes, etc.

Doing my research, I found out that angularjs does AJAX calls as simple and as easy as jQuery. Here’s some examples:

jQuery:

1
2
3
4
5
6
7
8
9
10
$.ajax({
url: '/ajax.php',
dataType: 'JSON',
success: function (data) {
$('#element').html(data);
},
fail: function (data) {
alert("AJAX failed!");
}
});

 

angularjs

1
2
3
4
5
6
7
8
9
10
$scope.myData = {};
$scope.myData.doClick = function (item, event) {
var responsePromise = $http.get("/ajax.php");
responsePromise.success(function(data, status, headers, config) {
$scope.myData.fromServer = data.title;
});
responsePromise.error(function(data, status, headers, config) {
alert("AJAX failed!");
});
}

Code Size:
+ jQuery
The very first noticeable thing here is the fact that jQuery has significantly less code. This may not matter right now because it’s a small ajax call, but what happens when you have multiple AJAX controllers (as I’d like to call them)? This can escalate quickly.

Library Size:
+jQuery
If you check your network tab like I do, you’ll also notice that jQuery is about 20% smaller in size. Not a biggie really, just a small win, but still a win.

Maintainability:
= neither / both
While I like how angular binds everything with variable names to make it easier to manage your code, there’s absolutely nothing holding you back from writing well structured jQuery code that will accomplish the same thing. Well structured code is well structured code. I can see either fail at this if either code is spaghetti.

DOM Manipulation:
++jQuery
I wanted to see an example of how angularjs will do DOM manipulation since my app is mostly DOM elements being updated, added, removed. This is where angular fails for me by far! The first google search led me to this jsfiddle link: http://jsfiddle.net/simpulton/E7xER/

Code:

1
var myApp = angular.module('myApp', []);

myApp.directive(‘myWidget’, function() {
var linkFn;
linkFn = function(scope, element, attrs) {
var animateDown, animateRight, pageOne, pageTwo;
pageOne = angular.element(element.children()[0]);
pageTwo = angular.element(element.children()[1]);

animateDown = function() {
$(this).animate({
top: ‘+=50’
});
};

animateRight = function() {
$(this).animate({
left: ‘+=50’
});
};

$(pageOne).on(‘click’, animateDown);
$(pageTwo).on(‘click’, animateRight);
};
return {
restrict: ‘E’,
link: linkFn
};
});

Notice something awkward? It starts all nice an ajngularjs-y, but the on line 11 of 28, something awesome happens. All of the DOM manipulation is handled by jQuery. Um…….. What? So not only do I have to load a library (jQuery), on top of a heavier framework, and handle my DOM with jQuery still? This is what I was referring to when I first started writing about this article. 8/28 lines are jQuery. And this after a google search on how to manipulate DOM with angularjs. I guess the answer is: use jQuery.

Most of my front end code is ajax calls and DOM manipulation. As most apps are, that’s the norm. And I mean 99.999% of my jQuery is just that. AJAX and DOM manipulation. This is why we’re creating an app in the first place; so we don’t have to constantly reload a page. This is as simple as it gets, and angularjs has failed me.

An app without DOM manipulation is no app. It’s an applet. Forget about building full SPAs without jQuery.

Scalability:
++jQuery
So, I wanted to see how my friends here would fare against some extended code to handle a dynamic AJAX controller with JSON data coming back from the back-end. I won’t post the back-end code since it’s the same code. I just want to see the difference of how angularjs handles the data coming back from the server, and how jQuery handles the same data.

For the purpose of simplicity, here’s the requirements:

* Two links, and two output elements on the page.
* One link loads a random number in the first element.
* The second link loads today’s date in the second element.

angularjs:
—-angularjs
First off, I had to search the documentation… A LOT. And although the documentation lists functions and methods, it doesn’t show examples like jQuery does. How do I know how to use it if there’s no example? Is it assumed that I already know how to use angularjs? Then why is there documentation if I know how to use it? It’s illogical garbage. If you, the reader, can show me how to achieve something similar to the jQuery example below, please, I beg you, show me!

Forget about trying to get an attribute value from an element. The documentation page about attributes… NOTHING. No examples:
https://docs.angularjs.org/api/ng/type/$compile.directive.Attributes

I found “some” answers on stackoverflow.

First, there was this:

1
// Use $observe to observe changes to the attribute:

attrs.$observe(‘data’, function(value) {
console.log(‘data has changed value to ‘ + value);
});
attrs.$set(‘data’, ‘new value’);

Where am I supposed to put this code? In my controller file? My main app file? In the HTML as a script tag? And I don’t care about detecting changes to the attribute. I want to get the value of an attribute. Found something else while browsing:

http://stackoverflow.com/questions/20636537/angularjs-find-element-by-attribute-value
“In AngularJS you won’t do direct DOM manipulation from the controller, you should create a directive to to that. Inside the directive you can use JQuery as you wish.”

……. dandy! So, while really trying to make DOM manipulations, which is the visual feedback that end users require in order to know if something happened… I went back to jQuery.

Binding and directives? How am I going to write them to achieve the dynamic world that jQuery offers through IDs and Class Names? How can one bind anything to achieve that beautiful DOM manipulation? What about rendering new elements (created after DOM ready) on the page that I can continue to manipulate with jQuery using the $(document).on(); function?

jQuery:

1
2
<a class="ajaxClick" href="/ajax.php" data-action="dobuttonone">Link 1</a>
<a class="ajaxClick" href="/ajax.php" data-action="dobuttontwo">Link 2</a>

 

The backend will return some JSON encoded code with the following structure:

1
2
3
{"htmls":{"#elemOne":496609}}
// or
{"htmls":{"#elemTwo":"2014-07-19 00:32:09"}}

The JS that will show the main controller that I was talking about:

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
var manipulateMyDOM = function (data) {
for(htmlElem in data.htmls) {
$(htmlElem).html(data.htmls[htmlElem]);
};
for(appendElem in data.appends) {
$(appendElem).append(data.appends[appendElem]);
};
for(prependElem in data.prepends) {
$(prependElem).prepend(data.prepends[prependElem]);
};
for(updatableElem in data.updatables) {
$(updatableElem).html(data.updatables[updatableElem]);
};
for(replaceableElem in data.replaceables) {
$(replaceableElem).replaceWith(data.replaceables[replaceableElem]);
};
for(removeElem in data.removes) {
$(document).find(data.removes[removeElem]).remove();
};
for(after in data.afters) {
$(after).after(data.afters[after]);
};
for(attrchange in data.attrchanges) {
for (value in data.attrchanges[attrchange]) {
$(attrchange).attr(value,data.attrchanges[attrchange][value]);
}
};
for(classRemoveElem in data.classRemoves) {
$(classRemoveElem).removeClass(data.classRemoves[classRemoveElem]);
};
for(classAddElem in data.classAdds) {
$(classAddElem).addClass(data.classAdds[classAddElem]);
};
}

$(document).on(‘click’,’.ajaxClick’,function(e) {
e.preventDefault();
var $this = $(this);
var _action = $this.attr(‘data-action’);
var _url = $this.attr(‘href’) + ‘?action=’ + _action;
$.ajax({
url: _url,
dataType: ‘JSON’,
success: function (data) {
manipulateMyDOM(data);
}
});
});

And you’re done!!!! The only thing you will have to take care of is to provide elements with the class name “ajaxClick” and add a “data-action” attribute to tell the back-end which function to run. Here’s that PHP file I said I won’t put up. For each one of those links, you just add another function to your ajax file. The binding happens because of the data-action attribute is named the same as the php function. Yes you can obfuscate them if you’d like, but this is just to give you an idea of how code can be structured without the aid of 3rd party frameworks.

What I did above was to build my DOM Manipulator for as much of the functionality that I will use for most of my apps. You can reuse this for every application out there as a plug and play piece of code. Angular cannot make this possible as it can’t do DOM Manipulation on its own.

1
2
$action = isset($_GET['action']) ? $_GET['action'] : 'badcall';
call_user_func($action);

function dobuttonone() {
// DO PHP STUFF HERE
echo json_encode(array(
‘htmls’ => array(
‘#elemTwo’ => date(‘Y-m-d H:i:s’)
)
));
}
function dobuttontwo() {
// DO PHP STUFF HERE
echo json_encode(array(
‘htmls’ => array(
‘#elemOne’ => rand(111111,999999)
)
));
}
function badcall() {
echo json_encode(array(
‘error’ => true,
‘message’ => ‘No action was provided’
));
}

Now THAT’S good structure. No frameworks necessary. Just good ol’ code. An entire dynamic and scalable application.

I really wanted to compare a real life world example on how I can achieve something with angular that I already have with jQuery. Unfortunately, angular has already failed for me, and I provided examples on how it did so.

To all those angularjs developers who keep claiming how awesome the holy grail of angularjs is, please provide some examples of some work so I can understand what you keep claiming to be real. It’s like a religion, I swear. AngularJS is just awesome. You just have to be immersed in it to realize it. Sounds just like religion.

For me, angular has failed for the following reasons:

* No clear examples of the two most widely used front end features, DOM Manipulation and AJAX calls.
* Most of my development (over 99%) consists of those two features.
* jQuery easily provides AJAX calls, and keeps the code lighter and cleaner than angular.
* Even angular documentation suggests you use jQuery for DOM Manipulation.
* Why even bother using angular if most of my work consists of features easily implemented by jQuery?

I’m sorry to say that my research with angularjs has just strengthened my trust in jQuery to be my library of choice.

Well, actually, I’m not sorry. I’m glad I chose wisely from the beginning.

ANGULAR JS WILL FAIL UPDATE: 10/15/2014

After reading a lot of your comments, I’ve started to realize why the two are apples and oranges. Most angular developers speak of SPAs as something that doesn’t require DOM manipulation. Just numbers or text values changing here and there. Or even replacing your curly brackets with chunks of html within the document.

AJAX can be done by both, fairly easily. So that’s not a problem. I have noticed several comments that are less than nice towards someone trying to understand something new. It’s as if it should be simple because you understand it. Some people have an easier time with apples than oranges I suppose.

Performance wise, both can be good or bad. I keep saying it over and over, but it’s HOW you code, now what you use that matters in the end.

As far as making things easier… well, the shortest road is the one best known. Shortcuts can sometimes leave you wasting time if you’re not familiar with them.

Having been in the web dev field for quite some time now, I’ve realized that it all comes down to the basics. Adding levels of abstraction just creates necessity for no reason. Necessity to learn new things, which some people may be opened to, but this old timer (and apparently a lot of the commenters and readers of this post) is about done with learning new things that go obsolete before they get famous (prototype, mootools, GWT, Code Igniter for backend, I could go on and on).

Frameworks are nice when you understand them, that’s why I believe that the best framework is the one that’s easiest to learn. Unfortunately, most people don’t understand that the most popular framework is JavaScript itself. As for BackEnd PHP Frameworks, PHP still outlived every other abstract layered framework on top of it, and their many non backwards compatible versions. Looking at Laralvel, the greatest marketed PHP framework since Zend, it honestly looks like all of the other frameworks before it… just done differently with a little more or a little less abstraction, and its own quirks. Sparse documentation doesn’t help it either.

In the end, it comes down to the choice of the developer. I give a lot of respect to developers that still write pure JS. No abstraction for them. They know what’s needed from the language for their project.

I’ll stick to my apples, thank you.

ANGULAR JS WILL FAIL UPDATE: 11/3/2014

All righty then. Angular 2.0… a complete revamp of angularjs. Yet, another reason AngularJS will fail. I keep trying to explain why it will fail, and of course, I get all sorts of backlash about how I suck at programming. Maybe I just have a better understanding of business requirements integrated with development.

For all of those fan-boys of AngularJS… I don’t want to say “I told you so…” but… well, you know.

Apparently AngularJS 2.0 will be a complete rebuild of the first. It will blow your socks off… if you haven’t already built something with Angular 1.3 or its predecessors. Nevertheless, if you have built something with a previous version of AngularJS, sucks for you! Yes, there will be migranes… I mean… migrating procedures and such… but look at the cost!

I remember the days of when jQuery went to 2.0. Well. I remember them because I had to do it, and not too many people complained. In fact, the things that were pulled out that people used, were stacked neatly in an additional line of code that mostly housed IE dependencies. Easy, peasy! And… 99% of it is backwards compatible… And it’s not like things were added to it as bulk

With Angular 2.0, good luck migrating your entire code that’s dependent on a specific framework to another framework that’s not backwards compatible… at all… in fact, they will have to spend a whole year making it backwards compatible, therefore, bringing it back to a bulky mess that it was in version 1.3.

Does anyone else see anything wrong with this? Or are the fan-boys so faithful in this new religion, even if their projects crash and burn on the way down? How can anyone have any faith in a system that will drastically change their way of doing things? What’s to guarantee that they won’t do it in the future, causing you more headaches and lost hours… that you apparently saved while you were working with what would become an outdated version of itself.

Frameworks suck, and frameworks that are not updated with backwards compatibility, fail! Just look at all of the PHP frameworks that have gone by the way side because they didn’t keep up.

I understand that frameworks are supposed to make things easier for the future… but has Angular JS done that in this case? Uh… nope! Major fail in my book!

Angular JS Kinda Sucks

UPDATE: 7/11/2015

It’s apparent to me that there needs to be more of a focus on architecture and not as much frameworks. Learn how to do it and why you should do it before you can just assume that throwing a framework will just magically fix anything ahead of time.

UPDATE: 4/3/2015

I feel like I have to clarify for the people who keep trying to explain that jQuery is not angular.js. No duh! I’ve learned that over the years. However, what people don’t seem to understand is that I’m not comparing angular.js to jQuery. I’m comparing the difficulty to lean angular.js to jQuery. With difficulty in mind, I read an interesting quote the other day: “More entrepreneurs than ever before will enter this booming market with limited coding ability and they will need something other than [insert preferred framework / language here]”.

And now for the original post…

Ok, so I ran across this angular js framework and looked it over, tried to duplicate some functionality that I already had existing with jQuery, and was not impressed.

First of all, I can do anything in jQuery, and have full control. Full control of the selectors, HTML, the DOM. I like that. I like knowing what I’m doing and what’s happening in my application. Somehow, angular fails to let me know what’s happening behind closed doors, unless I go dig into the code itself. Hm. Never had to do that with jQuery.

+ jQuery

The documentation is just plain horrible. Basically, it comes down to how basics work, not how you can and should build an application, even though they stress that you must first architect your application before you build it. Architect it how? Are there examples? Some nice examples would be of projects that are relevant to the outside world. Data manipulation? Dynamic AJAX driven application? It just seems like a lot of hype because it’s the “cool” thing to do and everyone is doing it. Well, not everyone. About 0.1% of sites out there use Angular, while well over 55% of websites use jQuery. Most of the documentation is just hard to understand without explaining the parts of the application or explaining the magic behind the app, or even explaining why I’m naming certain things the way I name them. Anyway, just confusing.

+ jQuery

Which brings me to my final reason for not liking it. Intuitiveness. It’s not intuitive at all! If you know JS and jQuery, everything is build so you can just figure things out. .show(), .hide(), $.ajax({stuff}), $(‘whatever selector you want full control of here’).doThings(). It’s easy to read, just like OOP. In angular it feels like you’re looking at fog. ng-this, ng-that, and now you have to assume that somehow everything is aware of everything else on the page. WTF?

+ jQuery

Speed of development? Hardly. We had some experience with it at work where some front-end code was handed down to be integrated by back-end guys, and… well… everything broke. Why? The back-end guy knew only jQuery. Now, he has to spend additional time and resources to learn angular, and the learning curve is STEEP!!!! And once he learns it, maybe someone will come up with another stupid framework that will do exactly the same thing jQuery does, only more abstract. Can we get practical with our development, stop being such lazy-ass programmers, learn to code properly, and stop complaining about how working on something feels like work? Beware of lazy programming and short cuts to faster deployment schemes. Sounds a lot like get rich quick schemes. How well have those worked out so far? Is everyone rich yet?

+ jQuery

Just not for me. Might be for you, but for me, I stand by the saying, “If it ain’t broken, don’t fix it!” And jQuery is definitely not broken. It’s by far the most favorable, intuitive, powerful “framework”/library to date. It’s not a hula hoop. It’s a cellphone.

Updated on Feb 27th, 2014:
After attempting to look through documentation and examples on stackoverflow, I’ve come to the conclusion that I’m much happier with jQuery, for the simple reason that I know how to use it and it does everything I’ve ever wanted, because it’s a tool for short-cutting a lot of mundane tasks that JS threw at us. .each() loops, .ajax calls, class selectors, very easy to understand and build on top of. After looking at many examples of angular implementation, I’ve noticed a pattern of jQuery being used on top of angular. Obviously to take care of the many things that angular can’t. It seems to me that performance wise it wouldn’t be smart to use angular, simply because it would be additional bulk on top of your programming. It doesn’t complement JS, it complicates it by changing the rules, and way of thinking. jQuery respects JS and complements it greatly. So…

+ jQuery

If anyone has the solution to how they would take care of the example I’ve created using jQuery with angularjs here, I would love to read it.

Finally, The vBox Plugin!

Ever wanted a nice plugin that you could just insert, and run with it? No major reconfigurations, no extra images, nothing of the sort.

Bad news first!

Here are some of the cons:
– Modern Browser Support only.
– IE 9+
– Chrome 4+ (all)
– FF 3.5+
– Safari 5.1+
– Safari Mobile 5.0+
– Android 4.0+
– Chrome aor FF for Android (all)
– Dependent on jQuery.

And the good news!

Here are some of the pros:
– Resizeable with window if contents are larger than window.
– Multiple levels, stackable.
– Based on jQuery, easy to implement and use.
– Always stays in the center.
– SUPER light!

Take it, make it, minimize it, do whatever to it. Feedback would be appreciated.

vbox-0.1.2
Updated from 0.1.1: Added a resize on any element within that has the class resizable to fit the pop up which fits the window itself.

vbox-1.0.0
Updated from 0.1.2: Added compatibility for other browsers. Added custom fade time.

Usage:

1
$.fn.vbox('open',{content:'<p>My internal HTML text.</p>'});

If you want to read it without opening the file, here you go:

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
(function($){
    var g_vboxlevel = 0;
    $(document).on('click','.vbox-close, .fuzz',function(e) {
        e.stopPropagation();
        $.fn.vbox('close');
    }).on('click','.vbox-content',function(e){
        e.stopPropagation();
    });
    $(window).on('resize',function(){
        $.fn.vbox('resize');
    });
    $.fn.vbox = function (action,options) {
        var settings = $.extend({
            content: 'sample',
            speed: 100
        },options);
       
        var win = $(window);
        var winH = win.height();
        var winW = win.width();
       
        if (action == 'open') {
            g_vboxlevel++;
            $('body').append('<div class="fuzz" id="vbox_'+g_vboxlevel+'"><div class="vbox"><div class="vbox-content"><div class="inner-content">'+settings.content+'<a data-id="'+g_vboxlevel+'" href="#" class="vbox-close">&times;</a></div></div></div></div>');
            $thisbox = $(document).find('#vbox_'+g_vboxlevel);
            $thisbox.animate({opacity:1},settings.speed,function(){
                $.fn.vbox('resize');
            });
        };
        if (action == 'close') {
            $(document).find('#vbox_'+g_vboxlevel).animate({opacity:0},settings.speed,function() {
                $(this).remove();
            });
            g_vboxlevel--;
        };
        if (action == 'resize') {
            $thisbox = $(document).find('#vbox_'+g_vboxlevel);
            $thisbox.find('.inner-content, .resizable').css({'max-width':(winW - 100) + 'px'});
            $thisbox.find('.inner-content, .resizable').css({'max-height':(winH - 100) + 'px'});
        }
       
    }
}(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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
.fuzz {
    position: fixed;
    background: rgba(0,0,0,0.5);
    width: 100%;
    height: 100%;
    display: table;
    text-align: center;
    vertical-align: middle;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    opacity: 0;
}
.fuzz .vbox {
    display: table-cell;
    vertical-align: middle;
}

.fuzz .vbox-content {
    box-shadow: 0 9px 39px #333;
    display: inline-block;
    padding: 20px;
    background: #fff;
    position: relative;
}
.fuzz .inner-content {
    overflow: auto;
    border: 1px solid #ccc;
    padding: 20px;
}
.fuzz .vbox-close{
    position: absolute;
    font-size: 28px;
    text-decoration: none;
    top: -12px;
    right: -12px;
    border: 3px solid #fff;
    box-shadow: 0 0 10px #000;
    border-radius: 16px;
    height: 26px;
    line-height: 22px;
    background: #000;
    color: #fff;
    width: 26px;
    font-weight: bold;
}

Update:

I’ve managed to make some tweaks with the help from some feedback and the vBox plugin is finally ready for release. Enjoy!

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.

It’s-a me, Mario!

Since I absolutely love the Super Mario Brothers, I couldn’t bare the thought of not upgrading an old classic to the power of HTML5. Am I saying that I’ll re-create the entire game here? No… probably not. But, it’s nice to know that with today’s technology, you can come pretty darn close, and sometimes, even surprise yourself.

Taken from the basic Mario where I had a jumping block on a white background, I think you’ll find it refreshing to see Mario re-evolve in the web world, and have this game be playable on any device eventually. That’s my goal.