We have found Malaysia Airlines MH370 in Pakistan

Malaysian MH370 found in Pakistan

Malaysia MH370 found in Pakistan

It’s a norm now, every thing whatever and wherever it happens in the world, it’s a work of some long-beard, bald headed Pakistani! Western media is so sanitised in itself that it wouldn’t even know about thousands of rape cases every year in USA, NSA spying on nearly every citizen of world effectively listening to every conversation we make everyday! but.. yes, human rights violations only exist in poor countries where there is some value, be it oil, be it natural gas, be it keeping eye on your super power status competition. Everything is alright under your noses. Problem is only where you want to look!

What I am not able to understand and nearly everyone is asking this question on Facebook and Twitter, we live in a digital space where NSA is used to of spreading malware through Facebook and still we are not able to track one of the biggest planes on earth? How a plane of the size of Boeing 777 carrying 239 passengers could cross Vietnam, Thailand, Myanmar and India to only land in Pakistan? What were military radars of these countries doing? Can a airliner cross a territory without permission? Do you really think it’s that easy or somebody is fuelling you dollars to say that?

It wouldn’t take you more than a few Google searches to know how aviation radars work? There are primarily 5 types of communication mechanisms which a commercial airliner can use during the flight.

  1. Primary Radars: Mostly used all over the world, even the tiniest and poorest countries in the world have these radars for military purposes. Nothing goes off it’s eyes. It relies on sending electromagnetic waves which then bounce back from any object at a certain altitude and let the people at the base know that some object is flying. That object can then be traced and it’s speed and altitude can be monitored. Air Forces all over the world use these radars to keep an eye on their airspace, any unidentified aircrafts are immediately asked for their intentions, if there is no answer then these Air Forces are allowed to use their multi-million dollar F-16s to tackle the flying object in air. Ironically, MH370 passed 5 countries military radars and tackling aside even none of these countries came up and said “oh yes, we had an unidentified object in our airspace during that time”.
  2. Secondary Radar: It’s the primary method of communication between air traffic controllers and flying planes. Just like military radars, ATCs (Air Traffic Controllers) are tasked to keep an eye on airspace of their region, no commercial plane could pass without identifying themselves first to ATC of that area. These radars also send electromagnetic waves but instead of returning blindly, these waves are then picked up by the transponder of aircraft and a reply is then sent back to ATC identifying the plane. We know now that someone inside the plane delibrately switched of the transponder, so, that means radar was identifying an object but plane was not identifying itself but obvious question is.. a plane was not identifying and ATCs of 5 countries did not do anything?
  3. ADC-B: It’s a new type of equipment which is now coming installed in most aircrafts. Most flight tracking sites such as Flightradar24 uses this equipment to track and plot planes on the map. Everyone can track a flight through these websites or can own a USB-stick for worth $25 and you can then see planes passing your area. Flightradar24 actually picked up planes location and then MH370s transponder suddenly went off the radar. Let’s say someone switched that one off as well.
  4. ACARS: It’s also called pilot communication, it’s sort of SMS service between airline and it’s pilots. The ACARS is subject of most speculation in the case of MH370, this communication system continued to send pings (just a method of telling another server that I am alive) to the satellites, which led experts to believe that MH370 never crashed immediately. It continued to fly for 5 hours more than initially thought and this is what has given the idea that plane is might be in Pakistan (because Pakistan is in that diameter of 5 hour flight from last known point, along with several other countries?)
  5. GPS: Yes, we all do have GPS in our pockets now and we can upload a place on Facebook which could track us back with the accuracy of milli meters, yet most commercial airlines use this technology just like we use it in our cars, to navigate! GPS system installed in Malaysia Airline MH370 was not equipped to send airliner location back to the base.

With all that explained, once again, channels like Fox News and people like Rupert Mudroch are supposed to be most informed but perhaps the scandal of News of the World and subsequent closure of newspaper tell us something, yellow journalism can earn you some dollars but you are never going to get any any respect and your words effectively become hollow over the time.


Local apps and dilemma of Pakistani Android market

Recently, we were approached by mobile Internet department of a major Pakistani telecom player. They were looking for developers which could develop targeted apps for Pakistani users. The reason behind is simple; 3G is just around the corner, sooner or later, telcos will have to launch 3G services, and as a matter of fact, they will not spend money on old and out-dated 3G technology, the licenses on offer include 4G spectrum and we will see service offerings of HSDPA and LTE. These services are known for fast Internet speed, nothing else. You don’t need 3G or 4G for sending SMS or making a phone call. This essentially means that telcos will be spending huge infrastructure money on making high speed Internet accessible for everyone. This also means that primary return on investment will come when users will be actively involved in using data intensive applications and always on – will have a true meaning, watching Youtube videos while riding your school bus will go mainstream!

We are primarily focused on International market of course as our parent company is in UK and most of our apps are iOS based and targeted towards US or European customer base but again we took a chance and spent our month of Ramadan in developing a religious content app with the intention to validate Pakistani apps market. There are few interesting stats we collected on the way. I will list them down here first:

    1. As anybody would guess, Android is the key player here and 70% to 80% smartphones here belong to Android.
    2. The explosion of Android belongs to local (read Chinese) players, such as QMobile, Samsung is on 2nd or maybe even at 3rd place now.
    3. Unofficial statement from QMobile says that they now sell 150,000 Android smartphones a month while market sources say that this number is around 50,000. This is a single brand number and is huge in both cases!
    4. There are a few local apps developed by local indie developers (you can easily guess that they are indie by looking at icons or content of the apps). Download numbers of such few apps are in literally millions, regardless of their quality.
    5. Compared to iOS, Android users are quick to download and subsequently uninstall the app provided if they don’t like it. A major reason of that was memory issue, prior to QMobile, the key smartphone in this market was Samsung Galaxy Y with only 50Mb of free memory, that means you can blow your entire memory in 10-15 apps and can’t download the likes of Facebook app which on average take 32Mb space. However, with advanced phones, this issue is now going away and you can forget about this in 6 months from now.
    6. Another issue is of Android version number which is now going away as well, most phones now run on 4.0 and above.
    7. There is a huge Pakistani diaspora, they need same local apps in some cases, they are always connected, mostly using Samsung S3 or S4 and because they reside in Saudi Arabia, UAE, UK and USA, you can make better money by serving banner ads to them.
    8. Our app is on 31st spot in Audio and Music category with average 200 installs per day which implies that 20th ranked in Top Free is attracting at least 3000-5000 installs per day.
    9. As per my own estimation, we won’t take 2016 to replace feature phone market with smartphones, we will do it much earlier. Most of Nokia N series and E series users will go on Android as soon as next year.

There is obviously a problem of Monetzation here (which is why we don’t see much investment in this sector), however there are few options now available. We are using AdMob, luckily our Islamic religious content is also valid in India and let’s say if it take 1000 Indian banner impressions to make $1 then with Pakistani banner impressions you will need at least 2000 users to make same amount of money.

Keeping all these stats in perspective and looking at our own success, I looked at Top Free Charts on Google Play store; the easiest way to enter in a market is to look at trends of that market, what people are downloading? is the very first and most important question to ask. Google Play store works on IP and if you are in Pakistan, you will automatically see Top Charts of Pakistan or you will need to use proxy with a Pakistani IP to see these charts (maybe use distimo or appannie for same purpose?)


For detailed please visit https://play.google.com/store/apps/collection/topselling_free from a Pakistani IP (or proxy)

For detailed please visit https://play.google.com/store/apps/collection/topselling_free from a Pakistani IP (or proxy)

