Implementing loading animation in AngularJS and jQuery

With the advancement of web development technologies, web application are closing the user experience gap with desktop applications very quickly. It is a very common practice to let the user know when the application is busy with a certain task, and one of the most common ways to do this is by showing a loading indicator or a spinning gif. This will let the user know that the application is working and he or she will not try to refresh or press other buttons until the task is finished.

To implement this, before the task is initiated at server, we must show our spinner or any loading animation we want to show, and then when the task is finished (successfully or unsuccessfully) hide the animation. I will show you how you can do it using jQuery and using AngularJS.

Implementing loading animation in jQuery

Let us start with the jQuery. I want to show a spinner whenever I post something to the server from the form, until I receive a response. Let us suppose we have a form like this:

<form id="subscriptionForm">
  <label for="email">Your email</label>
  <input type="email" id="email" name="email" />
</form>

and I have a div with a spinner gif img inside it somewhere in the html

<div id="processing" style="display: none"><img src="spinner.gif" /></div>

At the beginning, I need to make this hidden, so you can put a css style display:none   or hide it using jquery or whatever way you like most.

There are several forms to determine how to show the spinner and hide it. One way is to bind to subscriptionForm ajaxSend and ajaxComplete events to show and hide the spinner respectively.

$("#subscriptionForm").bind("ajaxSend", function(){	
   $("#processing").show();
}).bind("ajaxComplete", function(){		
   $("#processing").hide();
});

This will make the spinner show when a ajax request starts from that form and disappear when the request completes.

If it is the case that you need to make the spinner show for every ajax request made within the page, then you may need to bind the events to the DOM.

You can also make the spinner show as a modal dialog by applying a style like this and adding class ajax-loader to the spinner img element:

#processing {  
    position:absolute;
    top:0;
    left:0;
    width:100%;
    height:100%;
    z-index:1000;
    background-color:grey;
    opacity: .6;
}

.ajax-loader {
    position: absolute;
    left: 50%;
    top: 50%;
    display: block;     
}

This will make the spinner show in a modal dialog and prevent the user from initiating any other requests before this one finishes.

Implementing loading animation in AngualarJS apps

The strategy for implementing the loading animation in AngularJS is little different and requires a bit of a setup. To catch the start and end of requests, in AngularJS we must create http interceptors for request and response. Interceptors will intercept requests before they are handed to the server so we can show our spinner and response before it is handed to the client so we can hide the spinner.

To get the interceptors, we need to register them through an anonymous factory  and inside request and response functions, we need to show and hide the div of spinner respectively.

myApp = angular.module('myApp',[]).config(function($httpProvider){
  $httpProvider.interceptors.push(function($q) {
    return {
     'request': function(config) {
         $('#processing').show();
         return config;
      },

      'response': function(response) {
         $('#processing').hide();
         return response;
      }
    };
  });
});

Interceptors are a useful part of AngularJS which can be used to make several kinds of validations before a request is made or after a response is received (authentication validations, etc.), and one of the tasks we can put here is also to show and hide the spinner when a request has started and completed (please be aware that for the simplicity of the code, I have omitted functions which check for errors on requests).

To make the example more clear, I have create a sample interceptor demo in a Plunker, you may see it here http://plnkr.co/edit/hAg1T8sdsLq5c61iW97f?p=preview

This was a simple post to show you how is implementing loading animation in AngularJS and jQuery done. Of course your scenario may have additional or more complex requirements but this should serve as a basis to set it up.

Multilanguage AngularJS apps

Last two years, almost every project that I have worked on, has had the requirement of multilingual graphical user interface (GUI) and messages. This scenario may be important if your country has a multilingual environment or if you are opening to international markets and want to give your users the best possible user experience. The former is little easier as the number of supported languages is usually lower than the latter.

So, what is the problem definition here. We need to support dynamic language setting in GUI for two types of components:

  1. Labels
  2. Dropdown lists

In order to define the actual language the user is using, we chose to use a route parameter for it. Our route became something like this:

$routeSegmentProvider.when('/:lang/module/...', 'moduleName')

Route parameter :lang enabled us to get the user’s current language by calling

$routeParams.lang

Then, we used angular library angular-translate which happened to be very convenient and easy to use for us. The setup is pretty easy. You include angular-translate.js file in your index.html and require reference to ‘pascalprecht.translate’ when defining your module, e.g.

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

After this, we create a json file for every language we wanted to define, eg. en.js file will contain the labels for English language (sq.js for Albanian, and so on), and it looks like this:

