JavaScript Fundamentals – Session -1: Bangla Screencast

Video is available in HD

Additional Notes

গ্লোবাল স্কোপ, লোকাল স্কোপ, var কিওয়ার্ড

ভিডিওটির ভ্যারিয়েবল নিয়ে আলোচনায় কিছু কনফিউশান তৈরি হতে পারে, তাই এ ব্যাপারে কিছুটা আলোকপাত করা জরুরী । var কিওয়ার্ডটি সব সময় বর্তমান স্কোপে ভ্যারিয়েবল তৈরি করে । এটি ব্যবহার না করে ভ্যারিয়েবল তৈরি করা হলে সেটি আউটার স্কোপে (বা গ্লোবাল স্কোপে) তৈরি হয় । গ্লোবাল স্কোপে তাই এই কিওয়ার্ডটির ব্যবহার কোন প্রভাব ফেলে না কারন গ্লোবাল স্কোপে var ব্যবহার করলেও সেটি গ্লোবাল স্কোপেই তৈরি হবে (কারন var বর্তমান স্কোপে প্রভাব ফেলে এবং তখন বর্তমান স্কোপ হবে গ্লোবাল স্কোপ) ।

একটি উদাহরণ দেখে নেই –

এখানে globalWithVarKeyword একটি গ্লোবাল ভ্যারিয়েবল কারন এটা গ্লোবাল স্কোপে var কিওয়ার্ড দিয়ে তৈরি । অন্যদিকে globalVar টি ফাংশানের মধ্য থেকেও গ্লোবাল স্কোপে তৈরি হয়েছে কারন আমরা var ব্যবহার করিনি ।

Django REST Framework & AngularJS $resource – Trailing Slash Problem

If you use ngResource ($resource) from AngularJS, you probably have already noticed that AngularJS removes the trailing slash from an URL. Django, on the other hand by default has “APPEND_SLASH” turned on. So when you request:

http://example.com/api/object

Django redirects you to:

http://example.com/api/object/

Yes, Django adds an extra slash to the URL. Django REST framework also follows this scheme. Every api end point has a trailing slash.

Angular, not having any trailing slash will always request the first URL above and get redirected to the second one. Apart from the cost of one extra http request, this is fine. The pain appears when we want to make POST request. Django can’t redirect POST requests and won’t accept POST data on the URL without a slash at the end. Damn, Our AngularJS app breaks because it can’t make request to the URL Django expects!

This is a very annoying and known bug with an open issue on their Github for quite sometimes. Since the latest version doesn’t yet have it fixed, I was stuck. Then I noticed somewhere that Django REST Framework responds to this particular bug allowing an extra parameter to “DefaultRouter” to create API endpoints without any trailing slash. Just do this –

It will make sure that the API urls don’t have any slash at the end and play nice with Angular. But we’re not done yet, Django will still try to redirect requests appending a slash. Let’s fix this by adding this to the main settings.py:

Now, we should be able to make REST calls using AngularJS and $resource with sanity! 🙂

Django REST Framework, AngularJS and SessionAuthentication

Here’s the scenario, I am working on an application that uses Django REST Framework in the backend. On the front end I use AngularJS with ngResource. The application is expected to have a web front end and mobile applications in the future. So I chose both BasicAuthentication and SessionAuthentication as default authentication options. BasicAuthentication uses the basic HTTP Auth to verify the user and is suitable for mobile devices. And SessionAuthentication uses the default Django session. Since I have a web front end, SessionAuth comes very handy – I don’t need to send auth data on every request if the user is logged in already.

This works excellent for GET or HEAD requests but things get rough when you need to make a POST, PUT or DELETE request. SessionAuthentication depends on the CSRF token mechanism built into Django. Django requires a special header to be sent with the csrf token. Details are on the Django docs – https://docs.djangoproject.com/en/1.5/ref/contrib/csrf/#ajax.

Getting the cookie and parsing the csrf token part is rather simple. I ported the jQuery version to a generic JavaScript version just by replacing jQuery.trim() with String.prototype.trim() –

Now, ngResource or $resource isn’t very customizable compared to the $http component and most people suggested me to use the latter. Just when I was about to lose hope and planning to rewrite my own wrappers around $http, I just came to realize that $resource is also based on $http. If I can change the global $http config to push the header, $resource will also use the same header. So, I configured things like this –

And finally it works! 😀 Now, every POST request made using $http will have that extra header. But I don’t mind since my application is probably not going to make POST requests to any alien servers 🙂

REST access in AngularJS using ngResource

This will be a short and quick walk through on how to make REST API calls using AngularJS. We shall use ngResource to aid us.

Loading ngResource

If we want to use the ngResource module, we have to make sure it’s being loaded separately along with angular. We need to have something like –

Creating a Module and Resource Objects (Mapping)

Now, we shall create a module named “apiService” to keep our REST stuff separate from our main application logic.

Then we shall map REST api calls to our Angular resource objects. Here we create a Booking resource object and the factory method allows us to do that –