There is only one trend to spot. Yes, there is a Quran Android app, a dictionary app, local maps app, songs app but as you scroll down, you start spotting what’s in majority here, Sex! .. Slightly disturbing but I am old enough to know the cause of it. It was same in Pre-Facebook (or should I say Pre-Orkut) era. There was no Youtube, no websites to download songs, mIRC and MSN were primary source of communication and rest was the same as you see in Google Play store today. Today, all of us are broadband users (no need to dial a line with noisy modem just to get 2Kb of speed), we have better access to education, many of us now watch US television drama seasons, many of us watch movies and biographies of Steve Jobs, people from Plan9 present their startup accelerator in every university of Punjab, there is a TiE cup happening with a top prize of 1 million Pakistani Rupee, so, why our apps market which is expanding at a rate of at least 200,000 local customers per month, is living in dark ages of 1999 and 2000?

There is a very simple answer to above question: Lack of local apps! Majority new users are first time smartphone users, they certainly need to know more productive use of their phones. We need to find ideas (which are in abundance, there is an app for nothing in Pakistan’s case) and then work to develop them. At this moment, in my experience, you don’t need to go all out and spend 6 months on developing something, just make a 3 activity app, upload it, see the traction, if organic downloads are more than 100 a day, bingo! Go for updates. Ideally, this number should be 200 a day as that is where it will start making sense and you will be able to spend money on a designer and a few rupee on marketing, continue doing this and in the process you will see a big enough idea and big enough user base to capitalize on!

What is Plan9 of PITB?

Good question! You must have heard about Plan9 through a friend or an email on your university’s email list or through Facebook. Here I will explain what it really is without using the buzz words like “innovation, passion, initiative, groundbreaking etc. etc.” and with using but explaining buzz words like “incubator, startup, launchpad, mentor network etc. etc.”
Sit tight and buckle up because I am really going to tell you a recipe of making a few million dollars in few years so, please ensure that you read this blog and don’t check your facebook or youtube during this time .. Well, technically if you do check then probably this Plan9 is not for you!

Question: So, what is Plan9?

A: Plan9 is a program of PITB (Punjab Information Technology Board) in which they take teams which are actually trying to solve a problem through technology. Then:

  • They give you office space (working environment) on 9th floor of posh new Arfa Software Technology Park, Lahore.
  • They will give Rs.20,000/month stipend to each team member to cover your day to day expenses such as your bike’s fuel, food, ticket to the concert etc.
  • Office space will have shared Internet, Telephone, Printers, Copier your personal desks and PITB will also allot you laptops/computers (I will advise to bring your own laptops as I know you won’t be sleeping well during nights)
  • They will help you to incorporate your company and protect your intellectual property rights (legal advise), help will be available to manage your Human Resource (you will need this while managing your team), marketing (you will need a marketing plan and campaign to attract customers/users), branding and other similar time consuming but essential tasks.
  • They will give you access to Pakistani (or foreign) advisors (and trust me when I am saying this) who have made or are making millions of dollars every month through tech businesses, these people will give you advise on how to solve the problem and how to make a bigger company and how to make your few million dollars by selling your shares in the company.
  • PITB will take an intake of 15 teams in each term (each term will be of 6 months), 5 of those who qualify (they get their amazing product ready in 5 months) will go to Silicon Valley in California, USA to participate in another similar program for another 1 month (I will explain all of this below).

Question: How 'solving a problem through technology' can be of worth few million dollars?

A: Again a very good question. Do you know who these are?:
  • Google
  • Hotmail
  • Facebook
  • Angry birds

They all solved a problem initially and they are still solving that problem, in fact they grown so big that they made billions not millions and actually they were and are just solving a problem. Let’s analyse them:

  • Google: It’s 1995. My name is Larry Page and I am a doctoral (PhD) student in Stanford University and my area of research will be human-computer interaction, Internet has 10 million pages by now but search engines are not very efficient, together with my friend, Sergey Brin, who is excellent in mathematics I will do my thesis on counting the number of links between different web pages, then prioritizing them on the basis of “PageRank” which will allow me to see important and most cited research work first and weak research work at bottom. 15 years later, my company’s worth will be $247 billion.
  • Hotmail: It’s 1996. My name is Sabeer Bhatia, an indian immigrant in USA. Today, everyone has their own email addresses but they have to pay their ISPs to have them (imagine if someone asks you to pay PTCL for an email address!). The Internet is rising and I can browse everything through my browser window, one day while driving back home I got struck with an idea to have a browser based email service which will be accessible to everyone everywhere and it will be totally free. I called my friend Jack Smith, together we took an office, asked an investor for some money, hired a team, built the service and few months later we will sell Hotmail to Microsoft in exchange of $400 million.
  • Facebook: It’s 2003. My name is Mark Zuckerberg and I am a cheeky student of Harvard University. I have an idea to develop an online directory of my university’s students, I want to see their photos, their relationship statuses and their interests, then I want to send them a message and ask if any of those would want to go for coffee. I will make such a directory with the name of Facebook and 9 years later, in 2012, it will have 955 million users and it will be valued at $95 billion. (You need to watch “The Social Network” movie if you havn’t still!)
  • Angry Birds: It’s 2009. I run a Finnish company called Rovio. iPhone is 2 years old now and everyone is making iPhone games and making millions of dollars (apparently) but so far we have made and published 104 titles and millions are no where to be seen, we are making a game called ‘Angry Birds’ which will be simple, low cost but highly addictive, this is our last bid. Total downloads for Angry Birds will be a billion times on all platforms and in 2012 my company’s worth will be $6 billion.

Intrigued? All of these started by an idea, that idea wasn’t very unique, there were search engines before Google, there were email services before Hotmail, there were social networks before Facbeook and there were iOS games before Angry Birds. These ideas were executed by right people, at a right place, at a right time, with right kind of money, with right kind of resources available. If Sabeer Bhatia remained in Bangalore or Mark Zuckerberg was a student in Estonia .. well.. you never know but hitting that kind of success would have been far fetched. Initial funding in Hotmail was $2,50,000 .. you can think of sitting in front of your own computer and writing a script for mail server but that can’t be Hotmail, you can bring up a prototype but can’t go on to the scale of Hotmail – take your prototype to Plan9 and they will take you further! (not of another mail server, well yes if it’s unique and solving a problem which is not already solved by someone else)

Story: My Idea busted!

An example of what type of problems I spotted and was thinking of solving:

  • It’s 2009. I am sitting in waiting lounge of Heathrow Airport. There is a shop of branded sunglasses, I always liked Ray Ban’s Aviator but they do not look good on my face plus they are expensive. Whenever I go in that shop, a sales girl will come and stand literally on my head, I am a geek, I want to try all of these sunglasses to see which one look good on my face but at the same time I am not comfortable talking to a sales girl who is trying to pull £100 out of my pocket .. hmm .. what I should do? I look at my iPhone – why don’t I write an app (or for computer using a webcam) which will fit all sunglasses on my eyes when I turn the camera on and then I can go and buy those sunglasses or order them online!
    It’s 2012. I never had resources then plus technically that idea was a bit difficult, technology changes very rapidly, recent advances shown me a way – iPhone 4 just came with a front facing camera and improved processing speed. I figured out how to get money and do this thing, one last time I will go to app store and will try to find if somebody already have made this app: I found one Eyewear Try-on, a basic app but serves the purpose, my idea is gone, somebody better than me just uploaded it in July, 2012. What should I do? I am already on the next idea!
