Javascript : Block Scoped Variables & Functions

This article highlights new feature introduced in ECMAScript 6 called “Block Scoped Variable” & “Block Scoped Functions“. In internet, you may find many articles on block scoped variable and functions. But this is an attempt to present the topic in as much simplest and easiest way as I can so that developers of each level can understand the concept clearly.

Hope everyone reading this article knows about the concept of Block Scope. In general, SCOPE refers to the range to which the particular object is relevant and BLOCK SCOPE refers to the range inside the block. So lets dive into this concept quickly without wasting much time.

Block Scoped Variables

As per ECMAScript 6 standard, a new keyword introduced named as LET. Its somehow similar to the keyword VAR, though it has some differences.

Both VAR & LET keyword are same in context of declaring variable but different regarding to its scope. LET is scoped to the nearest enclosing block whereas VAR is scoped to the nearest function block. If both the keyword present outside the block, then it behaves similarly as global.

Example 1 (with VAR keyword) :-

<script>
    for (var i = 0; i < 10; i++) {
        // do something
    }

    document.write(i);
</script>

// Output : 10

Example 1 (with LET keyword) :-

<script>
    for (let i = 0; i < 10; i++) {
        // do something
    }

    document.write(i);
</script>

// Output : ReferenceError: i is not defined

For the above example, with LET keyword, the variable i is locally blocked to the for loop, but in case of VAR keyword, the variable i is global.

Example 2 (with VAR keyword) :-

<html>
    <head>
        <title>Testing Block Scoped Variables</title>
        <style>
            div {
                width: 100px;
                height: 100px;
                background-color: #ccc;
                border: 1px solid #000;
                display: inline-block;
                font-size: 30px;
                text-align: center;
                cursor: pointer;
            }
        </style>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
        <script>
            $(document).ready(function() {
                for(var i = 1; i < 4; i++) {
                    $("#dv_blockScope" + i).on('click', function () {
                        alert(i);
                    });
                }
            });
        </script>
    </head>

    <body>
        <div id="dv_blockScope1">1</div>
        <div id="dv_blockScope2">2</div>
        <div id="dv_blockScope3">3</div>
    </body>
</html>

// This will output 4 on each click as it refers to the same object.

In order to fix the above issue, we need to wrap the click event in an anonymous function and pass i as argument. But without creating function, we can fix the above issue by just using LET instead of VAR as shown in code below.

Example 2 (with LET keyword) :-

<html>
    <head>
        <title>Testing Block Scoped Variables</title>
        <style>
            div {
                width: 100px;
                height: 100px;
                background-color: #ccc;
                border: 1px solid #000;
                display: inline-block;
                font-size: 30px;
                text-align: center;
                cursor: pointer;
            }
        </style>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
        <script>
            $(document).ready(function() {
                for(let i = 1; i < 4; i++) {
                    $("#dv_blockScope" + i).on('click', function () {
                        alert(i);
                    });
                }
            });
        </script>
    </head>
    <body>
        <div id="dv_blockScope1">1</div>
        <div id="dv_blockScope2">2</div>
        <div id="dv_blockScope3">3</div>
    </body>
</html>

// This will output the respective number i.e. 1, 2 & 3.

Block Scoped Functions

According to ECMAScript 6, the syntax for block scoped functions got changed. The function scope can be written in a different and easy manner. Lets go through one example to differentiate.

Example 3 (syntax with ES5) :-

<script>
    (function() {
        // first function
        var operation = function (a, b) {
            return a + b + '<br>';
        }

        document.write(operation(1, 2));  // O/P - 3 (executes 1st function)

        (function () {
            // second function
            var operation = function(a, b) {
                return a * b + '<br>';
            }
    
            document.write(operation(2, 3));  // O/P - 6 (executes 2nd function)
        })();

        document.write(operation(2, 3));  // O/P - 5 (executes 1st function, as it belongs to the main block)
    })();
</script>

The above example contains same method but in different function block. There are some specific notations I used in the above example which let me note it down.
1. While declaring a self executable function, we had to use (function() { .. })();.
2. We had to use var = function (param1, param2, …) { … }; notation to define a function.