(function(){
	var myApp = angular.module("myApp");
	myApp.labels_en = {
		  "version": "Version",
		  "name": "Name",
		  "surname": "Surname"
	  };
}());

We also need to tell our app the translation configuration. I like to do this in a separate configuration file which I call translation.js (don’t forget to reference it in index.html) and it looks like this:

(function(){
	var myApp = angular.module("myApp");
	myApp.config(["$translateProvider", function ($translateProvider) {
		  $translateProvider.translations("en", myApp.labels_en);
		  $translateProvider.preferredLanguage("en");
		}]);	
}());

If later I want to add a translation for Albanian language, I will create one file sq.js which contain the translations e.g.

(function(){
	var myApp = angular.module("myApp");
	myApp.labels_sq = {
		  "version": "Verzioni",
		  "name": "Emri",
		  "surname": "Mbiemri"
	  };
}());

and I will add this line of code to the translation.js file

$translateProvider.translations("sq", myApp.labels_sq);

and the new language is automatically supported.

Now, in the controller that we want to use translation, we need to to tell the language to be used and we do it like by getting the param from route and pass it to $translate object:

$translate.use($routeParams.lang);

In the view, we put the dynamic labels and messages by using an angularjs binding and filtering it with translate

<label for="inputId">{{ 'version' | translate }}</label>

Here we are, our labels will be translated automatically based on the route parameter :lang.

The labels are translated, now we need to translate the dropdown lists. To support list translation, as we already had a small number of languages to be supported, we chose to save list values in the database lookup tables in all languages, so basically, every lookup table has a structure similar to this:

id name_en name_sq

and when we return the json object for the lookup values, we return an object similar to the object below and bind it in our controller to a scope variable list

$scope.list = {
  "id": 1,
  "name": [
    "en": "name in english",
    "sq": "name in albanian"
  ]
}

then our html select element will look like this

<select 
    data-ng-model="testObject.selectName" 
    name="selectName" 
    ng-options="i.id as name[lang] for i in list" 
    >
</select>            

In this way, our ng-options will get automatically the language from lang parameter set in $scope from the $routeParams and it will automatically get the lookup name for the specific language

This might not be the best way to implement multilanguage angularjs apps but it worked pretty well in our case and in several other projects I have worked on.

Hope it helps to you as well.

I want to create a website

Having your own website is one of the best things you can do if you are planning to have a serious online presence. Of course it is not a silver bullet solution, as it requires constant investment of time creating valuable content and marketing, but it is ultimately the starting point people will check about you online.

So, I want to create a website. What are my options? What should I do next? In this post, I will consider several options you may follow to create your own web site. Fortunately, there are a lot of options available to choose from, starting with ready made solutions which you may set up with very few clicks, to those which require advanced knowledge of some technologies. Unfortunately, I will not be able to list here all available options, but I will try to make a list of options which may suit most of you out there trying to create your own web site.

1. Free blog with WordPress.com

If what you are looking for is just a blogging website and you want it for free, wordpress.com may be the best choice for you. They have a managed wordpress hosting solution for which you may sign up and get your own blogging solution set up with a few clicks. This solution could be a good start if you want to try yourself blogging and create an online presence without investing any money. Though, this free solution comes with some limitations. You get a domain as http://yourname.wordpress.com and few free themes for your site. If you want a custom domain name like www.yourname.com, or a better design for your site you have to pay for it. You are also not allowed to install your own themes (if you already have one, or want to custom build one), but only choose from available ones there (free or paid).

2. Managed hosting with wordpress site

If limitations of wordpress.com do not fit you well, you may decide to go with a managed hosting where you may setup a wordpress site. I happen to prefer wordpress as my CMS of choice, otherwise, you may chose to set up a different CMS with your hosting provider depending on the type of hosting you have and the CMS you have chosen. With a manage hosting, you may chose your own domain, buy or develop a custom theme for your site, and do many more customizations which are not possible with free wordpress.com solution.

There are plenty of companies offering managed hosting solutions, and all of them vary in price and features they offer. Some of the popular hosting companies I have come over are GoDaddy and BlueHost.

3. Managed hosting with a custom solution

Another choice is to have a managed hosting solution with a custom web site developed for you. This is more powerful than above mentioned solutions as you have the option to chose everything (from colors, fonts, to design and features developed), however, it is more expensive. Depending on the market you live, developing a custom web site may cost you from several hundred dollars to several thousand dollars.

4. Private hosting