This idea stage is very important, some say ‘ideas are dime a dozen’, they are right but idea stage still remain important. Remember the movie “Inception” – “the smallest seed of an idea can grow and destroy you” – in our case it makes you a millionaire!

Question: I spotted a problem and now I have a technical solution for it, what should I do?

A: If you are solving a problem through technology and if it’s Internet based, you have to be:

  • at right place
  • with right kind of advisors
  • with right kind of money
  • at right time

and the answer is:

  • Silicon Valley in USA is the right place where Plan9 will take you for free
  • Plan9 will give you access to right advisors
  • Plan9 will give you stipend while you make your prototype and then will introduce to potential investors
  • and time is now!

Question: So, why do I need only an Internet or mobile technology based idea?

A: No, if you possess the right skillset and have cracked the code to build a gesture control TV or have made a graphene based Microprocessor, consider yourself a game! but if you want to open up a cafe or world’s fastest ship breaking yard then Plan9 is not for you.
Internet or mobile technology based ideas mostly have limitless growth, which means if you are doing an Android mobile app for a new kind of “to-do notes” then you have access to a market in which Android is unlocking 1.2 million devices a week! For Internet, add a few more millions to that number. In physical world, accessing this kind of scale in few years is far fetched. (However, please consult with PITB or Plan9 team, technology has very vast meanings but yes, Internet and mobile technology based ideas are right thing to do in Plan9).

Question: I read the word startup in Plan9 advertisement, What's a startup?

A: A startup is a setup in which you search for a profitable business model (it can be not-for-profit as well but in Plan9 we are talking about money!). Startup is not a smaller version of a bigger company, you can’t compare Coca-Cola with a startup, Coca-Cola already has a proven profitable business model while as I explained above (see Story: My idea busted!), I had an idea to wear sunglasses on camera and see which one suits me, now it was just an idea, the next step would be to find a business model on which this problem solving idea will make money, next steps can be:

  • I will find a seed investor or fund it myself
  • I will get office space
  • hire a team
  • start engineering
  • meanwhile I will do my market research on buying habits of people who wear sunglasses
  • best bid in this case would be to talk with Ray Ban, Gucci, Parada and ask if they will allow me to use their frames and then I will sale those frames as part of my frame testing app
  • I will start doing some sales
  • based on those sales I will make a business growth plan and a marketing plan
  • then I will pitch to investors to get some more money because I know many people will try to copy this idea as soon as I launch so I need to grow fast to avoid competition plus I will be stupid to think that Ray Ban will seriously listen to Hammad Tariq from Lahore, however, they may listen to James Caan of London (don’t know him? Google him .. no not the actor, I am talking about the Entrepreneur)
  • if my idea is good, growth plan is good and I get enough money I will make millions soon enough!
Now you probably know what I am talking about, again:

Startup = Growth – Exponential Growth not slow growth, if you open a corner grocery shop – you can’t call that a startup, it’s a business based on a proven business model plus it’s reach will be very local, it can’t have exponential growth – a startup is exact opposite of that!

This is what Plan9 would be doing

  • Plan9 gives you office space
  • You bring team and idea
  • Plan9 gives you stipend while you make a prototype
  • You do hardwork to find a growth model
  • Plan9 will give you access to advisors and will introduce you to investors
  • You do the sales and make millions

Question: What is a mentor network then?

A: Simple, a mentor is an advisor who ran a similar startup successfully, he was there, done that type of guy, he know the good things to do and the bad things to do… he can help you to make your idea better, he already know investors, how to reach them and how to talk to them. He already know how to spread the word around and generally is the one who has an answer of your every question or he will refer you to another mentor, a mentor connected to another mentor – a mentor network!

These guys are usually super busy and don’t talk to everyone because lot of people approach them daily with their ideas – beauty of Plan9? These guys are sitting there just for you – waiting for you to come and talk to them!

Question: and what is a LaunchPad?

A: “Launch Pad” – it’s an event organized by P@SHA (Pakistan Software Houses Association) in collaboration with PITB and in this event you will give a presentation about your idea, mentors will ask you questions, if you are successful then you will be selected for Plan9 program and off you go!

Question: What is an Incubator?

A: Alright, an Incubator is basically the office space and controlled working environment you get while your are building your idea. In Plan9, you have to be present 9 to 5 each working day of the week (in ASTP), you will have a fabulous working environment as many teams will be working with you, you will be able to share your ideas, see each other’s code, solve problems, hardware guys talking to software guys, mentors giving advise – you are in an incubator and getting ready to face the world! After six months Plan9 expects you to be a big boy, go out in real world, rent an office space and execute your new business model from there.

Question: What is a pitch then?

A: Another word for presentation, except in presentation you present your idea in form of power point slides or something, but pitch is something which you can give verbally to anyone standing anywhere – something you can tell to someone in one or few sentences and it will explain all of your idea and big picture, for example: “I am thinking of making an app which will allow you to try and wear virtual sunglasses using camera and then you will be able to order those sunglasses online”, now that’s a pitch!
However, when you will be giving pitch to Plan9 board members, you will have to dish out a little more information such as: why you are best suited to solve this problem, who are your competitors, what are your plans about making money etc. But don’t worry, just come along as Plan9 team will spend a whole day with you just to polish your pitch! So, you actually get mentors (read advisors) even before your pitch, a real opportunity to get yourself out there!

Question: I heard about free ride to Silicon Valley, where is it?

Silicon Valley is an area in California, USA where most of the tech companies were formed or have offices. Apple, Google, Facebook, Dropbox, Microsoft, Oracle .. they are all there plus a few thousand more! Today, technical enthusiasts from all over the world go to this place, it has a perfect eco-system in which you meet investors, engineers, entrepreneurs, lawyers, buyers and sellers! That is the place to be if you want to be on the level of Google, Hotmail, Facebook and even Angry Birds, after Plan9 if you will be able to woo an investor based in Silicon Valley and launch your idea there, most probably you are already on the way up!

Question: Who is an Entrepreneur then?

A: If you can spot problems and then you think about solving them and then you even think about executing that solution, you are an Entrepreneur! An Enterpreneur usually fill gaps in the market through solving a problem and through bringing new products to new markets.
If you ask me, I will say Entrepreneur is a person accustomed of seeing dreams during the day! This guy don’t think rationally, this guy risk it all or have nothing to loose and this guy wants to live his life on his own terms, this guy swim against the tide .. this guy is stupid .. the question is: are you that guy??

Question: What if I pitch my idea to Plan9 and then someone copies it before me?

Plan9 gives you some level of legal protection, however, consider these:
  • If you have an idea which people will be able to copy easily, just don’t do it, hop on to another!
  • Success is measured when others start following you, a startup is always at risk, that’s why you need money – a lot of money and access to right set of advisors to grow fast and kill the competition!
  • My idea is my passion, that was a problem which I faced, then I thought of a solution and looked at 100 possible ways to solve the problem, during that research I learned a lot about problem itself and I came in contact with many people who will later help me in building and selling the product! Read my Eyewear Try-on idea above (Story: My idea busted!)? I just given you a concept and while pitching to Plan9 board members I may let them know that I have a Masters degree in Embedded Digital Systems, I am running a company which make cross platform mobile apps and I have access to a computer vision research group in my mother institute which will help me in building the idea but did I told you these:
    – To find eyes in a live image, I will have to first detect eyes then find their middle and then I will guess the area around eyes to fit a frame on.
    – When the user turn his face side-ways (we always do when trying something on), we can not detect the exact measurements and as for the current state of technology, it is very hard, right now as we speak there are multiple researchers in multiple universities who are doing their PhDs on exact same concept and even if there is a solution, it will be very expensive (to hire that PhD and plead to give his research to us) Solution: build the prototype first and then if it’s successful, research and invest if we will be able to detect side-way view as well.