But with ECMAScript 6, lets see how the scoped definition for function changed.

Example 3 (syntax with ES6) :-

<script>
    {
        // first function
        function operation(a, b) {
            return a + b + '<br>';
        }

        document.write(operation(1, 2));  // O/P - 3 (executes 1st function)

        {
            // second function
            function operation(a, b) {
                return a * b + '<br>';
            }

            document.write(operation(2, 3));  // O/P - 6 (executes 2nd function)
        }

        document.write(operation(2, 3));  // O/P - 5 (executes 1st function, as it belongs to the main block)
    };
</script>

Check the syntax with ES6.
1. We no need to write a complicated line like this (function() { .. })();. We only have to write { .. };, plain & simple.
2. We no need to use var = function (param1, param2, …) { … };, instead we can directly write function (param1, param2, …) { … }.

Example 4 (syntax with ES5) :-

<script>
    (function foo() {
        let x = 1;

        (function foo() {

            let x = 2;
            document.write(x + '<br>');  // O/P - 2

        })();

        document.write(x + '<br>');  // O/P - 1
    })();
</script>

Example 4 (syntax with ES6) :-

<script>
    {
        let x = 1;

        {
            let x = 2;
            document.write(x + ' <br>'); // 2
        }

        document.write(x + ' <br>'); // 1
    }
</script>

That’s it !!! Hope I am clear on Block Scoped Variables & Block Scoped Functions. Do you find it useful? If yes, then please like and add comments :). Thank you and I will be happy to hear from you 🙂 🙂 .

Note :- Check here for Browser support details.

Advertisements

Dive into Javascript forEach()

Hello everyone, this time lets go through one of the popular control flow statement in programming language named as “foreach”. “foreach”, as the name suggests, it is a control flow statement for traversing items in one or set of collection(s). This article will cover how it works with Javascript.

I hope everybody reading this article knows about what control flow statement is. Still lets go through a short glimpse about it.

“The statements inside your source files are generally executed from top to bottom, in the order that they appear. Control flow statements, however, break up the flow of execution by employing decision making, looping and branching, enabling your program to conditionally execute particular blocks of code.”

It suggests flow of the control, the order in which the statements will execute in any application. Some examples are switch-case, if, if-else (decision-making statements), for, while, do-while (looping statements), return, break, continue, label (branching statements), in general.

We will go through one new control flow statement called foreach, which is supported by these languages, as per the wiki.

General Syntax :-

for each item in collection:
  do something to item

forEach in Javascript, iterates upon Array or object(Map or Set) with the following syntax.

  • Array.prototype.forEach() :- arrElem.forEach(callback[, args]);
  • Map.prototype.forEach() :- arrElem.forEach(callback[, args]);
  • Set.prototype.forEach() :- arrElem.forEach(callback[, args]);

1. Array.prototype.forEach() :-
The method executes the specified callback function once for every array element. Lets check some examples and get clarified.

Example 1 :-

var arr = [1, 2, 3, 4, 5];
arr.forEach(function(val) {
    document.write(val + ' - ');
});

O/P :- 1 – 2 – 3 – 4 – 5

Example 2 :-

function getSquare(elem) {
    document.write((elem * elem) + ' - ');
}

var arr = [1, 2, 3, 4, 5];
arr.forEach(getSquare);

O/P :- 1 – 4 – 9 – 16 – 25

Example 3 :-

// Object which contains the callback function for forEach.
var testObj = {
    getSquare: function(elem) {
        document.write((elem * elem) + ' - ');
    }
};

var arr = [1, 2, 3, 4, 5];

// First argument is to call the getSquare function.
// Second argument 'testObj' is 'this value' present inside callback function.
arr.forEach(testObj.getSquare, testObj);

O/P :- 1 – 4 – 9 – 16 – 25

2. Map.prototype.forEach() :-
The method executes the specified callback function once per each key/value pair in the Map object. Lets go through the examples.

The syntax for callback function should be like below :-

Syntax :-

function callbackfn(value, key, obj)