Private hosting is an advanced solution, mostly suitable for companies, where you get a private server rented for you from a hosting company. The hosting company creates the server (be it real hardware server or a virtual one), connects it to internet, but leaves the management of the server environment to you. This has huge advantages as you control what is installed in the server, what features do you want to offer, and it is very easy if you want to add some unsupported technology to your solution. However, it is also very expensive and requires technical skills of system administration and system security as this task is on you now.

5. Cloud solution

Cloud solution is a superset of private hosting. If you choose to have a cloud solution with one of the biggest market players in this industry (Microsoft Azure, Amazon AWS, Google Cloud Computing), then you not only have the server on your control, but a whole IT infrastructure. You have the possibility to create virtual servers, website hosting, email services, active directory services, storage and backup services, and many other IT infrastructure components as a service. This powerful solution requires you to have a very good understanding of IT infrastructure configuration, but as a benefit, you get a flexible IT architecture which can scale up and down as needed and you pay for what you use.

Conclusions

Which one is right for you? Well, it depends. Your needs define what is best for you, but generally speaking, amongst these, number 2 and number 5 are my favorites. So, if I want to create a website for myself, or you are an individual or a business who wants to have a blog or a personal/company site which is for online presence, then I think option number two is the best choice as it has the possibility to scale up with a custom solution or stay with a WordPress or a specific CMS. If you have a startup which is offering a SaaS or any other solution that you expect to have increasing demand, then I think option number five is the best as it offers you the possibility to start small and grow as needed. Of course these come with the complexity of knowledge required, but it will be worthy to invest in that direction.

Developing hybrid mobile apps with Phonegap, AngularJS, Bootstrap

In this post I am going to talk about developing hybrid mobile apps with Phonegap, AngularJS, Bootstrap. In my post Develop mobile applications using web development skills, I pointed out a list of possible frameworks which can be used to create a hybrid mobile app. My favorite choice so far is using Cordova/Phonegap (Read my post on my opinion about Cordova/Phonegap) in combination with a hybrid app development framework. In my previous mobile applications I have developed, I used to use jQuery mobile as my framework of choice for developing the UI of my apps. Nowadays, I have switched to another combination, which is:

Cordova/Phonegap + AngularJS + Bootstrap

The hybrid mobile app architecture with Phonegap, AngularJS, Bootstrap looks like this:

The presentation layer is built with Bootstrap framework, the app domain is modelled using AngularJS, and the is packaged using Cordova/Phonegap to a native app. Let us go through the components of this hybrid mobile app architecture and describe them.

Bootstrap

Bootstrap is a mobile-first responsive front-end framework. What this mean? Bootstrap has an easy to use responsive grid which allows you to position your layout in a well structured responsive way. As the framework is built with mobile use in mind, it responds well to different screen sizes and adapts the layout of the app easily to different screen sizes. This is a good possibility to use the very same implementation for tablet and mobile devices of different screen sizes. And it is not only the grid that makes it special. It helps you manage typography, responsive images, forms, form validation messages, notification messages, responsive tables, and a good number of UI components. You can download it from getbootstrap.com.

AngularJS

AngularJS

AngularJS

A very powerful, full-featured JavaScript MVW framework. With AngularJS framework, you can give a structure to your app domain model and manage your app logic in a very flexible way. Everything is organized around a model which is displayed through a View. Views can be well structured templated HTML code styled and organized using Bootstrap. Controllers organize the communication between the View, Services, and all other parts. The framework supports a good routing mechanism, which can also be extended by other extension libraries for more powerful functionalities. There are a plethora of extension libraries for AngularJS which add value to the framework by filling in the gaps of the framework. You can get AngularJS from angularjs.org.

 

Cordova/Phonegap

Cordova is an Apache project which creates an underlying platform for developing multiplatform mobile applications. In our case, it makes possible the AngularJS+Bootstrap web app to be packaged to a native mobile app which can be published to the mobile markets and be instlalled in mobile devices. Adobe PhoneGap is a distribution of Cordova.

Basically what Cordova does is to make possible the web app to run inside a WebView component of a native app, we can say it as a native package of a web app. You can do the packaging using Cordova Command Line Interface (CLI) or using Adobe PhoneGap Build which does not require any installations.

The most powerful feature of Cordova in my opinion is the extension possibility by plugins. By installing specific plugins, you get access to device’s hardware such as camera, compass, geolocation, as well as other device specific APIs such as contacts, media, notifications, etc. Very powerful plugins such as barcode reading, push notifications, and many more, can give your application good features by writing few lines of code.