Here we create a new resource object which maps to the API url – “/api/booking” with an optional parameter “Id”. Then we define a set of default parameters to be used, here we instruct to extract the value of “:Id” if “Id” is present in the set of params passed.

The above resource object can make these requests:

GET /api/booking/ — Gets all booking
GET /api/booking/1 — Gets the booking with ID 1
POST /api/booking/ — Creates a new booking
PUT /api/booking/1 — Update booking ID 1
DELETE /api/booking/1 — Delete booking ID 1

Besides the basic methods, we have also added a custom method named “reviews” which would add “reviews_only=true” to make a GET query and return the result as an array. This is helpful to deal with custom queries.

Making Rest Calls

Here comes the fun, how do we use the Booking object to make the different calls?

When making the calls, we need to remember that the first parameter contains the actual data. These data will be used as the parameters of the API. This can be appended like query strings or POSTed. The API will use these data to filter the response. Where as the second parameter overrides the default parameters for the resource definition. It is used by Angular to decide how to make the REST call. In our case, we used – “/api/booking/:Id” as our api entry point and then defined default parameters as – {Id: “@Id” }. So here, the second parameter will help angular decide which URL (by providing the value for Id) to make the request to. We didn’t need to pass any data but we did need to pass the ID in some methods. This is why most of the methods were passed an empty object as the first parameter.

This should explain things a bit more –

Each of these methods allow a callback function to be executed when there is a response from server.

Simple, isn’t it?

Extend Google Apps With Custom Scripts

Let’s get to the point straight way – we can extend the functionality of Google apps with our own scripts. Google allows us to create small scripts written in JS and attach these scripts to certain events (aka triggers) of the respective applications. When these events occur, the scripts are executed. For example, we can attach a script to the event when the user loads a document, or edits a spreadsheet or submits a form. The custom code we write allows the opportunity to do some extra processing. Thus it allows us to achieve a lot more than the default functionality. What are the common use cases?

— Adding our custom functions to spreadsheets
— Adding our own Menus to the user interface
— Creating Macros
— Do more with Forms: send customized messages
— Get sophisticated Gmail statistics
— Send out customized email messages to many people on the fly

and a lot more…

Google Developers Zone has it covered pretty nicely in the “Google Apps Script” section. Have a look yourself!

Just as a demonstration of what could be done, here’s a custom script I wrote to try it out. This script is for a form. It is attached to the “Form Submit” event of the form. When the form is submitted, my custom function gets an event. The event object has a “FormResponse” object which we can use to collect the field names and the values. Then we use “MailApp” object to send the submitted data to an email address:

We could do a lot more than that by adding a flick of our own imagination. Cool, no?

Log to Firebug Console from Firefox Extensions

This is a quick and short post, mainly for self documentation. If you are working on a Firefox extension and want to do “console.log()” to Firebug, you need to use this instead –

You can’t directly use console.log() because your code doesn’t execute from within a “window” instance. If you get “Firebug” is undefined or some similar error messages, make sure that Firebug is installed and working properly.

Firebug needs to be running when you try to log the strings.

Avro Phonetic Plugin for WordPress

Rifat vai has released an awesome jQuery plugin which adds Avro Phonetic layout to your text inputs. I converted it into a WordPress Plugin. Hats off to Rifat vai for the awesome job!

How to use it?

Click on the download link below. It should show you the raw php source of the plugin file. Save it as “avro-phonetic.php” and upload the file to “wp-content/plugins/” directory. Now go to your “Plugins” page from WP Dashboard. Activate the plugin.

Download: https://raw.github.com/masnun/Avro-Phonetic-WP-Plugin/master/avro-phonetic.php

Github Repo: https://github.com/masnun/Avro-Phonetic-WP-Plugin

Official Page: http://torifat.github.com/jsAvroPhonetic/

Knows Issues:

  • Doesn’t work with the Visual Editor (TinyMCE) of WordPress. Please use the HTML editor.
  • Doesn’t show any visual clue of which language (English or Bangla) is active.

    It now shows a black box with language identification

    Thanks to the Avro team for the nice icons.

  • Ctrl + M toggles between Bangla and English. It’s your responsibility to let the users know how to use it. The plugin doesn’t have any fancy instructions displayed to the users.

    It now has a widget. Add the widget to your sidebar.

  • Forces to load jQuery 1.7.2 without caring if an older version is already loaded. Had to do this because wp_enque_script() was not loading jQuery on some themes/setup.

    Thanks to Mehdi vai, the loading is now done using JS after checking if a version is loaded already! 🙂

Contribute:
Feel free to fork the codes on Github and send me pull requests. If you’re not used to Git, send me the modifications over email. I shall merge them and commit. My email address is available on masnun.com 🙂

Have fun!

Working with the Google Chart (Visualization) JavaScript APIs