// As per ECMAScript
function callbackfn(value: V, index: K, map: Map)

Example 1 :-

function assignVehicle(val, key, mapObj) {
    document.write('&lt;b&gt;' + key + '&lt;/b&gt; has bought a new &lt;b&gt;'+ val + '&lt;/b&gt;&lt;br&gt;');
}

var map = new Map();
map.set('prava', 'Fiat');
map.set('Bob', 'Harley');
map.set('Maria', 'Audi');

map.forEach(assignVehicle);

O/P :-
prava has bought a new Fiat
Bob has bought a new Harley
Maria has bought a new Audi

3. Set.prototype.forEach() :-
The method executes the specified callback function in the Set object once per each value. Lets check some example.

Example 1 :-

function checkValue(val) {
    document.write(val + ' - ');
}

var setObj = new Set();
setObj.add(1);
setObj.add(2);
setObj.add('prava');
setObj.add('Maria');

setObj.forEach(checkValue);

O/P :- 1 – 2 – prava – Maria

That’s it !!! We are done with the forEach statement of Javascript. Hope you are clear on the use of forEach control statement and hope you get to know how to use it. But even though it is pretty to use and upon using, the code looks much cleaner, there are some disadvantages of using forEach, which I will cover in my upcoming blog. So, stay tuned for more details and what to use & what not.

Do you find it useful? If yes, then please like and add some comments :). Thank you and I will be happy to hear from you 🙂 :).

Getting started with PHP on Azure

Hello Everyone, today let’s make ourselves ready to learn a new topic i.e. hosting PHP application on Azure. Many of us must have came across the word Azure and some of us must be knowing how to host the application written in PHP on it. Today we will go over how to host the application on Azure and how to auto-deploy the code through bitbucket. So, why to wait !! Lets start then :).

In this blog, we will mainly come across these following words.
1. PHP
2. Microsoft Azure
3. Bitbucket

1. PHP :-

“PHP is a server-side scripting language designed for web development but also used as a general-purpose programming language.” – wiki

Chicago Manual of Style, content style guide
The word PHP i.e. Hypertext Preprocessor earlier called as Personal Home Page. In 1994, Rasmus Lerdorf created this pretty language and in 1995, it came into existence as an open source technology. Because of its simplicity (as most of the syntax resembles to C, C++, Java), it is much popular in web development market and among the developers. One can take 100% advantage of using this language to make dynamic web pages quickly. It is a server side scripting language. Server side, as the name suggests, it runs on a web server and it requires a web browser to send/receive request/response. Scripting language, as the name suggests, it is only compiled when an interpreter reads it and convert it into machine understandable language.

But, first and foremost thing why developers love this technology is easy to learn, free of cost, platform independent and secure.

2. Microsoft Azure :-

“Microsoft Azure is a cloud computing platform and infrastructure created by Microsoft for building, deploying, and managing applications and services through a global network of Microsoft-managed data centers.” – wiki

Chicago Manual of Style, content style guide
The name Azure suggests, bright blue in colour like a cloudless sky. But in our context, this is little different :D. It is a platform which provides PaaS (Platform as a Service) and IaaS (Infrastructure as a Service) categories of cloud computing services. It supports many different programming languages including Microsoft and non-Microsoft related technologies. Azure was launched on 1st February 2010 as Windows Azure and then acquired the name as Microsoft Azure on 25th March 2014.

It is easy to publish and manage websites with PaaS environment. Mostly used for cloud computing, which literally means of using network to manage data, process and store which is hosted on remote servers rather than a local or personal server.

3. Bitbucket :-

“Bitbucket is a web-based hosting service for projects that use either the Mercurial (since launch) or Git (since October 2011) revision control systems.” – wiki

Chicago Manual of Style, content style guide
I hope everyone here are familiar with GIT, the version control system which is used for data integrity and support for distributed workflows. It is used to manage source code and the name satisfies as SCM, Source Code Management.

Bitbucket is the solution for professional teams who uses GIT. It offers hosting source code in free of cost and it has the option to add wikis for project & option to track issues. It is similar to Github which is used to manage the code for a distributed application.