Alright, I just told you 2 points from my treasure of 100, now consider this: You came to a LaunchPad event, you heard my 10 points pitch, went back home and successfully replicated all of it? Are you serious? You will have to have right set of skills for that! An idea is my baby, when it bites me I can’t sleep, the person who is trying to copy .. is just a copier 🙂

  • The problem you faced is never unique, there maybe millions of people who go through that every day (think of someone who like to find perfect sunglasses for himself but can’t stand sales girls or guys), 5 of these millions must have thought of the same solution I thought and 1 of them actually started executing that, when I was placed squarely to solve the problem, I did my research the last time and there was this guy, already launched! You know? You are never unique, your capability to move quickly is unique! What about me? I came up with another idea the next day because that previous idea taught me a lot about image processing and approaching problems, simple isn’t it?

Question: Will PITB or mentors will ask for stake in my startup?

A: No, PITB is a Government organisation, a Government’s primary job is to make policies and promote culture which will help citizens live a better life. Governments already have millions of dollars, they don’t need to take part in your business. For Plan9, mentors are moved by passion of participants and they don’t charge anything in return, basically there is no catch in this program.
However, consider this: There is a mentor who share your passion, believe on the idea and his involvement helped you in shaping the idea, his input is now more than 10-20% and you yourself feel that you need this guy onboard with you not just for Plan9 but even after that, then on mutual consensus you agree to give him a stake, that will be between you and the mentor, nothing to do with PITB or Plan9.

Question: I understand all of this now, I have a wonderful idea, I Googled it but there is nothing like this already and I think this can go on a global scale and I can earn millions, what should I do now?

A: Just go to plan9.pitb.gov.pk, click Apply, they will ask two questions:

  • Which problem you want to solve through technology?
  • Why do you think you are the right person to solve this problem?
They have LaunchPad dates on the website, apply in your choosen city, they will shortlist the ideas and will call you to give a pitch… mentors will first advise and then grill you.. if you pass you will go into incubation program.. keep working hard and you will be in Silicon Valley giving pitches to investors, you will get money and then you ….

If you have any questions, post below or find me on Twitter, the address is http://twitter.com/hammadtariq

Integrating InMobi Ads into jQueryMobile and MoSync based app

Recently I was developing a HTML5 app for a client using jQueryMobile and MoSync Reload with Wormhole Library (an amazing client which let you develop about 70% times faster compared to using native procedures) when I struck with a problem of placing InMobi ads into jQueryMobile sub-pages. If you are familiar with jQueryMobile you would know that it normally fetch pages on ID bases through AJAX and this trick allows it make smooth transitions. While on non-AJAX pages you can simply integrate InMobi’s JavaScript SDK which would be simple JavaScript snippet which you include in your pages and mobile ads will start rolling, however, in case of  AJAX based pages, ad providers normally detect AJAX requests and then refuse to serve ads because of the threat of misuse. I went as far as signing up for an AdMob account but found similar problem there.

I googled through, despite of some questions on stackoverflow, none had the solution (except the solution of turning to non-AJAX based pages which I couldn’t do in any case), I fired up an email to InMobi support and surprisingly got reply with-in an hour linking me to InMobi Mobile Web API.

InMobile Web API require POST request with a certain set of parameters and then return ads in XML format which you then need to parse and display ads wherever you want (including your jQueryMobile sub-pages).

Following is the dissection of request to API:

Basically InMobi Mobile Web API require you to make a POST request along with following parameters:

  • mk-siteid is the ID which you get after registering your app with InMobi through their website, for the purpose of development you can use their test ID which is: 4028cba631d63df10131e1d3191d00cb
  • mk-version is unknow to me but it remains static as it is.
  • h-user-agent is your browser agent which you can easily get through navigator.userAgent
  • mk-carrier is the user IP which you can get through following simple JSON call:
      userIP = data.ip;

and format can always be XML as response will always be.

Moving forward we all know how to make POST request using jQuery along with above parameters:

$.post("http://w.sandbox.inmobi.com/showad.asm", { "mk-siteid": "4028cba631d63df10131e1d3191d00cb", "mk-version": "pr-SPEC-ATATA-20090521", "h-user-agent": navigator.userAgent,
"mk-carrier": localStorage.getItem("userIP"), format: "xml", "mk-ad-slot": 10 },
function(data) {

URL in above post request is of Sandbox which you should use while developing and when you are ready to go Live, you should make your calls to:


At this point if you check your Firebug or Chrome JavaScript developer tools you should see a XML object with AdURL, ImageURL or LinkText in it. The next step would be how we extract this data and display in our page.

First you need to create an ad ‘holding’ area in HTML, in my case I created it just above the closing content div:

<a id="bannerURL" href=""><img id="playerBanner" src=""></img></a>

Next you need to expand your data callback function and include XML parsing capability which should extract the ad data out and show it in ad holding HTML.

function(data) {
        $(data).find("Ad").each(function(){ //find Ad tag and loop through each
        $("#bannerURL").attr("href", $(this).find("AdURL").text()) ;  //get AdURL tag and update 
        if($(this).attr("type") != "text"){ //if ad is not text based
           $("#playerBanner").attr("src", $(this).find("ImageURL").text()) ; //update image src 
        }else{ //in case of text based ad
           if($(this).find("LinkText").text() != "invalid ip-address"){ //ip not found
              $("#bannerURL").text($(this).find("LinkText").text()) ; //just update text

Above code should be self explanatory as I have added comments against each line, basically you need to loop through all of the XML, finding “Ad” nodes, then going through each node and finding AdURL (where user will go after clicking on Ad) and updating href attribute of our hyperlink tag in holding HTML then InMobi serve ads in two formats, one is text and other is image based banner ads. If it’s not text ad, we will get ImageURL and update the img src in our holding HTML, if it’s text ad then we will simply update text enclosed in “a” tags.

This should complete your ad integration and you should see a sandbox banner or text in your sub-pages. In my case it did:

Complete code is below:

var userIP;
        userIP = data.ip;
        localStorage.setItem("userIP", userIP);

$.post("http://w.sandbox.inmobi.com/showad.asm", { "mk-siteid": "4028cba631d63df10131e1d3191d00cb", "mk-version": "pr-SPEC-ATATA-20090521", "h-user-agent": navigator.userAgent,
"mk-carrier": localStorage.getItem("userIP"), format: "xml", "mk-ad-slot": 10 },
function(data) {
        $(data).find("Ad").each(function(){ //find Ad tag and loop through each
        $("#bannerURL").attr("href", $(this).find("AdURL").text()) ;  //get AdURL tag and update 
        if($(this).attr("type") != "text"){ //if ad is not text based
           $("#playerBanner").attr("src", $(this).find("ImageURL").text()) ; //update image src 
        }else{ //in case of text based ad
           if($(this).find("LinkText").text() != "invalid ip-address"){ //ip not found
              $("#bannerURL").text($(this).find("LinkText").text()) ; //just update text
<a id="bannerURL" href=""><img id="playerBanner" src=""></img></a>

This provides basic integration of ad API and you can build your ad serving structure on top of it. One improvement would be of adding your in-house ads which would show banners linking to your other apps probably as often InMobi simply do not return any ad when you go live, instead it would show:

<!-- mKhoj: No advt for this position -->

So, it would be wise to handle this exception and in this case show your own ad.

Happy coding!



Arfa Software Technology Park: A Cultural Shift?

Second blog in line of narrating my experiences and thoughts about Arfa Software Technology Park (ASTP), Lahore.

Along with dominating the Skyline of Lahore, ASTP have already started dominating ICT environment of Lahore in particular even if you want to believe it or not, everybody in the industry knows about it and everybody is talking about it!

How it brings in a cultural shift?

Arfa Software Technology Park, Lahore

Arfa Software Technology Park, Lahore

It’s iconic! .. will be the most short and precise answer!

It represents a 180 degree shift, it’s like giving people hope and landmarking something which our government rarely think about. ICT has it’s root in academia, it is something which directly create knowledge based economy, it directly get benefited by higher education standards, it directly create value for the country by giving jobs to the people and automating several tasks which eats up billions of rupee every year with little outcome (road traffic signal automation, tracking of police vehicles, automatic number plate recognition of each vehicle entering in the city etc. Yes, these all benefits are still a distant dream and we are still pleading turkish government to help us in them without realising how we could do them all at home in few million rupee rather than giving away billions of rupee but that’s another debate!) and it brings in billions of dollars each year without exporting tangible goods, we actually export just knowledge!

The state of ICT based companies in Lahore

– There are about 20-25 large companies in Lahore which have 100+ employees and I am not talking about Mobilink, Wateen etc. Likes of such companies are Teradata, Nextbridge, TRG, Netsol, Game View Studios, Sensys, Intech, System International etc. these are just the few which I can count from top of my head! Most of these companies are located in posh residential area of Lahore city with Gulberg being the most populated and other’s are scattered around in DHA and Johar Town. Few are in commercial plazas such as Shaheen Complex and only a handful have their own buildings such as Netsol. Remaining which are in residential rented buildings, with 100+ employees you can’t fit them all in one building, so, a number of them have to rent multiple buildings with operations staff scattered!

– Then there are small companies which are mostly Elance and oDesk based and they are also located in small residential buildings around the city. Although small and out of international exposure, each of them have revenue in terms of thousands of US dollars every month! Most of this income is undocumented as almost all of them are non-registered and running thorough personal bank accounts of owners. Fair enough for them but they also need mentors and proper subsidized office space to gain exposure and growth!

– Local ICT industry also include large call centers which work for local companies as well for companies which are established abroad in UK and USA and call centres always have staff in multiple of hundreds.

In such situation ASTP being iconic automatically becomes a hub, it has 17 floors, 3 gone for shops, 14 remain – 5 of which are already gone to Punjab Government and remaining floors come to a grand total of 9! 3 floors were for incubator offices (8th, 9th and 10th) and office size range in these floors is from 211 sq. ft. to 900 sq. ft. Now the actual situation on the ground is:

  • 4th and 5th floor gone to LDA (Lahore Development Authority) and Punjab Police for their IT related projects
  • Reportedly 9th floor (which is originally for incubator offices) is taken by Chief Minister Punjab himself for his personal secretariat
  • 11th floor is taken by PITB (Punjab Information Technology Board)
  • 10th floor was originally designed for incubator offices as well according to original prospectus of ASTP (formerly LTP) but marketing staff don’t show it any more to small companies so odds are that it has been rented out as a whole floor to a large company
  • 1 floor in a technology focused building is gone to Danish Technology University (this idea can only come in the mind of Mian Shehbaz Sharif – CM Punjab)

In this situation, out of 17 original and 14 office floors, 9 are available to local ICT industry for which this building has originally been constructed. Out of 3 floors for incubator offices, only 1 is in the market and PITB people are also thinking about it to rent as a whole floor to avoid rent collection fatigue (really?)

Potential of Cultural Shift

Still, this place has a lot of potential as a breeding ground of a lot of start-ups in the city as I can see a lot of buzz going around with-in, people networking with each other, events are already getting hosted in already functional auditorium!

The need of the hour is to promote a culture which shifts our industry’s focus from an outsourcing based to start-up based industry. Believe me with outsourcing we are going nowhere! A lot of companies here take projects from Internet or western agencies, do the hard-work and get some money at the end, while where we ship our hard work, our name hardly goes forward, we never get recognition of any kind! Secondly, yes developers get money for their work but they never socialise with each other, they never think about developing something new, to try their luck and bring in millions of dollars by selling their own products, the result is that most companies here are not focused on increasing their knowledge base (most developers and companies are happy working on WordPress and Joomla while world is making HTML5 based mobile apps), nor do they think about innovation!

With ASTP, we can create a whole eco-system for entrepreneurship! This building will serve as a networking hub automatically, investors and developers will come together and that will be the start of something bigger, the government just need to faciliate the change rather than doing things which it is not ment to do.

How other’s did it?

We all know Mountain View (famously known as Silicon Valley) as Mecca of ICT but what made it turn into a Mecca? US defense department! They first made a missile factory in the area, then HP was born and by late 50s they were making electronic components for defense factories in the area and they had more than 10,000 employees, that made everybody around that area an engineer! Then Standford University opened an innovation center spread over an area of 50 acres! that all happened in 40s, 50s and 60s and today we have a place known as Silicon Valley, the birth place of literally everything we know in the field of ICT. These factors were just catalysts, people automatically did the remaining job!

What our Government is doing?

Exactly what they are famous to do!

Instead of giving the projects to local companies, our government is pleading Turkish and other foreign companies to take billions of rupee and automate our systems. Do we really think that we can’t do those projects here? Take a chance, you will be surprised! Our ever energetic Chief Minister is offering 2 billion rupee to a turkish company to install automated traffic signal system in Lahore, did he have any idea what a change this money can bring to local industry if he let that money flow within Pakistan? But no, why we would give it locally, first if that would be awarded locally, the project will be scooped by some cousin of someone sitting in the government and that cousin would still be a student somewhere (exactly what happened in irrigation telemetery project, reportedly) and then a whole cycle of corruption will start and nothing will get delivered, that’s another debate but corruption is a controllable factor and only takes intention, right?

– Technology University in ASTP

As of what I will think about the scenario is that the CM must have seen the building first time and must have thought ‘uh, such a huge building, I should not let it remain empty and turn into a white elephant, let’s start a technology university on a floor here!’. A wonderful idea Sir but ‘a’ building is not the right place for it. Universities should be at open places with plenty of space for labs, playing grounds and class rooms. One floor of a technology building is not enough!

Secondly, it will destroy the working environment, students are mostly non-serious about facilities they would use while in business, facilities and time essentially translate into money! There will be a problem of security, students will use same elevators which would mean they can go on any floor and will put a strain on building facilities for which it is not designed.

There is a plus point that a university will encourage academia and industry collaboration but that is already happening, we recently went on a talent hunt to COMSATS (CIIT) which is 13 Km from Thokar Niaz Baig (literally 13 km out of the last corner of the city!) and we had no problem, we were there exactly out of the need and we were happy doing that! We knew we are going to meet students, idea of meeting students in our own elevator instead of someone who is working on a cool mobile app and need partner? – shrugs!

– CM himself on 9th floor?

What are you doing there Sir? We will be most happy with the thought that our CM has his own office in the building and he sometimes come and sit with us. We will be happy because we will have a chance to interact with CM, give our input into the existing and new technology projects and maybe if the presence of CM can become catalyst in joining hands with foreign governments! (Pay attention: I am talking about taking projects and doing them here rather than pleading other governments to do our projects!)

But what a CM would be doing on a whole floor? Sir, there are more than 500 small companies in this city, they all need to grow, they all need to become likes of Apple and Microsoft and they can! Instead of taking up their space, you should be providing them space! We don’t need your 200 useless secretariat employees sitting with us, instead we will be happy sitting with 200 innovators who can bring real change.

Continues CM presence will also bring in security challenges for the businesses inside the building, if CM should come, it should be granted a low-key event status and his presence should not hinder business activity.


I will conclude this blog by congratulating previous and current Punjab Government to construct a hub for the industry at a right place and with right facilities and I will hope that now on the operational side Punjab Government will also show the same spirit and will prove itself a catalyst in creating a knowledge eco-system to encourage entrepreneurship and bring value to the country rather than creating obstacles in the process!



Moving into Arfa Software Technology Park Lahore

Arfa Software Technology Park (formerly known as Lahore Technology Park) is one of the most iconic buildings in Lahore. You can’t help but noticing it when you first go towards Model Town or on Ferozpur Road towards Qasur after Kalma Chowk. Tall, Sleek, Hi-Tech look grabs your attention and you can’t stop yourself from asking ‘oh, what’s that?’. Well that was my response when I came to Pakistan last year in January after spending some good years abroad, I was completely unaware of this development but this came just forward when I was looking to establish a development office in Lahore.

Arfa Software Technology Park

Arfa Software Technology Park, Lahore

A little search on the web followed – found PITB site and it was written that construction will be complete by April 2010 after delaying for an year, well, that was already January 2011 and even probably due to delays PITB (Punjab Information Technology Board) staff was fed up to update their website (well, what else you do PITB?).

I immediately decided to have an office there and as from the look of building it seemed that outer structure is complete and they may take 6 months or so to finish any interiors work, we took a temporary office in a residential building (as is the norm in Pakistan for software houses) and started from there. I kept on calling PITB but they never had any clue when technology park will be complete, finally I found a reference in PITB and went to visit the site, on that day I got to know for the first time that it has been started, an advertisement was placed in national newspapers that weekend and building is ready to move-in, the marketing staff (they outsourced marketing to some company known as SFA) was eager to get bookings while they even didn’t had a clue when inauguration will be done and what are the per square foot rates or what will be the cost of electricity. That was November, 2011! I went there another 2 times and still the marketing office had no clue what was happening and that was because PITB being a government run organization (and because of the fact that their salaries are secured even if they work or not) was not clear about anything.

Why I liked Arfa Software Technology Park? 

Actual Image: Data Centre in Arfa Software Technology Park

Actual Image: Data Centre in Arfa Software Technology Park

– Purpose built floors: you want to have your own LAN – just pull out a tile, get your cable under the floor and ceil the tile again.
– Back-up electricity: Technology park building has 3 power sources, WAPDA and a backup generator and then a backup generator again. Building has double sourced connections for WAPDA supply as well, ensuring 80% less electricity outage!
– Fibre Optic cable until the office with in-house NOC for broadband suppliers!
– Plenty of parking space for both motor-cycles and cars, we are getting 1 car space for free with 345 square foot office space, motor-cycles are free anyway unconditional!
– In-house data center, so suppose we are going to demo something tomorrow and we need our own servers for that, you got a data-center just in your building!
– Auditorium and seminar rooms

What I don’t like about Arfa Software Technology Park?

–  There could have been small meeting rooms in the building, even if you have occupied a whole floor, it’s not necessary that would like to call every client or prospective employee inside the development office!
– A large hall to hold hackathon’s or such events!
– Food hall, well I know there are some ‘Food shops’ on 3rd level and marketing people are pushing out the likes of KFC, McDonalds etc. to open up franchises there but really if you can have a simple large canteen where anyone could go and have a simple lunch everyday – that would have been wonderful!

Top questions I asked every time and had to push for answers!

– What is the rate in per square foot on level 8 or 9? (A: Finally, it’s Rs. 110/sq ft.)
– What will be the electricity unit charge? (A: Standard WAPDA commercial unit)
– What will be backup electricity (generator) unit charge?  (No answer still)
– How I can get Internet connection in my office and what will the charge? (A: You can request any supplier, PTCL and Transworld are already in there and you can deal with them directly OR ASTP itself also provides Internet, details of which are unknown!)

And then we got to know an amazing thing, while doing the agreement, we came to know that we are only allowed to operate for 10 hours a day in the building and if we want to go beyond that, we will have to pay extra (which ranges from 26 paisa/sq ft to some figure far greater than that – but this rate has not been finalized yet!)
My Response: C’mon! are you kidding me? You have made a technology park, you are only allowing technology companies and call centers to step-in and you don’t even know how we work? Mostly it’s 24 hours! Software houses always have late sittings, a 8 or 10 hour day is a dream for most developers then call centers work round the clock, it’s support they give and even if they don’t work round-the-clock, most of them work for clients in UK or USA, they can’t take an office which is open from 0800 to 1700 PST! We were told about this conditon by marketing staff downstairs and I never believed my ears on what I am listening to so we requested them to have a word with PITB staff which are already enjoying 11th floor in ASTP. After speaking to one of their managers, we came to know building is running on BMS (Building Management System) and HVAC plant will be running for 24 hours anyway even if somebody uses it or not – and people will be paying for electricity getting used in their offices, guards will still be in place for their security duty – why this extra charge and ridiculous timings then? He, himself had no clue and told us that they are still thinking about that. That was a month ago and now when we were sent an agreement copy to create an agreement like that by ourselves and sign and send it back, this condition was still written that we agree to use building for 10 hours a day and will pay extra charge for over-usage. How wonderful!
This month (March, 2012) we applied for an office at 8th floor which is reserved for incubator offices and our application was approved, then we were asked to create an agreement document by ourselves and send them to PITB for approval, that’s been done and a cheque for initial payment is under process, when we will get possession – nobody knows still!

Insider Reports and Rumours:

– Incubator offices were scooped quite fast – even companies like Teradata are taking full floors, judging by the amount of IT companies in Lahore alone and their work staff strength – 14  office floors are still very less!
– Chief Minister has acquired whole of 9th floor – God knows for what and that’s in a technology building! What a CM secretariat will do there?
– And this is announced that CM is opening a Danish University in the building, well, can you open a university in ‘a’ building? Will that not damage working environment? I will write a separate blog about it.

I will leave this blog here, just take it for your information, ASTP is a very nice and well equipped building but people running it are obviously from Punjab Government so you know the likely state of it’s operations. Next, I will blog about a cultural shift which such a central hub of IT can bring to Lahore in specific and Pakistan in general.

Any comments or if you want to know anything from my experiences, just use the space below!


Tutorial: iOS Twitter app in 60 seconds using MoSync and Sencha Touch

Assumption for this video tutorial is that viewer don’t know Sencha Touch and MoSync at all, that’s why it is a bit longer than 60 seconds :;)

Introducing MoSync – SDK for Cross Platform Mobile App Development
MoSync is a cross platform mobile application development SDK which allows you to write cross platform apps for as many as 6 different platforms including iOS, Android and Windows Phone 7. Developers can develop their native UI web apps using HTML5 or native UI apps using C++. You can find more information about MoSync on http://www.mosync.com

Introducing Sencha Touch – JavaScript Framework for Mobile Devices

Sencha Touch is a JavaScript framework to write HTML5 based web applications targeted for touch based devices. It is specially designed to support touch based devices. Sencha Touch is from the same people who are behind ExtJs and Sencha Touch 2.0 is largely based on ExtJs codebase. You can find more information about Sencha Touch on www.sencha.com

Let’s get to work!

First step is to download MoSync IDE from www.mosync.com. You can download MoSync Mobile SDK or MoSync Reload which is specially written for HTML5 apps. I have used MoSync 3.0 Mac OSX version for this video tutorial.

The second step would be to have latest release of Sencha Touch with you, at the moment Version 1.1.1 is latest while version 2 is in developer preview only. You will need to give your email address to download free commercial version which I have already downloaded and unzipped on to my machine.

Let’s create our twitter client app. Open MoSync -> go to New Project -> Choose MoSync Project -> Choose HTML5 Project -> Choose HTML5 WebUI Project and then click Finish.
As you can see we have a HTML5 project ready for us now, it’s based on a template, so even if we don’t do anything and run it straight away on the iOS simulator, it will work for us!

A tip for you here will be that beside that you don’t need to configure anything on MoSync to run HTML5 apps, it come bundled with iOS simulator but you still need to have XCode installed on your machine to get it working, XCode is already installed on my MacBook at it’s default location and we can start using it straight away.

Now, back to our twitter client app, when you download Sencha Touch 1.1.1 and unzip the folder, you get examples folder in it, just open the examples folder, find twitter folder in it, copy it’s contents, go back to MoSync, delete all files from Local Folder and then paste the twitter folder contents in it. Then copy sencha-touch-debug.js from sencha touch folder and copy it also in Local files folder in MoSync. Then open index.html and change the path for sencha-touch.js file accordingly.

Now start you simulator again targeting iPad (because twitter example is not supporting iPhone resolution) and hey! you have your twitter client ready to go!
That is that easy! (I know this is cheeky)

Next time I will come back with a tutorial to target the same app to work on Windows Phone 7 and Android platforms.

Till then see ya!

Tutorial: Creating an Ajax based form using Zend Framework and YUI

Many of you would already know that Dojo is JavaScript framework of the choice for Zend Framework. However, Zend framework itself is very loosely coupled that you can use whatever JavaScript framework you are comfortable in. As part of my previous project we were already using YUI, so it was the best idea that while Zend Framework was our choice for our next project, we should stick to the JavaScript framework in which we already have developed our expertise i.e. YUI. As part of developing an Ajax based form, it takes a bit of time to take your head around but it works exactly as the JavaScript should work with PHP i.e. unobtrusive way. The deal is simple, the whole point of using a MVC architecture is that, you have different layers of presentation, controlling and business logic, that makes your code easier to maintain and develop upon, same should be the case of JavaScript you will be using in your application. Just a note that I am using Zend Framework 1.10 for this mini-tutorial.

Let’s get to work!

Say you have a form in your forms directory which extends Zend_Form class:

<?php class Forms_Product_Values extends Zend_Form { public function init() { // Set the method for the display form to POST $this->setMethod('post'); $this->addElement('text','my_timestamp',array( 'filters'=>array('StringTrim'), 'required'=>true, 'label'=>'Time Stamp' )); $this->addElement('text','my_value',array( 'filters'=>array('StringTrim'), 'required'=>true, 'label'=>'Currency Value' )); // Add the submit button $this->addElement('button', 'values', array( 'ignore' => true, 'label' => 'Modify', )); } } ?>
In here, note the last element, button, normally if it is a non Ajax based form, the element type will be the submit but as we do not want the form to submit itself straight away, we would just like to create a button element and give it a name, in this case ‘values’, same as controller name, I will explain this later that why I have used this specific name in our tutorial.
Next you will create a corresponding controller action obviously to handle whatever you want to do with your form input:
public function valuesAction(){ $form = new Forms_Product_Values(); $request = $this->getRequest(); // Check to see if this action has been POST'ed to. if ($this->getRequest()->isPost()) { // Now check to see if the form submitted exists, and // if the values passed in are valid for this form. if ($form->isValid($request->getPost())) { //do whatever you want to do } } $this->view->form = $form; // disable layouts for this action: $this->_helper->layout->disableLayout();
and not values.phtml which will act as a view for our controller action:
OK, up to here it was simple, straight form without submit button in the form, now we need YUI to act here. You can either create a separate JS file (always recommended) or just paste your JavaScript code in the values.phtml (your view file) which is not recommended however, I am doing that just for demonstration purpose of this tutorial!
Here is you updated values.phtml:

<!-- Combo-handled YUI JS files: -->
<script type="text/javascript" src="http://yui.yahooapis.com/combo?2.8.1/build/yahoo-dom-event/yahoo-dom-event.js&2.8.1/build/connection/connection-min.js&2.8.1/build/selector/selector-min.js"></script>
<script type="text/javascript">
function fnCallback(e) {
sUrl = e.currentTarget.id; //controller name is the same as button name;
var nodes = YAHOO.util.Selector.query('input');
//prepare the data in query string format var data = ""; for (var i = 0; i< nodes.length; i++) { data += nodes[i].name+"="+nodes[i].value; if(i != nodes.length-1){ data += "&"; } }
var div = document.getElementById("responseDiv");
var handleSuccess = function(o) { //upon successful response we embed the response text into responseDiv on our HTML page div.innerHTML = o.responseText; YAHOO.util.Event.addListener("submitButton", "click", fnCallback); }; var handleFailure = function(o){ //if the request if failed, we need to log the event if(o.responseText !== undefined){ div.innerHTML = "Failed request to the server. Please try again."; } }; var handleEvent = { start:function(eventType, args){ }}; var callback = { //on start call back calls the handle event which starts showing ajax loader image customevents:{ onStart:handleEvent.start }, success:handleSuccess, //parameter to define which function to use on success failure:handleFailure, //parameter to define which function to use on failure timeout:1500 //timeout is 1500ms, can be extended from here }; var request = YAHOO.util.Connect.asyncRequest('POST', sUrl, callback, data); } function init(){ YAHOO.util.Event.addListener("values", "click", fnCallback); } YAHOO.util.Event.onDOMReady(init);
<div id="responseDiv">

See, no rocket science, however, couple of things to note, I am using a different approach here to remember controller name, I have assigned the same name to the button as the controller i.e. ‘values’, on click event the listener fires fnCallback function and then I read what is the id of the button, hence I know which controller is this and that is all I need as sUrl (the URL which I need to call, you may also need to concatinate “../../”+e.currentTarget.id),  another approach you can use is to echo the controller name in a hidden span or div in the view and then just read it from the JavaScript on click or if you can come up with any other approach, kindly post in comments of this tutorial for others to use.

Then is the YAHOO.util.Selector.query(‘input’), the beauty of YUI become handy here, as in this form I only have input elements I want to read, however, if you want to read say for example all the select and textarea elements, it is simple, just use this YAHOO.util.Selector.query(‘input’, ‘select’, ‘textarea’), now you know how to harvest your inputs from your form, you pull that on into the data variable and make the normal Ajax request through connection manager utility of YUI. The only bit remains here is, because your controller action is same, when you will send a request to it, your whole form will regenerate itself (which is intentional as in the controller I am actually making a database call and I want to show that whatever user has modified is actually in the database now) so you will loose the listener which you attached earlier to the button, you have to add it again on receiving the response, however, in this example, I have hard-coded it, you may want to send it dynamically with function call so that your function become totally dynamic and you could use same with all of your forms, I leave that upto you!

Happy Coding!

YUI Button: Mimicking the native Select dropdown to avoid IE width problem

This is the 5th installment in YUI series. This installment uses YUI button widget and YUI keylistener utility. Although this post and example mimics the default SELECT element behaviour and look but you should also consider the JavaScript execution overhead this will cause.

Microsoft in all it’s glory continued to develop it’s own web standards, avoiding to support any open industry standards but then as technology progressed, word spread, people got knowledge and resources, open-source alternatives started to come into the market which now threatens the very existence of Microsoft itself. Yes, I am talking about the browsers at this moment, what Firefox and Google Chrome has done against a browser which comes pre-installed with an operating system which most of the people around the world use, yes the mighty IE (Internet Explorer).

As being a web-developer, you most probably would know the pain of working with IE. Although it has the developer tools now which makes the life a bit easier but what about it’s own implementation of DOM which is the only implementation and for this browser only,  a developer always feel forced to insert conditions in his/her code just so the code can work on IE as well. Anyway, this is something we all know about and can’t do anything until Microsoft thinks of something else. Let’s get to the business!

The problem with IE Select dropdown

IE Select dropdown width problem

If you are a web developer and you ever worked with a select dropdowns in your projects, you know this problem very well. IE by default don’t adjust it’s drop down panel according to the width of the longest text size. There are already work-arounds available and couple of them are based on YUI itself but they don’t mimick the exact look and feel of our old select dropdown list. I wanted the exact same look and  functionality of native SELECT element. I will list the work-arounds I founds:

Why a new fix?

Good question! The first fix I told you here, involves animation, when you get your mouse on the select element, it will animate itself to with of longest text option element, doesn’t look good to me as I think normal web user do not expect that to happen!

The second fix, had two major problems:

  • Scrollbars, my lists were very long as you will see in the example. By default YUI menu button’s scrollbars appear at the top and the bottom, if you increase the scroll rate for faster scroll, not very user friendly.
  • It didn’t had the important feature of selecting the options through keypress, I mean if you press B in normal select dropdown list, it will take you to the first item which is starting with B.

The fix itself!

Ok Ok, I think I am talking too much and few of my fellows will be in a hurry to get the code, copy paste it and get it done! Well, alright, the example is here:

Example: Work-around for fixed-width SELECT element

Explanation – The CSS

In fact I have modified the official YUI2 example.
First we need the same look as traditional select menu dropdown has. However if you want to make it more pretty, the CSS is here, do whatever you like to do, maybe using default arrow image of YUI is a better idea.

So, for the CSS, just as we override the default CSS rules of YUI skin sam:

.yui-skin-sam .yui-menu-button button {
    background-image: url("http://ciitronian.com/examples/images/select_arrow.PNG");
    outline: none;
    	font-size: 0.8em;
    	width: 15.2em;
    	background-color: #F8F8F8;
    	cursor: default;
    	line-height: 1.3em;
    	min-height: 1.45em;
	.yui-skin-sam .yuimenuitemlabel:visited  {

	.yui-skin-sam .yuimenuitemlabel  {
	padding:0 20px 0 0;

	.yui-skin-sam .yuimenuitemlabel:hover  {
	background-color: #111166;
	color: #ffffff;

and a bit of tweak to YUI’s official example em class of button to make it look like a classic one

        /*  Restrict the width of the label to 10em. */
        width: 10em;

Our YUI menu button has got the classic look of SELECT element. Now the bit which I refer to as a nasty tweak, YUI menu button comes with it’s own scrollbars and as I mentioned earlier, if  you have a very long dropdown list, like a list of all countries in the world, the scrollbars functionality is not very useful. YUI gives you the flexibility to disable the scrollbars but I actually needed a vertical scrollbar so, what I did, I made the YUI scrollbars hidden!

Here’s what I did:

/*hide the YUI scroll bars*/
.yui-skin-sam .yuimenu .topscrollbar,
.yui-skin-sam .yuimenu .bottomscrollbar {
    height: 0px;

What it’s doing? Simply overriding the overriding the CSS property of height and setting it to 0. It hides the top and bottom scrollbars altogether. Next we need to turn the overflow to auto for yui menu body:

.yui-skin-sam .yuimenu .yui-menu-body-scrolled {
    overflow: auto;
    padding-right: 10px; /*to prevent horizontal scroll*/

If you just set overflow to auto, there will be just about a couple of pixels which will get over-flowed horizontally as well, to make it right, the padding property is there.  The padding-right property in div.yuimenu .bd is also there because IE8 was not getting right even if after the above rule.

Explanation – The JavaScript Code

The other JS code is almost the same as you will find in the official example but as mentioned earlier there were only two problems, the scrollbar, which we have already fixed through CSS, now the sorting or whatever you call it that when you click for a character, the first of it’s appearance should get selected automatically. So, all we need is basically a YUI keylistener with a correct scope and then we need to have a functionality which gets all the menu items text in an array, traverse the first character of each text element and then if matched, scroll to it and select it with the correct focus.

The keylistener code:

var kl = new YAHOO.util.KeyListener("select-1-container", { keys:keyArr },
			   { fn:labelCharCode,
				 correctScope:true } );

The keylistener code select-1-container as first argument to give it correct scope. Notice the loops before this code in the source code of example, 65-90 are the keyboard character codes for A-Z characters and 48 to 57 are 0-9 characters. Next, keylistener calls the labelCharCode function with the keypressed event type, and arg[0] has the character which got pressed.

Now, the YUI Menu has a useful method of getting all items in a menu, as you see in the source code, I have used it to get the menu items:

var MenuItems = oMenuButton1.getMenu().getItems();

Now, in the labelCharCode, we have got the character which user has pressed, we need to match it with the first character of menu item. We access the text property of all menu items in a loop, slice the first character, match it in a if else block, if matched, simple old window.location takes us to the id of that menu item and then we fire the focus event for that menu item.

for (var i = 0; i < MenuItems.length; i++) {
			var firstChar = MenuItems[i].cfg.getProperty('text').slice(0,1);
			if(firstChar === Character){
				window.location = "#"+MenuItems[i].id;

That’s it your SELECT dropdown element is ready which will work in all browsers and will adjust itself with the width of longest item in the menu!

Things which are still nagging me

The above code works as you may see in the example (I only tested that in IE8, Firefox 3.6 and Chrome 5), however I personally don’t like the concept of matching in a loop and slicing. I tried using YUI DataSource for this purpose but what I have seen in the YUI source code is that, it takes LocalDataSource array as it is and then apply matching on it, probably DataSource is more useful for remote data. However, I left it there after I tried seeing the code of AutoComplete widget and DataSource together, maybe I need to give it a bit more investigation. However, I dislike the current approach of this example because of processing involved. If you have a better understanding and know a better way of doing this, kindly embed the example or simply let me know, that will make this fix better!

Happy Coding!

Get String Length Tool

Just a bit of background, I was working on live data coming through from Java applets into Javascript, there were strings which I had to match, the conditions were like if (thisID === “blahblahblah”) and there were a lot of them, I had to match strings and then do my stuff, the strings were all different, I had to cut each string into sub-strings because there was a variable portion of every string which I didn’t wanted to match. The result you can imagine is that I was sitting there, counting each string character by character and then putting a condition on it. Got the idea of this tool then (obviously I am lazy when it comes to code), just input your string, get the length, put it as a parameter for the Javascript equivalent of PHP substr or maybe use slice() method of JS and move on! Here is tool:

When I actually searched for such a simple tool online to find a string length straight away (like I have seen a simple tool the other day to convert px values in em for CSS), couldn’t find any (maybe there are but I couldn’t find them). However, when you will search you will get lots of functions in every language (C, C++, Java, Javascript etc.) to do that but what if I only want string length and don’t want to write a line, execute it, know the length, erase it and then continue? Well, here is one, it helped me, it may help someone else too!

Happy Coding!

Get Adobe Flash player