The development process

As we described the architecture parts, let us start with the process of developing hybrid mobile apps with Phonegap, AngularJS, Bootstrap. We start with creating a sample application  which shows you your current location coordinates and demonstrate the development process. The easiest way to start the app development is by creating initial template using Cordova/Phonegap CLI. We do this through this command (if you do not have cordova cli installed, here is the link showing how to do it: https://cordova.apache.org/docs/en/4.0.0/guide_cli_index.md.html)

phonegap create blogSample com.ariancelina.blogSample BlogSample

The create command requires 3 arguments:

  1. The directory name to be created for generation of the project, in our case “blogSample”
  2. The second argument is the project identifier, in our case “com.ariancelina.blogSample”. Usually it is used as a reversed domain name identifier
  3. The third argument is the display title of the application, in our case “BlogSample”

In this sample code, I used phonegap to create the app. The command equally applies to cordova as well.

If you already had phonegap installed and the app was created successfully, inside blogSample directory you should have a config.xml file and four other directories (hooks, platforms, plugins, and www). Platforms folder contains builds for specific platforms, plugins directory contains installed plugins, and WWW directory contains all our web code (AngularJS + Bootstrap + other files).

To read our location coordinates we need to install the Geolocation plugin (Find the list of plugins) and we do that by executing this command:

cordova plugin add org.apache.cordova.geolocation

Now that we have the initial structure, we need to add platforms to which we want to deploy, but to do that, we need to be inside out app directory, which in our case is blogSample. Adding ios platform is done using the command

phonegap platform add ios

After the platform is added, we can build our app using

phonegap build ios

We can repeat last two commands for all other supported platforms like android, windows phone, etc.

If we want to test our app, we can go to directory blogSample/platforms/ios and lunch BlogSample.xcodeproj and run the app in simulator or existing device.

We have our platform set up, now let us add the AngularJS and Bootstrap files. After we download these (download AngularJS as a zip file so you get all parts of it), we put inside blogSample/www/js directory AngularJS and Bootstrap js files: jquery-1.11.2.min.js (jquery is a dependency of bootstrap and can be downloaded from jquery.com)angular.min.js, angular-route.min.js and bootstrap.min.js. Inside blogSample/www/css directory we put bootstrap.min.css and bootstrap-theme.min.css files. And the last part here is to link these files in our main file index.html. We put css code in head section:

        <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css"/>
        <link rel="stylesheet" type="text/css" href="css/bootstrap-theme.min.css"/>
        <link rel="stylesheet" type="text/css" href="css/index.css" />

and near the closing body tag we link the javascript files

        <script type="text/javascript" src="js/jquery-1.11.2.min.js"></script>
        <script type="text/javascript" src="js/bootstrap.min.js"></script>
        <script type="text/javascript" src="cordova.js"></script>
        <script type="text/javascript" src="js/angular.min.js"></script>
        <script type="text/javascript" src="js/angular-route.min.js"></script>
        <script type="text/javascript" src="js/index.js"></script>

Now we have the setup ready and we can start coding the logic. We need three things to define to make it work, we need an angular route config which allows us to navigate from page to page, then we need an angular controller, and a view which will display the user his/her current location.

We start with the app.js file which contains the initialization of the js app. This file also is the place where the initialization events are placed. In our case, it looks like this:

var blogSample = angular.module('blogSample', ['ngRoute','ui.bootstrap']);
var app = {
    // Application Constructor
    initialize: function() {
        this.bindEvents();
    },
    bindEvents: function() {
        document.addEventListener('deviceready', this.onDeviceReady, false);
            document.addEventListener('deviceready', this.onDeviceReady, false);
    },
    onDeviceReady: function() {
        app.receivedEvent('deviceready');
        navigator.geolocation.getCurrentPosition(app.onSuccess, app.onErr);
    },
    onErr: function(error)
    {
        alert('Unable to get your location. Without location you will not be able to use navigate feature! Error:' + 'n' + error.message);
    },

    onSuccess: function(position)
    {
        blogSample.latitude = position.coords.latitude;
        blogSample.longitude = position.coords.longitude;
    }
};

We start by defining our angular app, blogSample (line 1). We initiate it and  define the modules which we need (ngRoute, ui.bootstrap). There are other interesting things happening here. As we are used to use jquery ready function to react when the page is loaded and ready for use, here we have onDeviceReady event which is fired when the app is loaded and we can start using it. Inside this event, we will get the current position of the device through this line of code

navigator.geolocation.getCurrentPosition(app.onSuccess, app.onErr);

The getCurrentPosition function which gets the current latitude and longitude of the device, needs two functions as parameters, first being the function that is called if the current location can be obtained successfully, and the latter for errors. The error function is used to report the unavailability of the location. The success function is used to read the coordinates and bind them to our angular app, blogSample through this function

onSuccess: function(position)
{
   blogSample.latitude = position.coords.latitude;
   blogSample.longitude = position.coords.longitude;
}

Now that we have our app setup ready, let us define two views, one about page and the other showing location information. Showing the coordinates inside the view is done using

<p class="text-center"> Your location is: <br/>
  Latitude: {{latitude}}<br/>
  Longitude: {{longitude}} <br/>
</p>

AngularJS will substitute the values inside curly braces with current coordinates set in onSuccess function. But views do not access application level values. We usually link a controller with a view, and view is limited to the scope of that controller, so we need to define a controller to glue the coordinates to the view. The controller will look like:

blogSample.controller('mainController', function($scope, $route){
    $scope.latitude = blogSample.latitude;
    $scope.longitude = blogSample.longitude;          
});

and finally we add the router configuration to bind the controller to the view and enable the user moving between pages. The router has this code:

blogSample.config(['$routeProvider',
  function($routeProvider) {
    $routeProvider.
      when('/', {
        templateUrl: 'views/main.html',
        controller: 'mainController'
      }).
      when('/about', {
        templateUrl: 'views/about.html'
      }).
      otherwise({
        redirectTo: '/'
      });
  }]);

The router part defines one default url and ‘/about’ url. The default url ‘/’ binds to main.html view, and the ‘/about’ url binds to about.html view.

Now that we have all the building pieces in place, we need to add the reference of last created files in index.html and the references will look like this:

        <script type="text/javascript" src="cordova.js"></script>

        <script type="text/javascript" src="js/libs/jquery-1.11.2.min.js"></script>
        <script type="text/javascript" src="js/libs/bootstrap.min.js"></script>
        <script type="text/javascript" src="js/libs/angular.min.js"></script>
        <script type="text/javascript" src="js/libs/angular-route.min.js"></script>
        <script type="text/javascript" src="js/libs/ui-bootstrap-tpls-0.11.0.min.js"></script>
        <script type="text/javascript" src="js/app.js"></script>
        <script type="text/javascript" src="js/angular/routes.js"></script>
        <script type="text/javascript" src="js/angular/controller.js"></script>
   

        <script type="text/javascript">
            app.initialize();
        </script>

Now that everything is on place, we can deploy our app to the phone for testing, or run it in a simulator. Running the application is different depending on the platform. You may use the simulators that can be started from phonegap, by xcode, eclipse, or android studio, but for any serious app development, I would strongly suggest you try your app in a real device. I will not go into details about deployment as it is out of scope of this post, but in the simplest scenario, you may go to platforms folder inside  your phonegap project folder, and open the project of the specific platform and run the project from the respective ide.

The complete source code of this application can be found on GitHub https://github.com/acelina/phonegapWithAngularJs, you may download it and try it on your computer.

What is the mission of a software developer

Nowadays, there is a great demand for software development out there. The world needs software solutions just about anything. From planning and running complex business and industrial services to planning and running your day. From execution of mission critical operations to playing for fun, almost everything is backed by a software. There are millions of software developers out there and yet the global need for them is not about to be met. The world needs a lot more software developers, but seriously, why do we need them, what is the mission of a software developer that is so important to the world economy?

Let us analyse first how a software developer grows. Basically, there are two major paths one may follow to be a software developer. One is to have a formal education (be it a university degree, or a formal training program) and acquire the necessary skills to develop software, and the other is to be an autodidact and teach yourself using plenty of available resources (books, online courses, articles, tutorials, etc.) about software development.

The self learning approach is very personal and it is hard to generalize the way one teaches himself therefore it is hard to draw conclusions that what process is followed or what the outcomes may be. Also, compared to the numbers, I am sure this group is the minority, and the majority of developers come from a more formal path.

The formal path, however, has a visible indicator how one is being trained in the field of software development. We can have a look at the curricula of many universities and analyze them. We can get a subset of subjects that are covered from most universities, or so to say core subjects,  and they are programming languages, databases, data security, algorithms, maths, web development, etc. (I am not focusing here on training programs as usually they tend to have a narrower focus on one technology or one aspect of it, and rarely on a complete process as universities do). Some universities offer also non computer science complementary courses such as on entrepreneurship, preparing business plans, biology, etc., but only as elective courses that are left on the will of the student if he or she wants to take it.

From the university curricula I have seen, I can draw the conclusion that most of the universities prepare the software developers as pure technical persons who are supposed to solve technical problems related to software development. But is this the reason world needs the software developers that much? Personally, I do not agree with this, and I keep asking myself the question:

What is the mission of a software developer?

Let us try to answer this by trying to find the answer to this question: What does a software developer do after the graduation? I can think of several answers to this:

1. Industry path: He or she is employed by a company who needs software solutions for their business needs (be it a software developer company, a bank, an engineering company, a distribution business, whatever…) and he/she works there trying to create software solutions for the needs of the company.

2. Academic path: He or she may decide to pursue further studies and be a researcher who continues to contribute to academia by teaching and to the knowledge by researching unknown solutions for existing technical, real life or business problems.

3. Entrepreneur path: He or she creates a solution for a real life problem or a business problem, makes a business out of it, and creates an enterprise which runs a business by providing a software solution for a business problem.

Of course it is not easy to sum up all available paths to follow, but in my opinion these three cover the major available paths to follow for a computer science graduate.

Now what can I see from these choices is that, none of them are about solving technical problems purely. What I can also conclude is that, solving a real life or business problem is what turns out to be the real reason why we need so many software developers today. From this, I can confidently say that

The mission of a software developer is to solve real life and business problems.

You may say that is something we know and it is obvious, what is the problem about this? Well, I have a lot of contacts with different developers, experienced ones and want to be ones, university trained and autodidacts. I am teaching programming courses myself on a university level and professional level for over 6 years now, and I have had the opportunity to deal with over 1000 students up to now. What I can see is that, software developers see themselves as technical persons who are there to solve technical problems and they do not care about the business world. All they are interested is that how a technology or a framework works and how they can use or advance it. That is it. They care about code quality, they care about unit testing, they care about code reuse, and lots of other technical characteristics of the software, but rarely they discuss about how usable their applications are, or how efficiently they optimize a business problem their software is addressing or what business value they have delivered with the software they have built. I am not saying that technical characteristics are unimportant, far from it, we should always strive to write the best quality code we can, according to best industry standards, using best practices, and best patterns we know. I am just stating that the most important thing is we deliver value with software. If there is no value, there is no point having unit tests, most clearly written code, or bug free code, as it will not be used.

But perhaps this is not their fault as the education system they are following is not preparing them to think in that way, and that is where our duty as computer science teachers come to a focus. It is us, everybody who teaches a computer science related subject, be it a university course, an online course, or tutorial series, we should communicate the idea that technology is there to solve real life and business problems. I do think that we should not grow technical persons who write code, but we should teach them to be problem solvers who provide value with their solutions.

What do you think? Leave a comment and let’s discuss about it. If you agree with my opinion and think this is a valuable point, please share it so it reaches a broader audience.

Outputting json data with php

This is going to be a very short post, but could be of use if you did not know about this

Many times, for the purpose of demonstration when I teach AJAX requests to my students, I see the need to have a sample json dataset for easy consuming through AJAX requests. So basically what I want is to output an array of some JSON objects so we can consume let’s say using jquery and display them. I have found some examples, but strangely, none of them was appropriate for using in examples (they either had too much data that confused students, or had a complicated structure).

Usually, what first comes to our minds is that we need a Web Service for outputting json data with php, or perhaps even a REST service. No, for such an easy thing, we do not need a web service, we can achieve this with one line of code, yes, one line.

Let us create an array of arrays, where each array will hold the data of some famous cars:

$cars = array (
			array("name" => "BMW", "type" => "535", "engine" => 3.0),
			array("name" => "BMW", "type" => "320", "engine" => 2.0),
			array("name" => "Audi", "type" => "A4", "engine" => 3.0),
			array("name" => "Audi", "type" => "S3 Sedan", "engine" => 3.0),
			array("name" => "Mercedes", "type" => "A220", "engine" => 1.8),
			array("name" => "Mercedes", "type" => "C220", "engine" => 2.2)
			);

If we have such an array of arrays, this could easily be translated to a JSON array with JSON objects inside it. The one line of code that we need to do this transformation is:

echo json_encode($cars);

The result returned will be:

[
  {"name":"BMW","type":"535","engine":3},
  {"name":"BMW","type":"320","engine":2},
  {"name":"Audi","type":"A4","engine":3},
  {"name":"Audi","type":"S3 Sedan","engine":3},
  {"name":"Mercedes","type":"A220","engine":1.8},
  {"name":"Mercedes","type":"C220","engine":2.2}
]

I have published this code to my web site, so if you want to test the result, please go to this link http://18.197.31.180/json.php

The whole code will look like this:

<?php
	$cars = array (
			array("name" => "BMW", "type" => "535", "engine" => 3.0),
			array("name" => "BMW", "type" => "320", "engine" => 2.0),
			array("name" => "Audi", "type" => "A4", "engine" => 3.0),
			array("name" => "Audi", "type" => "S3 Sedan", "engine" => 3.0),
			array("name" => "Mercedes", "type" => "A220", "engine" => 1.8),
			array("name" => "Mercedes", "type" => "C220", "engine" => 2.2)
			);

	echo json_encode($cars);

 

Develop mobile applications using web development skills

The need for mobile apps has increased dramatically as their number to. The number of mobile devices in use has passed the first billion more than a year ago and it is still increasing. As mobile use is closing the gap with computer use, the gap of development skills is increasing. Mobile platforms are huge with lot of possibilities and not so easy learning curves. Apple iOS supports Objective-C, C, C++, or Swift programming languages, on the other side, Android supports Java programming language. If you want to target these platforms, you have to be proficient in at least two programming languages, which is not very easy. In addition to that, publishing to both platforms requires you develop and maintain the very same application twice. Cross platform development of hybrid webview applications could be your saviour if your requirements are not graphic or resource intensive. With the performance of the mobile devices of our time, we can easily run mobile web applications packed as native apps with a performance close to native apps (games and resource intensive apps make an exception here). But how do we build such an app?

The answer is, by leveraging our existing web development skills with HTML5, CSS3, and JavaScript and packaging it to a native app. But as we make our mind to use these technologies, we have still many other choices to make. The next one is what framework do we want to use. You can choose to make your UI by yourself, but chances are you will make a not so good feeling UI, or you will use quite a good time with it, so going with a framework is a wise choice here. Some of the choices are:

and this is not the end of the list. There are more choices.

Some of these frameworks offer only a mobile friendly User Interface (UI), and some have UI and packaging features. UI only frameworks are jQuery mobile, AngularJS and Bootstrap combination, Ionic and AngularJS, Kendo UI, and intel XDK. If you choose one of these, you can packaged them to a native mobile app using Apache Cordova or Adobe Phonegap Build. Appcelerator Titanium and Sencha Touch offer their own tools of packaging.

How do you make your choice? I would say your experience and required time to market are most important factors here. Perhaps jQuery mobile can give you the fastest way to put the app together, however, I must say it does not give you a very native user experience. Kendo UI has a good set of UI components but it comes at a price. So, in my opinion. there is no clear line here. The project requirements and available skillset influence the choice.

From my personal experience, I have developed few apps using jQuery mobile, Sencha Touch, and AngularJS with Bootstrap. The latter is my favourite choice, but I am looking forward to expand my horizon and try other frameworks as well. Let’s see what future brings.

PHP Tutorial site

In many of my posts I have shown a positive attitude towards PHP programming language. Although it is not the language I use every day, I do consider PHP as one of the best programming languages for a beginner in web development because I believe it has a fairly easy learning curve. I am now announcing an initiative to create a small PHP tutorial site.

I have been teaching PHP for over four years, and it was always my language of preference when I had to explain web development concepts to someone. I have been teaching it in university level as well as a professional course, and I have seen that students have learned the most important parts of it very quickly.

As a supporting material to my courses, as well as to contribute globally in knowledge sharing, I am creating a new section in my site for PHP tutorials. You can see the page here. This section is going to be dedicated to several tutorials explaining basic concepts of PHP. This is going to be an evolving project of online teaching I am planning to implement during 2015, so I will be adding learning materials continuously. If you don’t want to miss anything, please subscribe, and you will receive them in your email.

Subscribe

Get my posts in your inbox weekly

* indicates required


A beginners’ guide to web development

If you are reading this post, most probably you have some sort of interest in web development, or even you think about starting to learn about web development. In this post, I would like to show you what path you can follow to be a web developer. This is a beginners’ guide to web development from the perspective of what to learn and how to specialize. This is not a post in which you will learn coding. I just want to point out the what you need to consider before you start learning to code. So, welcome to our dynamic and ever changing world. One of those fast-pace professions with lot of challenges and excitement. So let us define some basic concepts first.

Front End vs. Back End

The initial separation you will feel here is Front End vs. Back End. Let us clarify first what is Frond End and what is Back End.

Front End

Web applications are categorized as distributed applications with a client-server architecture. So, we have a part of code which runs in the client and another part in server. The part of application which is run and rendered in client (most of the time, the client is our web browser) is called the Front End. The most usual technology combination which is used to develop for Front End is HTML+CSS+JavaScript. Front End specialists usually develop expertise in creating Front End of the web applications using these technologies. Another common skill Front End developers master is slicing Photoshop designs to HTML+CSS+JavaScript web pages.

Back End

Back End developers write code that runs on server. Usually, this part of the job entails communication with the DataBase for reading/writing data, reading/writing files, doing the business logic, etc. In some cases where the business logic resides in client side, then Back End is used to serve the data from the DataBase usually in the form of Web Services. Back End developers usually master one of web programming languages and a DataBase Management System.

 

You can master both, but from my experience, I have seen that all web developers tend to like one more than the other. Some even specialize on only one of them. Although there is a line of separation, there is no limit that which side should do what. Sometimes Front End is used only for visual representation and all the job is done in Back End. In some cases, Back End only serves the data and all the calculations and functions reside in Front End. It is a matter of design and architecture to define which side does what (although, depending on the architecture you choose, there are some guidelines about the responsibilities of each side).

Programming languages

There are a lot of available programming languages for web development. When we want to program on Front End, the defacto standard language is JavaScript. When it comes to Back End, we have plenty of choices. Let me list some of the popular choices:

  • PHP
  • JavaScript
  • Ruby on Rails (used with Ruby programming language)
  • ASP.NET (used with .net programming languages)
  • Java EE
  • Python

And this is not a definitive list, just those that came to my mind right now. So which one to choose. Well, your choice should be evaluated based on some factors like: the job market, hosting environment of the web application, available learning resources, available time to learn, the development community around you.

If you want to work as a web developer, in my opinion the most important factor is the job market. You should analyze the job market you are in (or you want to be in) and chose that language that has most job openings. Another important factor is the hosting environment. For example, PHP hosting is quite cheap compared to Java hosting. If you are going to develop an intranet application which is going to be hosted internally in an organization, perhaps Java EE could be a very good choice, but if you want to host your application online, Java EE could be rather expensive compared to other languages.

With the popularity of Node.js, JavaScript has started to become a popular choice of Back End programmers, however, this is still quite a new and immature technology compared to others, and I would not recommend it as a choice of beginner Web Developer.

In my opinion, PHP has the easiest learning curve, cheap hosting environment, plenty of learning resources and relatively easy development environment, so I would recommend to any beginner web developer start with PHP. ASP.NET is also a good choice. Microsoft offers a lot of learning resources, free development tools and a pretty rich environment. If you like the Microsoft ecosystem, ASP.NET is a very good choice.

Frameworks

If you are a beginner, give yourself some time before you start learning a framework. Frameworks are code libraries which make the life of a web developer easier. Frameworks give a structure to a web application, help web developer do some tasks a lot easier and faster then coding everything yourself. If you want to be a professional Web Developer, then it is a must you learn at least one framework, which boosts your speed of development.

You have a plenty of frameworks which try to be general solutions or specialist solutions. You must evaluate your needs. If you have chosen PHP, I would recommend Laravel as a framework of choice. It is a sound MVC framework which is quite trendy these days. If your choice is with ASP.NET, I would definitely recommend you learn ASP.NET MVC and EntityFramework at least.

Web development can be huge and you may want to focus on one type of applications, let’s say development of web sites with Content Management Systems (CMS). Again if you have chosen PHP, I would recommend you continue with WordPress. WordPress allows you to create web sites, blogs, but also it can be extended with ready plugins or custom themes and plugins to quite complex business applications.

You will find plenty of choices for frameworks for any language you choose, so based on your language of choice, you will have to work with different frameworks.

What next

As a first advice, even if you choose to specialize for Front End or Back End (I would strongly recommend you do), you should have a grasp of the other side, and if you do, your team’s performance will be better. If you have learned a programming language and mastered a framework, what I would recommend is you start with another one. Programming languages have their own philosophies and paradigms, and sometimes some differ quite a lot. Knowing two or more programming languages will allow you have a better picture and understanding how programming problems are tackled and will make you a more fluent developer. As I said earlier, you have to consider many factors when you choose your languages. My choices until today were: JavaScript, PHP, ASP.NET, and Java EE. I’m still looking forward to extend my list 🙂