Now, let’s start with setting up and host a PHP application on Azure.

Step 1 :- First, we need to login into the account on Azure Portal. For that, we need to provide work or school or personal Microsoft account, otherwise need to create a new Microsoft account without any cost.

Once you successfully logged in into the system, it will redirect into Azure Portal page. See the below image for reference.

Screen Shot 2016-05-14 at 10.18.31 PM

Step 2 :- Now, click on All Resources -> New button for creating the base/marketplace.

Screen Shot 2016-05-14 at 11.22.49 PM

Then select Web App + MySQL for hosting the application. Click on Create button for creating the hosting setup.

Screen Shot 2016-05-14 at 11.24.06 PM

Step 3 :- Once you click on Create button, it will open one form to provide App Name, Subscription Details, Resource Group, Database Details and Legal Terms to accept. Provide a unique App Name as the website hosting name would be app_name.azurewebsites.net and the DB details (choose Database pricing tier as Mercury, the free one) as like below.

screen-shot-2016-05-14-at-11-25-18-pm

screen-shot-2016-05-14-at-11-27-15-pm

screen-shot-2016-05-15-at-1-01-44-am1

Step 4 :- Once you provide every information mentioned above, check Pin to dashboard option and click on Create. Now, it will start the process of deployment the server and it may take few time to complete the process.

submitting_deployment

Screen Shot 2016-05-16 at 12.33.44 PM

Step 5 :- Now lets go to Bitbucket (https://bitbucket.org/) and create the account. Do the Signup here (https://bitbucket.org/account/signup/) and you can see the Dashboard like the below once you successfully logged in into the system.

screen-shot-2016-05-16-at-12-45-25-pm

Step 6 :- Inside Bitbucket, go to Repositories -> Create Repository. Provide the necessary details there like below :
Screen Shot 2016-05-16 at 12.53.14 PM

Once you Create Repository, it will show the dashboard for Repository setup and then select “I’m starting from scratch”.

screen-shot-2016-05-16-at-12-57-01-pm

Step 7 :- Open your Terminal to run some commands. Follow the rules mentioned in the above section i.e. “Set up your local directory”, “Create your first file, commit, and push”. For reference, do the following :

Set up Git on your machine if you haven’t already

Create your first file, commit, and push

  • phpinfo() >> phpinfo.php
  • git add phpinfo.php
  • git commit -m ‘Initial commit with phpinfo’
  • git push -u origin master

Step 8 :- Now time is to connect Azure with the deployment source for continuous integration. Again lets go to https://portal.azure.com and click on All Resources. Select the app we have created so far i.e. test-demo-app (type as App Service) and then choose Deployment Source from PUBLISHING section like below.

screen-shot-2016-05-16-at-1-23-33-pm

Step 9 :-

Click on Choose Source and select Bitbucket as the source. Provide the Authorization details of Bitbucket. Once Authorization is completed, it will ask to choose Project and branch. Provide all the details like below.

Screen Shot 2016-05-16 at 1.32.54 PM

Step 10 :- After providing the details and click on OK will start the source deployment and finally it will show one flash message as Successfully set up deployment source.

We are all DONE !!! 🙂 Now browse http://test-demo-app.azurewebsites.net/ (as we have provided the name as test-demo-app so far) and you can view the current PHP information for your server now.

Isn’t it cool & easy !!! 🙂 So, why to wait? Create one simple PHP page and host the application into Azure along with continuous integration using git Bitbucket. Do you really find it useful? If yes, then please like and add some comments, if you want.

Thanks and I will be happy to hear from you 🙂 :).

CSS: Nested Selector vs Modular Selector

Hello Everyone, today I am going to share on two different categories of selectors i.e. Nested Selector and Modular Selector. Let’s quickly jump to check 2 different style aspect without waiting for a moment.

Basically, there are 2 different categories of presenting the style –
1. Nested Selector (shortcut selector)
2. Modular Selector (flexible selector)

Let’s quickly go through one example to make it more clearer. Lets say we have to design the navigation section like below :

nested selector - 1

To design the navigation pad, the code will look like this :

