Two way data binding in angular js

Data binding is a feature that you might have heard of in javascript. It is one of the core principles of javascript.

Let us take a look at what this concept means with respect to angular js.

What is data binding?

Data binding in angular js can be explained in the following example:

<div ng-init="personName='test data'">

The output will be as below:

Here the model data is initiated using the ng-init directive. This model data is bound to the html content using the angular binding expression “{{}}”. This is one way data binding in which any changes you make to the model will be reflected in the html.


Two way data binding:

Now we know what a one-way data binding is. Angular provides a powerful feature of two-way data binding. You have seen that the model can modify the html view. Similarly any changes to the bound view can modify the model as well in angular js. This concept is known as two-way data binding.

Take a look at the example below to give you a better idea:

<!doctype html>
<html ng-app="todoApp">
 <script src=""></script>
 var data = {
 names: [
 name: 'roshni',
 done: false
 name: 'devadiga',
 done: true
 name: 'pri',
 done: true
 var todoApp = angular.module('todoApp', []);
 todoApp.controller('todoCtrl', function($scope){
 $scope.listOfData = data;
 <body ng-controller="todoCtrl">
 <li ng-repeat="user in listOfData.names">
 <input type="checkbox" ng-model="user.done">

Here the output would be as follows:

Here the list is populated using a model data.names. This model data is bound to the checkboxes and also the respective values are displayed next to them. Here you can see one way data binding since the data of the model is used to modify the view elements. Once you click on the checkboxes, its values toggle. Here two way data binding comes into picture where the changes in the views modify the model data.


I hope this post helped you understand the basics of two way data binding in angular js.

Angular js vs angular 2

Angular js was introduced in 2009 as framework to develop single page applications, popularly known as SPA’s. From here it has come a long way and has become an integral part and is widely used in today’s web applications.

Angular 2 was introduced in 2014. Angular 2 is different from angular js in a variety of advanced features and the way things are handled.

Let’s take a look:

  1. The prime building blocks of angular js were controllers and $scope objects. These are dropped in angular 2. These are replaced with components and directives in angular 2.
  2. Angular 2 was developed keeping in mind mobile application where you need performance improvement. This implies that angular 2 is better in performance than angular js
  3. A lot of modules have been removed in angular 2 which makes it lightweight.
  4. Angular 2 has little backward compatibility so migration from angular js to angular 2 will be a big job
  5. Angular 2 is based on ES6 model
  6. Angular 2 has child routing feature which wasn’t present in angular js. The whole application can be divided into mini applications each mini application having its own routing feature.
  7. Angular 2 also has a logging feature which helps in performance analysis and improving performance.

Create a download functionality in php

Php has a huge set of features to implement almost anything that you see across the internet. One of the common functionalities that you can find especially in dashboards is the functionality to download reports mainly in xls or csv format.

In this article I will show you how to implement this functionality using php and javascript/jquery. Here are the steps:

Suppose you have a table having user data which you want to download in a csv file. Here is the html of the table

<table class="user_table">
      <th>Email Id</th>
      <th>Phone No</th>
 <tbody class="user_details_table_body">

Now create a download button. Clicking on this button will trigger the download of the above table. The html of the download button is as follows:

<div class="download_data_div">
    <a class="download_button">Download data in csv format</a>

Now we need to write the javascript that would trigger the download of the table. We will collect the data of the table in an array ‘myTableArray’ and pass it to the ‘download’ function. The download function will build a temporary form with action as ‘post’. It will add a hidden field in the form with value as the array data (‘myTableArray’) that you pass to the function. It will then submit the form to the php code that will have the download logic. In the same step it will remove the temporary form so that the user is on the same page and does not get redirected.

Here is the javascript code which we would bind to the download button


jQuery('.download_button').on('click', function(){
        var myTableArray = [];

        jQuery("table.user_table tr").each(function() {
            var arrayOfThisRow = [];
            var tableData = jQuery(this).find('td');
            if (tableData.length > 0) {
                tableData.each(function() {
    download('<url>', 'table_data', myTableArray); //replace '<url>' with the url of the code that has the download logic

Here is the actual download function in javascript

var download = function(url, key, data){
    // Build a form
    var form = jQuery('


').attr('action', url).attr('method', 'post');
    // Add the one key/value
    form.append(jQuery("<input></input>").attr('type', 'hidden').attr('name', key).attr('value', JSON.stringify(data)));
    //send request

Now we need a code that will handle the download logic in php and send a csv file to the browser from the server containing the data that was sent in the array
Here is that php code:

$filename = "dashboard_report_" . date('Ymd') . ".csv";
  $fp = fopen('php://output', 'w');
  header("Content-Disposition: attachment; filename=\"$filename\"");
  header("Content-type: text/csv");
  $flag = false;
  foreach(json_decode(stripslashes($_POST['table_data'])) as $row) {
          fputcsv($fp, array('Name', 'Email id', 'Phone', 'City', 'State'), ',');
          $flag = true;
    fputcsv($fp, $row, ',');

Hope this article has helped you. Please reach out to me in case you want any more details by commenting.

Create an xml sitemap in php with fixed set of urls

Xml sitemap is used by crawlers like Google to determine which pages are present on the website. It is like a menu for a vast site. The xml sitemap can be submitted in tools like google webmaster to fasten the process and monitor the indexing of the various pages on the website.

If you a using an open source CMS like wordpress, you have a whole set of plugins at your disposal to create such xml sitemaps and keep updating it dynamically. But without any ready-made plugins in frameworks like Codeigniter, it is difficult to generate such type of xml sitemaps, especially when the number of  site urls are huge. It is definitely not possible and not feasible to generate them manually.

I have come up with a simple code that can help you solve this problem. I have written the code in Php Codeigniter but the function can be used in any php framework.

Here is the code

class Xml_creator extends CI_Controller
    public function __construct()
    public function create_sitemap()
        $url_list = array(
        $xml_result = '<?xml version="1.0" encoding="UTF-8"?>
                     <urlset xmlns="">';
         foreach ($url_list as $url)
            $xml_result .= '<url>';
            $xml_result .= '<loc>'.$url.'/</loc>';
            $xml_result .= '<priority>0.4</priority>';
            $xml_result .= '</url>';
        $xml_result .= '</urlset>';
        $dom = new DOMDocument;
        $dom->preserveWhiteSpace = FALSE;
        $dom->formatOutput = TRUE;
        echo $dom->saveXml();

Here you need to mention the urls of your website in $url_list array and run this php code. The xml sitemap will be printed in the browser which you can copy into a file and save it with .xml extension.

You can then upload it in the root folder of your site and enter its link in Google webmaster’s sitemap section. Your sitemap.xml will be ready to be crawled by Google and your urls will be indexed gradually.

Hope this was useful to you. Do let me know your feedback.

Exciting new features in php 7

Heard about PHP 7 but have very little idea about what it has in store for you? You have landed at the right place.

With the release of php 7, there are a set of excitingly new features and add-ons that would enhance your coding and overall performance of your website.

Lets dive into the details about what php 7 has in store for you:

  1. Lightening fast speed: A couple of benchmark tests have proved that php 7 is much much faster than php 5.6. This will help bring down the server response time since the processing would be faster and will positively impact your php application.
  2. Scalar Type Hints: In PHP there is ideally no need to mention the type of the variable. The PHP engine decides this at run-time depending on the value that is assigned to the variable. In the earlier versions of PHP like PHP 5 you could force passing objects of a particular type function declarations.
    function marksheet(Student $student){}

    Here we are forcing to pass an object of Type ‘Student’ to the marksheet function. If we pass any parameter other than this object it will produce an error.
    Prior to PHP 7 this declaration was only restricted to objects. But with PHP 7 this has been extended to using Scalar types like int, float, string and bool
    eg: We can now use

    function marksheet(float $marks){}
  3. Strict Mode: You can mention a line at the top of the file to enable strict mode on a particular file. By doing this if any of your code does not adhere to the policies of declaring the functions it will throw an error.
    To enable strict mode you need to place the following line at the top of the file ‘declare(strict_types=1);’
  4. Return type declaration: Similar to coercing the argument type you can also enforce the return type of the data returned from the function.
    return (string)($abc + $xyz);
  5. Error handling: In earlier versions of PHP whenever a fatal error occurred then it would directly lead to termination of the script. This was due to absence of proper error handling mechanism. With PHP 7 this problem is solved. These errors can be proper handled using the error handling mechanism since now both Errors and Exceptions implement the new Throwable class. Any error which is unhandled will continue to throw error and terminate the script

Hope this list helped you understand the new features of PHP 7.

Inheritance in javascript

Inheritance is the most widely used object oriented concept which finds it’s way in most of the programming problems. But what is inheritance and why is it so important? This post will answer all your questions.

Inheritance concept in object oriented programming

Inheritance is an object oriented programming paradigm which facilitates adaption or passing over of the properties and methods of one class to another class. The properties and methods of the base class can be used in the derived class. This saves us a lot of rework and facilitates reuse of the existing code.

Consider the scenario where you have a class called Vehicle. Now the Vehicle can have many ‘types’. It has a type of ‘fuel’ that is allowed to be used to run it. It has a ‘mode’ like land, water or air. It has a ‘color’. Apart from these ‘properties’ it also can have methods like run(), stop() etc.

Now consider a four wheeler ‘Car’. It can derive all the properties from the base class ‘Vehicle’ and can also add on its own specific properties or methods to it. Thus the derived class ‘Car’ inherits the base class ‘Vehicle’.

After having understood the basics of inheritance, lets dive into the details of what inheritance looks like in javascript.

Inheritance in Javascript

Unlike other classical languages where one class inherits from another class, javascript has Prototypal inheritance which means that here one object inherits from another object. This is so due to the fact that we do not have classes in javascript but have only objects.
We make use of prototype for inheritance in javascript.

var class1 = function()
{ = ‘Roshni’;
class1.prototype.hello= function(){
var class2 = function()
this.surname = ‘Devadiga’;

//class2 will inherit class1
class2.prototype = Object.create(class1.prototype);

var objectClass2 = new class2();
//The getName function of class1 is inherited in class2

In the above example we first created class1. We added a method ‘hello’ in the prototype of class1. We then created class2. The prootype of class2 inherhited the prototype of class1. With this the properties and methods of class1 became visible in class2. In the last statement we called the hello method from the object of class2.

Google whacking: tips to get relevant results from Google

Google is the most widely used search engine in today’s time. But it gets a little annoying when we type something to search and do not get accurate and relevant results. So what do we do in such cases? Well, the answer to this is Google Whacking.

What is Google Whacking?

It is a trick by which we can get more relevant and accurate results from google. It resides on patterns which Google search engine understands well and using this you can quickly and effectively get the results that you are looking for.

Let me list down a set of tips that will significantly help you to quickly find your answers on Google:

  • Search pages of a particular website: To search the pages of a particular website you can type ‘site:website name’ in google search.



  • If you want to find out specific type of pages within a particular site, simply add the relative url after the website url

Example: to find all category pages within a website, you can use the following query


  • We all love free ebooks, but finding them is a little difficult. But with google whacking it becomes an easy task. You can easily search for pdf for a particular topic using the ‘filetype:’ keyword

Example: filetype:pdf Abc

This will search for the book Abc and give results of all urls containing pdfs


  • Search for specific words in the results: For searching specific words in the results make use of quotes around that word

Example: To search for words abc, xyz and mno, type the query as “abc””xyz””mno”


  • Excluding certain words from the search, make use of hyphen before the word that you want to exclude

Example: To search for abc and exclude xyz type the query as abc -xyz


  • Find all the sites that link to a particular website: If you are a website owner it is always good to know from where your website gets back links ,that is, from where your website gets linked. You can make you of the ‘link’ keyword to find this.

Example: To find from where is getting linked from, use this in search results:


  • Find sites that are of similar type: You can use the keyword ‘related’ to do this.


  • You can use wildcard character ‘*’ which will act as a placeholder which google can replace later

eg: “features php *”




Improve google pagespeed

A high speed webpage is the most essential factor for improving user experience. Is has been observed that page speed also plays a pivotal role to boost the search ranking of a page. It is also one of the first things to fix in any seo tech audit.

For any webpage you would easily get the pagespeed suggestions from the pagespeed insights tool of Google. Here is the url . Simply enter your webpage url in text box and you are set to go. Google will report all the points which can be improved on your webpage and finally give your webpage a score out of 100. It reports for both desktop and mobile webpages. Try to keep the pagespeed of your website above 90 as far as possible.

Here are a few tips that can help you to improve pagespeed:

  • Image optimization : Lossless compression of all the article and site images goes a long way in boosting the pagespeed. There are many free online tools which help you do this. One such popular and tested one which I would recommend is kraken. If you have jpeg images then go for compressjpeg
  • Lazy loading of images: If you have a huge page having a lot of images. So it it not necessary to load all of them in one go. You can gradually load the images when the user scrolls the page. Initially only the images in the first fold would be visible. As the user scrolls down, gradually the images coming in the viewport would be visible. This concept is known as lazy loading. There are a couple of javascript plugins which help you do this. If you are running a wordpress site, your task is much easier since wordpress has some plugins for lazy loading which if installed you may not have to tweak the code much.
  • Defer loading of javascript: Javascript created a lot of render blocking issues. Until the entire js is loaded completely the rendering is stopped. So if we have a big js file then this creates a problem and affects pagespeed. So what we can do is, separate the js file, one containing the js which is needed on initial load and second which contains the ones which can be loaded later. The second file can be defer loaded
  • Create image sprites: Instead of wasting a network call for loading each image, we can combine smaller images to image sprites. With this, instead of multiple calls of multiple images, we can settle down with a single call which saves network bandwidth
  • Implement caching: Rather than going through the entire php procedure we can cut it off for similar type of requests using the concept of caching. When a result is cached and a similar request comes, then instead of using the php engine to process the request, we can simply pick up the data from cache. This saves a lot of time and tremendously boosts the pagespeed.
  • Reduce Server response time: If google pagespeed insights highlights that the server response time of your website is high then it is time to analyse your code to find major performance bottlenecks. Find out which section of your website takes most of the time. Then you can either optimize the code to improve the response time or you can defer load that section if it does not affect user experience adversely. For example, say you have a widget in your sidebar which goes for a couple of third party calls for fetching the data. Since this widget is not that important and does not hamper the initial load experience, you can defer load the entire widget which will bring down the server response time.

Usage of traits in php

Introduction to traits:

Traits were a concept introduced into php since PHP 5.4. Traits are mainly to improve code reuse. If there are a set of methods which needs to be used in a set of classes you can combine those methods in a trait and then ‘use’ that trait in your desired class.


Why not use abstract class?

This would be a valid question that you would ask. But there are differences in the context in which a trait is used against an abstact class. An abstract class is used in scenarios where we have ‘is a’ relationship between the base class and the derived class. An example of such a relationship is base class ‘Car’ and derived class ‘Maruti’. In this case ‘Maruti’ ‘is a’ type of car. So we can make use of an abstract class ‘Car’ and let the derived class ‘Maruti’ extend it.

Multiple inheritance is not allowed in php. So you cannot inherit more than one abstract class.


Difference between traits and interfaces:

One of the main reasons why interfaces were introduced is to support multiple inheritance. Similarly multiple traits can also be used in a class. But the difference between an interface and trait is, in an interface we only have function declarations and the class that implements that interface should provide definition to these functions. Whereas a trait has functions along with the function definition.

Usage of traits:

The context in which a trait is used is different from an abstract class. Traits are used when we do not have any relationship between the base class (trait) and the classes using that trait. The purpose of trait is not to satisfy inheritance but to re-use a set of functions or code. An example would be suppose we define a trait ‘Move’ having functions like walk(), run(), glide() etc. This trait can be used in disjoint classes like ‘Mammal’, ‘Reptile’ etc. These classes do not have any relation with the trait but are simply using its methods since they require a similar functionality and traits help them in code reuse.

Code sample:

trait Move


function run()

{echo ‘It is running’;}

function glide()

{echo ‘It is gliding’;}



Class Mammal


use Move;


Class Reptile


use Move;


Building a custom plugin in wordpress

WordPress is a very powerful CMS with a huge set of features. What makes WordPress extremely powerful is its ability to modify, extend and add new features using plugins. The wordpress repository is full of a large variety of plugins to satisfy almost each and every requirement of a website owner. But there are cases where you need certain functionalities for which a plugin has not been written.  In such a scenario you can always write your own plugin and add the functionality as per your requirement.

Below is a step-by-step guide of getting started with WordPress plugin development:

  • The plugins in wordpress are stored in /wp-content/plugins folder. To create a new plugin, create a folder inside the plugins folder. Here we will name it as test. So now we have a folder /wp-content/plugins/test. Our plugin code will reside inside this folder.
  • Now we create the main php file containing our plugin code. We name it as test.php
  • For the file to be recognized as a plugin file, we need to add a few comments at the beginning of the file:


Plugin Name: test

Plugin URI:

Description: Test plugin description

Author: abc

Version: 1.0



  • Once this is done, save the file and log into the wordpress admin panel. The url would be something like


  • Navigate to plugins option and activate your plugin.

With this you have created your basic custom wordpress plugin. You can go ahead and add the functionality that you want in your test.php file.


Stay tuned for more information on these topics