For a current project at my workplace I need a good charting solution. I need a pie chart for now, on which people can actually click and interact. I found a few tools and went for the Google Visualization APIs. The APIs are a set of JS libraries which let you build quick charts and graphics out of data tables. I started trying the sample codes on the Google Ajax playground and quickly understood which way to go to get things right. First I must make it clear that, I’m no Javascript pro. I have coded with jQuery a few times before and I have no real experience with JS until today. It is just today I spent a good amount of time with the Facebook JS APIs. Who knows if it’s the brilliant documentation at the Google Code or my fast learning ability, it took me just one hour to learn the Visualization APIs and cook something up from scratch.

Here’s the source code:

It’s very simple and easy. First we include the root javascript from: http://google.com/jsapi and then put the above codes in a script tag inside head.

We use the google loader to load the visualization package and then use it to build a PieChart. When the loading is done, the setOnLoadCallback() method invokes another function to proceed with further execution. We packed our main code inside a drawChart() function and set it as the callback.

To assemble the data, we first need a DataTable. A data table is an object with virtual columns and rows. First, we need to define the columns. We do that by calling the addColumn() method. The first parameter is the data type and the second one is the name. In our example, we added two columns.

Next, we call the addRows() passing an integer as the only parameter. This method creates “filler” or empty sets for putting data into.

Then, we use the setValue() call to insert/update data. The first parameter is the row number counted from 0. The second one is the index of column. Remember the sequence of the column definitions? Yes, follow that sequence. The first column is the index 0. The 3rd parameter is the actual value for that row and column.

The above call will insert the string “meaow” into the second column of the 3rd row. It’s easy! 🙂
PS: Please be aware of the data type of the column while inserting/updating data.

Now that we have a DataTable at our disposal, all we need to do is feed this data to a PieChart and draw it up. First, we created a new div with the id “chart”. This div will be holding the chart. Then we call the PieChart constructor with this div element. Then we call the draw() method of the chart object to paint it on the screen. The first parameter is the datatable and the second one is an object (dictionary/associative array like) defining the look and feel of the charts.

That draws the chart alright. But I need to let the users interact with the chart. So, I added a Listener to listen to any “select” events and call the handler function back. We get a event object but for select events, they don’t have any properties. That is they don’t tell you what the user clicked. You have to get the data by calling the getSelection() method of the chart. The returned object will have “row” and “column” values. For PieChart, alone the row value does the job. We get the row index. Then call the getValue() method of the data table to get the value of a certain column in a row. In this case, I just iterated over both columns. Built a text string out of the data and dynamically updated a div with that!

It’s pretty simple. It’s powerful and user friendly as well.

PS: I really liked the Google Ajax Playground. I am gonna play a lot in there from now on 🙂
I just realized I’m becoming a good coder as well. I wrote the above codes without any pretty printer or code formatter. It looks well indented to me 😀

Using The Facebook Graph API with js-sdk : An explanatory Tutorial

The facebook Graph API has a nice Javascript SDK to build applications using JS. The most important benefit is that with JS you could tightly integrate the Facebook Graph API with your web application.

Integration is quite easy. First we add a fbAsyncInit object to the window object for asynchronous initiating. The following code snippet was borrowed from the official docs and then slightly modified:

Thanks to the elegance of Javascript, we called the newly constructed object immediately after initiating, with a callback that loaded the JS sdk on our page. We registered the auth.login, auth.logout events and for initially looking for any logged in user, we made the getLoginStatus() call. In fact this code snippet initiates the facebook access on the page. Registering the events to our custom functions, we just made sure that, we know when something important happens. While iniating, if the user is already logged in, the login() function gets called because of the getLoginStatus() call. Later, after initiating, if the user logs in or logs out, the auth.login and auth.logout events get fired. Our registered handlers will be called in those cases.

To make things easy for the end user, you can use a fb:login-button tag from FBML. I believe Facebook app developers are already aware of that. Still, I was just reminding that you can still use those tags 😀 A login button is going to help you. Because, it’s mandatory that you call the FB.login() on an user event (like button click) because most browsers won’t allow opening a popup on a non-user event.

Now the user is logged in and authorized the apps, you can start customizing your contents for the user. You can always check for available users by calling the FB.getSession() function. It returns null if no user is available, otherwise, it returns a session object with access_token, app key and secret and most importantly the user uid.

You can use the dir() function on the session object to explore it on the Firebug console.

Now, you can make calls to the Graph API using the normal path pattern:

The above code will alert() the user’s latest photo URI. Well, make sure that the applicaton has permissions to make the calls.

You can even mix up with the legacy API by passing an object with a “method” parameter pointing to the method name and related args. You can build the Facbook UIs using the FB.ui() call. Have a look how we use legacy API and UI to build a nifty sharing dialog box.

Here, instead of alert()ing the response, we logged it to the console 😀

In this way, you can interact with the user the way you want. It’s plain and simple. So, start digging now and have fun.

The Offcial js-sdk docs can be found here: http://developers.facebook.com/docs/reference/javascript/

Happy developing! Happy Facebooking! 😀 😀 😀