<html>
<head>
    <title>Example of Nested Selector</title>

    <style type="text/css">
        .sidebar {
            box-sizing: border-box;
            float: right;

            .title {
                margin-bottom: 15px;
                margin-top: 20px;
                position: relative;
            }
        }

        .nav {
            list-style: outside none none;
            margin-bottom: 0;
            padding-left: 0;

            > li {
                display: block;
                position: relative;

                > a {
                    display: block;
                    padding: 10px 15px;
                    position: relative;
                }

                &.active {
                    > a {
                        background-color: #fafafa;
                        border: 1px solid #f3f3f3;
                        color: #e84c3d;

                        &:hover {
                            background-color: #fafafa;
                            border: 1px solid #f3f3f3;
                            color: #e84c3d;
                        }
                    }
                }
            }
        }
    </style>
</head>

<body>
<aside>
    <div class="sidebar">
        <h3 class="title">Components</h3>
        <div class="separator"></div>
        <nav>
            <ul class="nav nav-pills nav-stacked">
                <li class="active">
                    <a href="">Tabs & Pills</a>
                </li>
                <li><a href="">Accordions</a></li>
                .........
                <li><a href="">Image Boxes</a></li>
            </ul>
        </nav>
    </div>
</aside>
</body>
</html>

The above code is a simple example on how nested css can be written. But guys, did you find the problem with the above code. Can we use only .sidebar style (title with different css) in any other place in future?

No .. right!! As the styles are nested, we can not use the component separately as we want.

So, if we want to reuse each and every style what we have written so far, we have to use Modular way to design the style.

Lets check the same example in a Modular way !!

<html>
<head>
    <title>Example of Modular Selector</title>

    <style type="text/css">
        .sidebar {
            box-sizing: border-box;
            float: right;
        }

        .sidebar .title {
            margin-bottom: 15px;
            margin-top: 20px;
            position: relative;
        }

        .nav {
            list-style: outside none none;
            margin-bottom: 0;
            padding-left: 0;
        }

        .nav > li {
            display: block;
            position: relative;
        }

        .nav > li > a {
            display: block;
            padding: 10px 15px;
            position: relative;
        }

        .nav > li.active > a, .nav > li.active > a:hover {
            background-color: #fafafa;
            border: 1px solid #f3f3f3;
            color: #e84c3d;
        }
    </style>
</head>

<body>
<aside>
    <div class="sidebar">
        <h3 class="title">Components</h3>
        <div class="separator"></div>
        <nav>
            <ul class="nav nav-pills nav-stacked">
                <li class="active">
                    <a href="">Tabs & Pills</a>
                </li>
                <li><a href="">Accordions</a></li>
                .........
                <li><a href="">Image Boxes</a></li>
            </ul>
        </nav>
    </div>
</aside>
</body>
</html>

So, now can we use only .sidebar class for any other styles? A BIG YES right !!! 🙂

Nested selectors are more complex and those are less readable. But, it has its own advantages of targeting DOM elements. Maintainability is easy as, we just need to do fewer changes when the class name need to be changed later. The code will look concise and the selector looks pretty.

But, now-a-days CSS is getting more modular. It is modulated into different defaults, components, and settings and developer/designer should take 100% advantage of doing so. With modular CSS, coding is much easier like writing simple HTML. Styles will be consistent and easier to reuse the modules. Once the base been created, it would be easier to do modification in future. Then the subsequent development time will be very less. It simplify the code as clashes will not happen with this type of styling.

Much theories !! 😀 Ahh .. I know :).. Let’s stop then. Now you decide which one is better and why. Do you really find it useful? 🙂 If yes, then please like and add some comments, if you want.

Thanks 🙂 and I will be happy to hear from you 🙂 :).

CSS: Creating nested numbered list using CSS-Counters

Hello everyone, today I am going to share one basic thing, which you all may know about it. I am going to explain how can we create numbered list using CSS. So, let’s go through it quickly without wasting much of our time :).

HTML provides us few ways of creating lists. A list can be created using either of the following 3 ways i.e.

  • Unordered List
  • Ordered List
  • Description List

Let’s have a look at the results created by the above 3 lists –

counters-1counters-2counters-3

As the post title suggests, we will have our focus on Numbered List, we’ll consider only the case of Ordered List which alternatively known as Numbered List.

Let’s notice the default behavior of a numbered list. The sub-numbered list has started numbering from 1 to n, once again. Now, what if I need those to be numbered like 1.1, 1.2, 1.3… so on?

This can be done in various ways using Javascript OR CSS.. WAIT ! umm … CSS?
With alone CSS can we achieve this?

Yes, we can :). I know, the primary use of CSS is to describe the presentation semantics of an HTML document but, we can also use CSS for content generation. With the use of Content property along with pseudo-elements like :before, :after etc. we can inject a piece of content into an HTML element. But here our HERO is “CSS-Counters”. Let’s quickly go through this. There are 3 properties for CSS-counters –

  1. counter-reset: counter-name /* initializes or resets the counter */
  2. counter-increment: counter-name /* increments counter values */
  3. content: counter (counter-name) /* evaluates to counter value */

Let’s go through an example :

<!DOCTYPE html>
<html>
    <head>
        <style>
            body {
                counter-reset: section;
            }

            h1 {
                counter-reset: subsection;
            }

            h1:before {
                counter-increment: section;
                content: "Section " counter(section) ". ";
            }

            h2:before {
                counter-increment: subsection;
                content: counter(section) "." counter(subsection) " ";
            } 
        </style>
    </head>
    <body>
        <h1>Wordpress</h1>
        <h2><a href="https://pravasini.wordpress.com">https://pravasini.wordpress.com</a></h2>
        <h2><a href="http://suvendugiri.wordpress.com">http://suvendugiri.wordpress.com</a></h2>
        <h2><a href="http://tanmayabiswal.wordpress.com">http://tanmayabiswal.wordpress.com</a></h2>

        <h1>CodeProject</h1>
        <h2><a href="http://www.codeproject.com/Members/prava-mfs">http://www.codeproject.com/Members/prava-mfs</a></h2>
        <h2><a href="http://www.codeproject.com/Members/SuvenduShekharGiri">http://www.codeproject.com/Members/SuvenduShekharGiri</a></h2>
        <h2><a href="http://www.codeproject.com/Members/taditdash">http://www.codeproject.com/Members/taditdash</a></h2>

        <h1>Stack Overflow</h1>
        <h2><a href="http://stackoverflow.com/users/2269132/prava">http://stackoverflow.com/users/2269132/prava</a></h2>
        <h2><a href="http://stackoverflow.com/users/1006297/suvendu-shekhar-giri">http://stackoverflow.com/users/1006297/suvendu-shekhar-giri</a></h2>
    </body>
</html>

The above code will generate :
result

Isn’t it interesting!!! 🙂 Just using CSS, we can generate the contents as like above styling. Do you really find it useful? 🙂 If yes, then please like and add some comments, if you want.

Thanks 🙂 and will be happy to listen from you 🙂 :).

Handy tips to handle form submit using AJAX

Hello everyone, this time, I am going to explain different ways to handle form submit using AJAX.

Basically, to submit a form via AJAX, we need to follow certain process in our javascript file.

1- Process form submit event
2- Get all the form data using javascript/jQuery
3- Submit the form with data using AJAX
4- Show success/error message according to the result

So, in this blog, we are going to discuss different ways to get all the form data. Lets put some light into there :).

Tip – 1
Get all form data individually and put in key=>value format like below.

var formData = {
    'first_name'  : $('input[name=first_name]').val(),
    'last_name'   : $('input[name=last_name]').val(),
    'dob'         : $('input[name=dob]').val(),
    'gender'      : $('input[name=gender]').val(),
    'email'       : $('input[name=email]').val()
};

In short cut, one can write :

$("#form[name]").each(function(event, obj) {
    formData[obj.name] = $(obj).val();
});

Tip – 2
Instead of getting the data individually, we can use serialize() to get the data in string manner.

var formData = $("#formId").serialize();

The above code will produce the data in string manner i.e.

first_name=Rasmus&last_name=Lerdorf&dob=....

Tip – 3
We can use serializeObject() for serializing the data, which, instead of encoding form elements to string, converts form elements to a valid JSON object.

var formData = $("#formId").serializeObject();

Note: You need to include the below code to use serializeObject().

$.fn.serializeObject = function()
{
   var o = {};
   var a = this.serializeArray();
   $.each(a, function() {
       if (o[this.name]) {
           if (!o[this.name].push) {
               o[this.name] = [o[this.name]];
           }
           o[this.name].push(this.value || '');
       } else {
           o[this.name] = this.value || '';
       }
   });
   return o;
};

Using the above code, we can access the data using .(dot) operator i.e.

formData.first_name ==> Rasmus

Tip – 4
We also can use serializeArray(), which creates an array of objects (name and value) by serializing form values.

var formData = $("#formId").serializeArray();

After applying seriaizeArray(), we can get the data by looping through it i.e.

$.each(formData, function(event, field){
    $("#results").append(field.name + ":" + field.value + " ");
});

The above will print first_name:Rasmus last_name:Lerdorf dob:….

Tip – 5
We can use HTML5 formData() to achieve the same thing. It allows to compile a set of key/value pairs to send data using XMLHttpRequest.

var formObj = document.querySelector("form");
var formData = new FormData(formObj);

The output data will be in the same format that the form’s submit() method would be.

Okay!! That’s it… One can use any of the way mentioned above for accessing the form data. Do you really find it useful? 🙂 If yes, then please like and add some comments, if you want.

Thanks 🙂 and will be happy to listen from you 🙂 :).

Zend Framework 2 : Error & Exception Handling

Hello everyone, today I am going to share one problem I faced, when I was developing my first project with Zend Framework 2. The issue was with defining and managing error, exceptions. In the front-end, it was displaying errors/exceptions to the user, rather filing it into any file. It was too awkward for user to see the error message as kind of paragraph in the front-end :D.

So, that time, I thought of logging those errors/exceptions in a log file, for further check and fix for the issue, as we always do with any other framework/normal PHP projects. I searched for the native solution, it is present or not in the same Framework. I found the manual (though now-a-days we can find a lot of blogs/tutorials for solving error logging issue), where some logging code has been written, and which I thought would definitely help me to reach my goal.

So, what I did was – I just gone through the manual for error logging once, and believe me, I didn’t understand even 50% of the concept 😀 :D. That’s why I decided myself to keep patience and go through the same manual once again or twice.

Hmmm… after reading 3 more times, I got some points and I thought of using it in the code. Then, I checked and analyzed what should be the best position to use the logger code, so that it would help me as extent and I should not have to write the same code again and again.

So, here I am going to explain what attempt I had taken that time and it was successful also. Let’s check step by step process, of adding the logger for errors/exception.

1st Step
First attach to the dispatch error event inside Module.php (say in Application folder).

public function onBootstrap(MvcEvent $e)
{
    // other config code

    $sm = $e->getApplication()->getServiceManager();
    $sharedManager = $e->getApplication()->getEventManager()->getSharedManager();

    $sharedManager->attach('Zend\Mvc\Application', 'dispatch.error',
        function($e) use ($sm) {
            if ($e->getParam('exception')) {
                $sm->get('\Zend\Log\Logger')->crit($e->getParam('exception'));
                return false;
            }
        }
    );
}

2nd Step
Create service.config.php file (say Application/config/service.config.php).

return array(
    'factories' => array(
        // other config code ,
        '\Zend\Log\Logger' => function($sm){
            $logger = new Zend\Log\Logger;
            $writer = new Zend\Log\Writer\Stream('./data/logs/' . date('Y-m-d') . '-error.log');

            $logger->addWriter($writer);
            return $logger;
        },
    ),
);

Now, it’s done. The call anyway will go through bootstrap method and will log the error if any into one file. The path we used above for creating the log is inside ‘data/logs/’ directory. Do you really find it useful? 🙂 If yes, then please like and add some comments, if you want.

Thanks 🙂 and will be happy to listen from you 🙂 :).