Showing posts with label javascript. Show all posts

4 jQuery Cross-Domain AJAX Request methods

The web has changed and with it the way we develop websites. Today, the web is becoming a place where we develop web apps, rather than websites. We use third party API's to create our next mashups. So knowing how to make a cross-site AJAX request or requests that do not comply with the same origin policy is a must. In this article, you will learn 4 cross-site AJAX request methods (plus 4 bonus legacy methods and links to jQuery plugins).

This methods will be handy to overcome Same origin policy as well. Browsers will throw an error if you are making AJAX request to the same domain but with different protocol (to https from http), use different port (http://same-domain.com:81) or subdomain.

This article reviews the following 4 methods and discusses their advantages & disadvantages. Also, summarise cases when they are better used.

Here is the list of methods:

  1. CORS (Cross-Origin Resource Sharing)
  2. JSONP
  3. window.postMessage
  4. Setting up a local proxy
  5. + 4 bonus legacy methods (document.domain, window.name, iframe, flash)
  6. + list of JavaScript libraries and jQuery plugins for making XSS requests.

Before we dive into the method details, let's cover most common cases:

  • Firstly, if you are trying to read data that is available as RSS feed, you are better off with universal RSS to JSON converter powered by Google.
  • Secondly, if you are accessing data from some popular website API, it's more likely they support JSONP as well. See their documentation.

JSONP is a cross browser method that does not rely on any browser hacks. It is supported by all browsers and many javascript libraries provide methods that make JSONP request seamless.

5 notes on JavaScript Arrays

In this post, we will go through some of the features of JavaScript's Arrays. I thought this would be a good place to come back time to time and refresh my memory about special cases and notes I've collected on Arrays in Javascript. Without futher ado, 5 notes on JavaScript Arrays.

1. Arrays are Objects in JavaScript

Arrays are Objects in JavaScript. Let me repeat it one more time: "Arrays are Objects". Understanding this helped me simplify my conceptual understanding of the language. Instead of rembembering different special cases and syntax for Arrays and Objects, now, we just need to remember rules to work with Objects alone.

Now, let me elaborate on it more. Array index keys are just property names of an object. Since, a property name can not start with a number, we have to use alternative [''] property access notation just like we would with any other object. So, there is nothing special about Array keys. They are just object property names that are integers.

var array = [1, 2, 'three', 4, 5]; // or 'new Array()'

array.0    // SyntaxError: Unexpected number
array[0]   // 1
array[2]   // 'three'

2. Arrays keys are String

Internaly javascript engine keeps array keys as String values, because naming rules do not allow properties starting with a numeral. When you access array values with an integer, javascript engine casts it into string. So this means that JavaScript Arrays are not breaking any of the naming rules defined by the language. Property names are not starting with an integer and they are stored as strings. Let's see some examples.

var array = [1, 2, 'three', 4, 5];

array[1]                 // 2
array['1']               // 2 - Accessing with a string works just fine
array['3'] == array[3]   // 'true'
array['03'] == array[3]  // 'false' - because array['03'] != array['3']
array['03'] == array[03] // 'false'

In the example above: array['03'] is not equal to array[03], because numerical value 03 furst turned into 3 and only then casted into string. So the end equation would become array['03'] == array[3] and that equals to false.

3. Arrays keys must be positive integers

Just like in any other programming language, JavaScript imposes a rule that array keys can only be positive integers. You can still treat them as if they were objects and set values to any keys. Javascript engine would simply ignore them.

var array = [1, 2, 'three', 4, 5];

array['06'] = 7;
array['str'] = 'some value';
array.prop = 'another value';

console.log( array );  // [1, 2, 'three', 4, 5]

array['6'] = 7;
console.log( array );  // [1, 2, 'three', 4, 5, undefined, 7]

4. Use the literals notation [] instead of new Array()

The new Array() is ambiguous in how it deals with its parameters, so it is better to always use alternative [] notation to define arrays. The literals are more readable and shorter as well.

You can read more about this behaviour here.

// Prefered method
var array = [1, 2, 'three', 4, 5];

// Not so prefered
var array2 = new Array(5);

5. Loop through arrays with for() loop

As we said previously, arrays are objects. So you can loop through them using for in loop. But it is not recommended. Because, for in loops through all the properties that are in the prototype chain and you will have to use .hasOwnProperty() check. This means only 2 things:

  1. bloated and hard to read code;
  2. performance penalty.
var array = [];
a[1000] = 'some value';

for (key in array) {
  if (a.hasOwnProperty(key)) {
    array[key]; // 'some value'
  }
}

// Recommended
for(var index = 0, l = array.length; index < l; index++) {
  array[index]; // 'some value'
}

// OR if you have ECMAScript5 support
array.forEach(function(value) {
    value; 'some value'
});

6. Bonus notes

Since arrays are objects of an Array class. We can check if an object is an array.

function is(type, obj) {
  var clas = Object.prototype.toString.call(obj).slice(8, -1);
  return obj !== undefined && obj !== null && clas === type;
}

is('Array', [1, 2, 3]); // true

If you have jQuery included on your page, use either $.type() or $.isArray().

var array = [1, 2, 3];

$.type(array);     // 'array' - string
$.isArray(array);  //  true   - boolean

jQuery Form Reset

This post shows you how to reset HTML form using jQuery. Also, in the notes section below, you will find a list of special cases and things to keep in mind while resetting form.

Please note that this post discusses 2 cases of resetting a form:

  1. Resetting form values to their default/initial values (similar to clicking on form "reset" button);
  2. Clearing form values (clearing form values, no matter what their default values were).

1. Reset form values

Probably, you already tried to use $("your-form").reset() method and got the following error:

TypeError: $(...).reset is not a function

That is because jQuery does not have .reset() method. However, DOM form elements have .reset() method. It resets form values to their initial values. In other words, if we had an input field with value="set on server" attribute set, and then, user typed in some other random text. On reset() that input fields value would be reset to "set on server" again and not to " ".

That out of the way, here is how you can reset a form using "pure" JavaScript.

// JavaScript only syntax
getElementById("your-form-id").reset();

// Using jQuery selectors
$('.my-form-class')[0].reset();

Here is a better way to reset your form with jQuery. Simply trigger a reset event on your form.

// jQuery syntax
$('.my-form-class').trigger("reset");

Notes on method 1

Things to remember:

  • Form values are reset to their initial/default values. They are not cleared/emptied.
  • Hidden values are not reset. If you have changed hidden input field values, you will have to reset them manually. You can do it by subscribing to reset event.

2. Clear form

The difference between clearing and resetting a form is that in clearing form values we clear all form fields. In other words, we will not reset them to their default values, but will replace their content with "" (empty space).

In other to do that, we will have to go through each field in the form and set its' value to "".

UPDATE: Replaced the code with the one from learningjquery.com. It creates a clearForm jQuery plugin.

$.fn.clearForm = function() {
  return this.each(function() {
    var type = this.type, tag = this.tagName.toLowerCase();
    if (tag == 'form')
      return $(':input',this).clearForm();
    if (type == 'text' || type == 'password' || tag == 'textarea')
      this.value = '';
    else if (type == 'checkbox' || type == 'radio')
      this.checked = false;
    else if (tag == 'select')
      this.selectedIndex = -1;
  });
};

Here is how to use clearForm jQuery plugin:

// Call it on your <form>
$('form').clearForm();

Notes on method 2

Put the plugin definition code into jquery.clearform.js file and include it your project.

JavaScript: typeof & when should you use it?

In this post, we will talk about JavaScript’s typeof operator. We will start with its’ purpose. Then discuss its’ flaws and finally see when should you use it.

typeof's usage doesn’t happen to match its’ initial purpose.

What is typeof?

The typeof operator is used to identify the type of an object. It always returns a String value, so you should always compare return value to a string.

// Examples
typeof 37;        // "number";
typeof true;      // "boolean"
typeof undefined; // "undefined"
typeof {};        // "object"

// Call with parentheses
typeof(37);        // "number";

As you can see above, there are 2 ways to call the method. typeof is an operand and not a function, that is why, the second method is actually not a function call. Operation in parentheses are evaluated and then passed to typeof.

So far, so good, we know its’ purpose. Now let’s see its’ flaws.

Flaws and caveats

I’ll just say it: typeof is one of the biggest flaws in JavaScript. It had only one job, to return the type of an object. But let’s see the table below (source):

Value               Class      Type
-------------------------------------
"foo"               String     string
new String("foo")   String     object
1.2                 Number     number
new Number(1.2)     Number     object
true                Boolean    boolean
new Boolean(true)   Boolean    object
new Date()          Date       object
new Error()         Error      object
[1,2,3]             Array      object
new Array(1, 2, 3)  Array      object
new Function("")    Function   function
/abc/g              RegExp     object   (function in Nitro/V8)
new RegExp("meow")  RegExp     object   (function in Nitro/V8)
{}                  Object     object
new Object()        Object     object
alert               Function   function (object in IE 6, 7, 8)
null                null       object   (in future ECMAScript versions)

"Type" column lists the typeof‘s return values and "Class" column shows the actual class of the operand.

As you can see, in most of the case you end up with object string instead of the actual class name. A workaround for getting the class of an object is to use Object.prototype.toString method. Here is how:

Object.prototype.toString.call("foo")      // [object string]
Object.prototype.toString.call(new String) // [object string]

As you can see, this is not the ideal return value. Here is a JavaScript function that would help make your code more readable (source):

function is(type, obj) {
    var clas = Object.prototype.toString.call(obj).slice(8, -1);
    return obj !== undefined && obj !== null && clas === type;
}

is('String', 'test');             // true
is('String', new String('test')); // true

If you want to check the type of an object, use Object.prototype.toString method instead of typeof operator. This would make your code behave as expected.

NOTE:
ECMAScript 5 changes the Object.prototype.toString method’s return values for null and undefined from object to null and undefined.

When should you use typeof?

typeof is good for checking if variables are undefined. If you make use of an undefined variable in your code, you will get a ReferenceError. Using typeof will not cause your code to throw an error.

if( typeof foo !== "undefined") {
    // defined
}else {
    // undefined
}

To conclude, unless you are checking whether a variable is defined or not, you should avoid using typeof.

ReferenceError: $ is not defined

This post will explain the root cause of the Reference Error in your browser’s console log. Also, list most common cases with examples and solutions. Without any further ado, lets see what a reference error is.

This is a common JavaScript error that says: you are trying to access a variable or call a function that has not been defined yet.

Reproducing the error:

// VARIABLES
foo; // ReferenceError: foo is not defined
var foo;
foo; // No more errors

// FUNCTIONS
bar(); // ReferenceError: bar is not defined
bar = function(){};
bar() // No errors

By now, you might have guessed the reason behind the "ReferenceError: $ is not defined" error. It is exactly the same as the bar() example above, but the name of the function is $ instead of bar this time. So, what it means is that we are trying to access the method $ that has not been defined yet. When is it possible? Only when jquery.js file has not been loaded successfully before we tried to call $().

Some common cases when error may occur

  1. Problem: Path to your jquery.js file is broken and it can not be found (Error 404).

    <script src="/wrong/path-to/jquery.min.js"></script>

    Solution: fix your path to jquery.js file. If your project is a public website, you better use Google hosted jQuery file.

    <script src="/correct/path-to/jquery.min.js"></script>
  2. Problem: jQuery plugin is included before jQuery file.

    <script src="/path-to/jquery.plugin.js"></script>
    <script src="/path-to/jquery.min.js"></script>

    Solution: Include jquery.js file before any jQuery plugin files.

    <script src="/path-to/jquery.min.js"></script>
    <script src="/path-to/jquery.plugin.js"></script>
  3. Problem: You are including jQuery file without the protocol in the URL and accessing the page from your local file system.

    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>

    Solution: Temporarily add HTTP protocol (http:// instead of //) in the URL while you are developing.

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
  4. Problem: jQuery file is included from the web, but you don't have an internet connection. It is a silly mistake, but you would be surprised how ofter it happens.

    <script src="http://www.example.com/js/jquery.min.js"></script>

    Solution: Include local jquery.js file copy or connect to the internet :)

    <script src="/js/jquery.min.js"></script>

If the above cases do not solve your case, try to figure out why jQuery is not loaded before the line where this error is thrown.

Bind jQuery events to tab or window close

This post shows you how to bind JavaScript functions that will fire when user navigates away from your page, closes browser or a tab. Browsers have native JavaScript events on window object: unload and beforeunload. beforeunload is a proprietary event introduced by Microsoft and supported by other browsers, but not all.

Please note, these events will be fired when user navigates away from the current page. This includes when user:

  • closes the browser or a tab;
  • clicks on any link (does not matter if it's to other domain or the current domain);
  • types any URL to the browser bar and leaves the page;
  • clicks browser's page reload, back, forward buttons.

NOTE
You must test your code, because the behavior of how browsers handle unload event has changed even in different versions of the browsers.

Catching browser/tab close event with JavaScript

Since unload is a native JavaScript event, we can get away without using jQuery at all.

window.onunload = function(){
    // do some clean up
    clearLocalStorage();
};

If you are using alert(), confirm() or making AJAX requests here, please see what browsers block them belove.

Subscribing to browser/tab close using jQuery

jQuery introduced $.unload() event shorthand in v1.0 and deprecated it in v1.8. $.unload() is a shorthand for .bind('unload', handler).

$(window).unload(function() {
    // Do some code clean up
});

How browsers handle alert(), confirm() and AJAX requests on unload event?

The document unload event was originally designed to let JavaScript to do some clean up. For example, clear or set cookies, but most of the time it is used to fire alert/confirm box or make an AJAX request to the server. This led to bad user experience and browsers started to block these methods in unload event.

Here is what each browser does:

  • Chromer/Safari (WebKit)
    • alert(), confirm() - blocked (confirm() returns false), AJAX request - not sent.
  • Firefox
    • alert(), confirm() - blocked (throws an internal NS_ERROR_NOT_AVAILABLE exception), AJAX requests - sent on page reload, but not on tab close.
  • IE9
    • alert(), confirm() - not blocked, AJAX requests - not sent.
  • Opera
    • alert(), confirm() - blocked, AJAX requests - not sent.

Browsers that have pop-up window blockers will block all window.open() function calls in unload event handler.

Learn QUnit in just 2 hours

This is not a catchy post title or usual marketing trick. 2 hours is actually how long it would take to learn QUnit for an average developer (provided you are familiar with JavaScript and web dev basics of course). Well, that's how long it took me to learn. I read the docs (very short and concise), read QUnit tests of some popular jQuery plugins, wrote some tests of my own, and all these got me to the point where I could answer QUnit related questions on StackOverflow.

First, I was planning to cover all the basics of QUnit in this article, but then I thought, getting the message out would yield more positive results. The message that learning everything (and I mean everything) about QUnit testing takes no more than couple of hours. I believe this would make a better impact on jQuery/JavaScript community as a whole. This article will outline the basics and guide you through the optimal learning process (with links to resources).

Let's get started

Learning QUnit at first might be overwhelming. But once you learn that its' API has only 14 methods (and some of them are just negation of others, e.g. equal() & notEqual()), the learning process gets more manageable and easy. Here is an overview of those 14 methods mentioned above:

  • 8 assertions (equal(), notEqual(), deepEqual(), notDeepEqual(), strictEqual(), notStrictEqual(), ok(), throws())
  • 3 assertion organisation methods, also known as test suites in other unit testing frameworks (module(), test(), asyncTest())
  • 3 helper methods to test async methods, such as AJAX, setTimeout(), callbacks, etc. (expect(), stop(), start())

This out of the way, we are ready to learn QUnit.

Here are 4 steps that will (1) introduce you to unit testing and QUnit, (2) cover all API methods, (3) show and discuss some common testing scenarios and (4) see how others are using it:

  1. Read an Introduction to unit testing. The article introduces the idea of unit testing and sets the stage to and introduces QUnit. - 20 min
  2. Go through those 14 methods we talked about above (assert, async assert, test). The API explanations are very short and to the point. - 30 min
  3. See some examples of testing javascript and jQuery code using QUnit in the cookbook. - 40 min
  4. Read and examine some tests on GitHub: - 30 min

Hopefully, you will spend the next 2 hours learning QUnit and your next jQuery plugin/JavaScript code will be covered by tests. Please, help to spread the word and share the link.

PS. In upcoming posts we will cover other testing frameworks such as Mocha and Jasmine (has syntax that resembles Ruby's rspec), object stubbing and mocking with Sinon.JS, and some alternatives to assertions with Chai. Also, to make coding more pleasant we'll cover CoffeeScript as well. So stay tuned: Like us on Facebook, follow on Twitter or subscribe to RSS.

The difference between == and === in jQuery/JavaScript

In this post I would like to explain the difference between double (==) and triple (===) equals in JavaScript/jQuery. A quick and short explanation is that == does type coercion (conversion) before checking for equality; and === does strict equation which requires values to have the same type as well.

Here is what it means:

0 == false     // true
0 === false    // false, because they have different types (int, bool)
1 == "1"       // true
1 === "1"      // false, because they have different types (int, string)
null == undefined // true
null === undefined // false

Detailed (longer) explanation

When you use == the javascript interpreter will convert one side of the comparison according to these rules:

  • When comparing a number and a string, the string is converted to a number value.
  • When comparing a boolean, the boolean is converted to 1 if it is true and +0 if it is false.
  • When object is compared with a number or a string, the object is converted to its’ default value (.valueOf(), .toString()). If these methods are missing a runtime error is thrown.
  • When comparing an object and another object, no type conversion is made. They are equal only if they refer the same object.

When you use === the javascript interpreter will not convert values to primitive types and make sure that the operands have the same value as well as the same type.

"foo" === "foo"  // true, both operands are of type String
new String("foo") === new String("foo")  // false, 2 Objects refer diff object instances

Detailed comparison information can be found on Mozilla Developer Network page. Here is the summary:

  • Two strings are strictly equal when they have the same sequence of characters, same length, and same characters in corresponding positions
  • Two numbers are strictly equal when they are numerically equal (have the same number value). NaN is not equal to anything, including NaN. Positive and negative zeros are equal to one another
  • Two Boolean operands are strictly equal if both are true or both are false
  • Two distinct objects are never equal for either strictly or abstract comparisons
  • An expression comparing Objects is only true if the operands reference the same Object
  • Null and Undefined Types are == (but not ===)

JavaScript to detect iPad visitors

This post gives you a short JavaScript function to detect your iPad users. Without any further ado, a javascript code to detect iPad users:

function isiPad(){
    return (navigator.platform.indexOf("iPad") != -1);
}

You can also detect browser version and some other stuff by parsing user agent string. Here is an iPad Safari’s user agent string for your reference:

Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safari/531.21.10

Recently a friend of mine got himself an iPad and I couldn’t not notice how his internet browsing device preferences are changing (PC & iPad). More and more people are using hand held devices namely iPad to browse the internet. So it’s about time to show your iPad visitors some love and display your website designed specifically for iPad.

Let’s see how to do this. There are two way:

  1. Redirect iPad visitors
  2. Apply different CSS file for iPad users

Most of the posts on the internet related to iPad user detection are suggesting and showing you how to redirect (including myself in my previous iPhone & iPod detection post). However, I would recommend the second option, applying different CSS file.

You can apply the same technique described in applying different styling for javascript enabled browser with CSS post and apply different CSS rules for iPad visitors.

Sidenote: If you decide to redirect iPad users rather than apply different CSS style rules, than I would recommend using server side detection and redirection. You can see an example PHP code by David Walsh.

iPhone / iPod detection using jQuery & JavaScript

In this post you will learn how to detect iPhone/iPod using javascript/jQuery, redirect your iPhone users to mobile version of your site using javascript and alternative and better way to redirect your visitors using server-side PHP code snippet.

The latest buzz around jQuery is upcoming jQuery mobile – support for mobile devices. Current jQuery core work fine on iPhone and iPod touch browsers and most of us have created a mobile version of our websites, developed or converted websites for others. Basically, jQuery is already being used on iPhone and iPod touch devices. Without any further ado…

Javascript code to detect iPhone and iPod browsers

// Return boolean TRUE/FALSE
function isiPhone(){
    return (
        (navigator.platform.indexOf("iPhone") != -1) ||
        (navigator.platform.indexOf("iPod") != -1)
    );
}

You might wonder why do we even need to detect if our website is ran on iPhone Safari or normal desktop Safar if jQuery works fine on both. Well, there are Safari specific CSS features that you might want to utilize and you need to know if the current browser is Safari, then you may also want to consider reducing resource consuming features like animations for iPhone version of your site.

Redirecting iPhone & iPod users

You may also use this script to redirect iPhone and iPod users to your website’s mobile version:

// Redirect iPhone/iPod visitors
function isiPhone(){
    return (
        (navigator.platform.indexOf("iPhone") != -1) ||
        (navigator.platform.indexOf("iPod") != -1)
    );
}
if(isiPhone()){
    window.location = "mob.example.com";
}

For example: if your website is www.example.com and you have a mobile version at mob.example.com, then put the following script to your www.example.com.

Redirect iPhone users using PHP

It is better to detect and redirect your iPhone users on the server-side. Here is a PHP code to redirect iPhone users:

// Redirect iPhone/iPod visitors
if(strpos($_SERVER['HTTP_USER_AGENT'], 'iPhone') ||
   strpos($_SERVER['HTTP_USER_AGENT'], 'iPod')){
      header("Location: http://mob.example.com");
}

User agent strings for your reference:

/*
User Agent String for iPhone
    Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420+ (KHTML, like Gecko)
    Version/3.0 Mobile/1A543a Safari/419.3
    
User Agent String for iPod Touch
    Mozilla/5.0 (iPod; U; CPU like Mac OS X; en) AppleWebKit/420.1 (KHTML, like Gecko)
    Version/3.0 Mobile/3A101a Safari/419.3
*/

As final words, I would like to remind you that sometimes your visitors would not like to be redirected to mobile versions of your websites. That’s why your mobile version should always include a link to your non-mobile website. The above scripts can be rewrote to check if user has chosen not to be redirected. Either set cookie or a URL parameter.

jQuery & Cookies (get/set/delete & a plugin)

In this post I would like to share javascript functions that will help you easily get, set, delete and basically manage your cookies. Also, link to jQuery Cookie plugin, it’s improved version with more functions and of course easy to read and short examples on how to use these functions.

I will try to keep this post short and will not explain what cookies are and how to eat them. There are plenty of articles covering it already.

Here are javascript functions by Peter-Paul Koch to getCookie(), setCookie() and deleteCookie():

function setCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}

function getCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

function deleteCookie(name) {
    setCookie(name,"",-1);
}
/*
  Changed function names from readCookie(), createCookie()
  and eraseCookie() to getCookie(), setCookie() and
  deleteCookie().
*/

Here is an example that shows you how to use those functions in your javascript to create, edit and delete your cookies:

// Create/write a cookie and store it for 1 day
setCookie('myCookie', 'myValue', 1);

// Get my cookie
getCookie('myCookie');

// Delete/erase my cookie
deleteCookie('myCookie');

These 3 javascript functions are all you need to manage your cookies, but if you want to do it in “jQuery style” than you can use jQuery Cookie plugin or it’s improved version.

Here is how to use jQuery Cookie plugin in your code:

// Setting a cookie
$.cookie('myCookie':'myValue');

// Creating cookie with all availabl options
$.cookie('myCookie2', 'myValue2', { expires: 7, path: '/', domain: 'example.com', secure: true });

// Get a cookie
$.cookie('myCookie');

// Delete a cookie
$.cookie('myCookie', null);
With an improved version of the plugin you can set and get multiple cookies in one call. The improved version of the jQuery Cookie pluin only adds few additional bytes. So it really worth it. 
// Set multiple cookies
$.cookie({ 'cookie1':'value1', 'cookie2':'value2' });

JavaScript / jQuery password generator

This month, October, is a National Cyber Security Awareness Month. The aim is to increase cyber and internet security awareness among surfers. Google and others are joining the move. So I thought I would write a post regarding internet security to add my 2 cents. In this post you will find JavaScript function that generates random passwords of any length as well as jQuery version.

JavaScript Password Generator

function password(length, special) {
  var iteration = 0;
  var password = "";
  var randomNumber;
  if(special == undefined){
      var special = false;
  }
  while(iteration < length){
    randomNumber = (Math.floor((Math.random() * 100)) % 94) + 33;
    if(!special){
      if ((randomNumber >=33) && (randomNumber <=47)) { continue; }
      if ((randomNumber >=58) && (randomNumber <=64)) { continue; }
      if ((randomNumber >=91) && (randomNumber <=96)) { continue; }
      if ((randomNumber >=123) && (randomNumber <=126)) { continue; }
    }
    iteration++;
    password += String.fromCharCode(randomNumber);
  }
  return password;
}

This function takes two parameters: integer value for password length and optional boolean value true if you want to include special characters in your generated passwords.

Examples of generated passwords

password(8);
// Outputs: Yrc7TxX3

password(12, true);
//Outputs: C}4_ege!P&#M

jQuery password generator

$.extend({ 
  password: function (length, special) {
    var iteration = 0;
    var password = "";
    var randomNumber;
    if(special == undefined){
        var special = false;
    }
    while(iteration < length){
        randomNumber = (Math.floor((Math.random() * 100)) % 94) + 33;
        if(!special){
            if ((randomNumber >=33) && (randomNumber <=47)) { continue; }
            if ((randomNumber >=58) && (randomNumber <=64)) { continue; }
            if ((randomNumber >=91) && (randomNumber <=96)) { continue; }
            if ((randomNumber >=123) && (randomNumber <=126)) { continue; }
        }
        iteration++;
        password += String.fromCharCode(randomNumber);
    }
    return password;
  }
});

// How to use
$.password(8);
$.password(12, true);

Host jQuery on Microsoft CDN servers

After Microsoft decided to ship and use jQuery library for its JavaScript needs in Visual Studio, hosting jQuery on Microsoft CDN servers is actually a logical and good decision. Yes, some of us might argue that Google already hosts jQuery, but Microsoft can not recommend to use its competitor’s services, can it?! :)

Anyway, intention of this post is not to discuss why Microsoft introduced its own jQuery hosted servers, bu to share links to Microsoft hosted jQuery library. Here we go:

jQuery 1.4.x
http://ajax.microsoft.com/ajax/jQuery/jquery-1.4.2.js
http://ajax.microsoft.com/ajax/jQuery/jquery-1.4.2.min.js
http://ajax.microsoft.com/ajax/jQuery/jquery-1.4.1-vsdoc.js

jQuery 1.3.2
http://ajax.Microsoft.com/ajax/jQuery/jquery-1.3.2.js
http://ajax.Microsoft.com/ajax/jQuery/jquery-1.3.2.min.js
http://ajax.Microsoft.com/ajax/jQuery/jquery-1.3.2-vsdoc.js
http://ajax.Microsoft.com/ajax/jQuery/jquery-1.3.2.min-vsdoc.js

Microsoft also host jQuery Validation and jQuery UI files.

Currently Microsoft AJAX CDN hosts only jQuery version 1.3.2, but they will add more releases in the future. To see a full list of the JavaScript libraries and their URLs that are already hosted on CDN cache go here: www.asp.net/ajax/cdn

Get URL parameters & values with jQuery

In this post, I would like to share a little jQuery code snippet that makes getting URL parameters and their values more convenient.

Recently, while working on one of my projects, I needed to read and get parameter values from URL string of the current page that was constructed and sent by PHP script. I came across this short and sweet JavaScript code snippet by Roshambo that does just that.

// Read a page's GET URL variables and return them as an associative array.
function getUrlVars()
{
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}

The function returns an array/object with your URL parameters and their values. For example, consider we have the following URL:

http://www.example.com/?me=myValue&name2=SomeOtherValue

Calling getUrlVars() function would return you the following array:

{
    "me"    : "myValue",
    "name2" : "SomeOtherValue"
}

To get a value of first parameter you would do this:

var first = getUrlVars()["me"];

// To get the second parameter
var second = getUrlVars()["name2"];

To make the script syntax to look more jQuery like syntax I rewrote it as an extension for jQuery:

$.extend({
  getUrlVars: function(){
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
      hash = hashes[i].split('=');
      vars.push(hash[0]);
      vars[hash[0]] = hash[1];
    }
    return vars;
  },
  getUrlVar: function(name){
    return $.getUrlVars()[name];
  }
});

Now, if you include the above code in your javascript file, you can get URL parameter values in the following way:

// Get object of URL parameters
var allVars = $.getUrlVars();

// Getting URL var by its nam
var byName = $.getUrlVar('name');

That’s it! You might also find the following jQuery related articles on this blogs interesting:

  1. Cross-domain AJAX querying with jQuery
  2. Javascript for() loop vs jQuery .each() performance comparison
  3. Create jQuery custom selectors with parameters
  4. JavaScript / jQuery password generator

QR Code (generator) plugin for jQuery & JavaScript

I recently came across a 2 dimensional barcode called QR Code. QR code’s are popular in Japan and they are mainly used there to quickly get to some website on their mobiles by simply taking a picture of the QR code. You may read more about QR codes on Wikipedia.

Here is an example of QR code for jQuery HowTo blog:

qrcode-jquery-howto

If you have a QR code reader on your mobile take a picture of it and it will open this website. Cool ha?!

Anyway, there are plenty of free online QR code generator sites, but no JavaScript and jQuery plugins/functions. So, I quickly searched for a free online QR code generator sites with “friendly” URL’s and put together a javascript and jQuery functions that generate QR barcode image’s URL for passed URLs. I used Kaywa & University of Bath services.

See jQuery and QR code in action on this demo page.

Here are javascript and jQuery QR code functions:

// JavaScript function
function qrcode(url, size){
  if(typeof(size) == 'undefined') size = 8;
  return 'http://qrcode.kaywa.com/img.php?s='+size+'&d='+url;
}
qrcode('http://jquery-howto.blogspot.com');

// jQuery plugin
(function ($) { 
  $.fn.qrcode = function(url, size) { 
    if(typeof(size) == 'undefined') size = 8;
    return 'http://qrcode.kaywa.com/img.php?s='+size+'&d='+url;
  }
})(jQuery);
$().qrcode('http://www.google.com');

The code above utilizes Kaywa’s online QR code generator. You can specify image site as the second argument to the function. The size argument mut be between 1 and 40 and the generated image will 32 x your argument.

Here is javascript and jQuery code for University of Bath barcode generator:

// JavaScript function
function qrcode(url){
  return 'http://go.bath.ac.uk/qr/download?DATA='+url;
}
qrcode('http://jquery-howto.blogspot.com');

// jQuery plugin
(function ($) { 
  $.fn.qrcode = function(url) { 
    return 'http://go.bath.ac.uk/qr/download?DATA='+url;
  }
})(jQuery);
$().qrcode('http://www.google.com');

NOTE: You can encode plain text messages. They are not limited to URLs...

Javascript for() loop vs jQuery .each() performance comparison

This post is an outcome of 15 minutes of free time and a question that I had yesterday. This question were:

  1. How fast jQuery’s .each() method is?
  2. How does it compare to javascript’s native for loop?

It is clear without any performance tests that native javascript for loop is faster, but I always used jQuery’s .each() utility with caution. It always felt like I will get a performance penalty for using it. So I tried to never use it.

So today, I wrote up a little javascript performance test and got my answers. Basically, I created an array and iterated through it using native for loop and jQuery’s .each() iterator. All I did was just an iteration and no array amendments or any other logic. I know it is very basic, but that’s exactly what I want to know. How fast they iterate!

Performance test code:

console.time('TestNative');
length = myArray.length;
for( i=0; i < length; i++){
  myArray[i];
}
console.timeEnd('TestNative');

console.time('TestjQuery');
jQuery.each(myArray, function(i, val) {
  val;
});
console.timeEnd('TestjQuery');

Performance test results:

JavaScript Native FOR loop

Array size    Time
==========    ======
10,000        7ms
100,000       62ms
1,000,000     613ms


jQuery .each() loop

Array size    Time
==========    ======
10,000        10ms
100,000       177ms
1,000,000     1100ms

As you can see native for loop is never over 1ms. That’s probably because we are not doing anything with our array and browser simply optimizes the code or maybe its that fast :)

Usually we don’t have more than 1000 items in our arrays and objects, that is why I guess it can be concluded that using .each() loop in our code will not cause any performance penalties.

Remove the bottom table row using jQuery

I have posted a small jQuery code a while ago which adds a table row at the bottom of any given table. The code takes into the consideration tbody tag and also can be used as a jQuery plugin.

Recently I was asked to write a jQuery or JavaScript code that removes the last/bottom row from the given table. The jQuery code I wrote was surprisingly small.

jQuery code to remove bottom/last table row

// Simple bottom row removal
$('#myTable tr:last').remove();

// Removing n'th (ex. 3rd) row from the table
$('#myTable tr:eq(2)').remove();

Improved jQuery code

We can improve our simple bottom row removal code to take into the consideration the possible <tbody> and <tfoot> HTML tags that can be found in tables.

// Improved code that takes into the consideration
// the <tbody> tag
$('#myTable').each(function(){
    if($('tbody', this).length > 0){
        $('tbody tr:last', this).remove();
    }else {
        $('tr:last', this).remove();
    }
});

// Improved code that for n'th row removal
// In this example we are removing 3rd row
$('#myTable').each(function(){
    if($('tbody', this).length > 0){
        $('tbody tr:eq(2)', this).remove();
    }else {
        $('tr:eq(2)', this).remove();
    }
});

Bonus JavaScript function

You can also turn the code above into the jQuery plugin or JavaScript function. Here is a JavaScript function to remove the bottom table row (you can amend the code to make it remove n’th row).

/*
    Remove the last/bottom table row
*/
function removeTableRow(jQtable){
    jQtable.each(function(){
        if($('tbody', this).length > 0){
            $('tbody tr:last', this).remove();
        }else {
            $('tr:last', this).remove();
        }
    });
}

// Here is how to use it
removeTableRow($('table'));
Also the above javascript function can easily be rewritten as a jQuery plugin. Read this post to learn how to create jQuery plugins.

Get geographical location (geolocation) by IP address using jQuery

Today I came across this post called “IP Address Geolocation Javascript API : JSON”. The author provides you with a free geolocation query URL. The API returns the geographical location of the queried IP address with some additional information such as:

{
	'status':'ok',
	'IP': '74.125.45.100',
	'CountryCode': 'US',
	'CountryName': 'United States',
	'RegionName': 'California',
	'ZipPostalCode': '94043',
	'City': 'Mountain View',
	'Latitude': '37.4192',
	'Longitude': '-122.057'
}

// In case of an error
{
	'status':'parent server not responding'
}

Update: the URL has been changed!

The JSON geolocation querying API’s address is:

http://iplocationtools.com/ip_query.php?output=json&ip=80.80.214.93

The URL above is dead, instead use this one:
http://www.geoplugin.net/json.gp?jsoncallback=?

And the great thing is, you can identify your website visitor’s IP and Geo location by simply querying the API without any parameters like this:

http://iplocationtools.com/ip_query.php?output=json

Knowing your users’ IP and/or location, you might add a behavior to your website that is specific to some location. For example, offering some advertising to US only visitors, or popup with special offer to European users.

Anyway, here is a sample jQuery code to query the API:

// Build the URL to query
var url = "http://iplocationtools.com/ip_query.php?output=json&callback=?&ip=";

// Utilize the JSONP API
$.getJSON(url, function(data){
    if(data['status'] == 'ok'){
        // Do something with the data
        $('#profile #ip')
            .append(data['IP']);
        $('#profile #country')
            .append(data['CountryName']);
    }
});

Here we are not specifying any IP address in the url variable that is why it is getting current user’s data.

Shorten long URLs with jQuery & bit.ly service

I recently signed up to twitter and actively engaging with people who are interested in jQuery. Twitter is a great service and there are all kinds of developers who are sharing interesting links and resources. So it is some kind of interest news group for me. Since you can only have 140 characters in your post, sharing long links limits you. URL shortening services to the rescue. There are lots of free URL shortening services, some are just for long URL shortening, some provide more features like real time click tracking, geostatistics and private URLs.

The great thing about them is that they also provide you with an API. So I thought that there is a way we can make a use of them in our jQuery code. One of the most popular services is bit.ly. You can read more about its API here.

I wrote a simple jQuery code that utilizes the service.

Here is an example:

(function($){
  // set up default options
  var defaults = {
    version:	'2.0.1',
    login:	'bitlyapidemo',
    apiKey:	'R_0da49e0a9118ff35f52f629d2d71bf07',
    history:	'0',
    longUrl:	''
  };

  // Build the URL to query
  var daurl = "http://api.bit.ly/shorten?"
    +"version="+defaults.version
    +"&longUrl="+defaults.longUrl
    +"&login="+defaults.login
    +"&apiKey="+defaults.apiKey
    +"&history="+defaults.history
    +"&format=json&callback=?";

    // Utilize the bit.ly API
    $.getJSON(daurl, function(data){

        // Make a good use of short URL
        $('#myContainer')
            .append(data.results[url].shortUrl);

    });
})(jQuery);

This code does not do much, but I hope you will find a good use of it in your own applications.

jQuery AJAX functions (load(), $.get(), etc.) are not loading new page versions problem

Today I would like to share with you a quick solution to the common problem when your AJAX calls to some page that changes over time is not being loaded to your page. In other words, jQuery or your browser is not loading new version of the page.

This problem is common in Mozilla Firefox (FF). Internet Explorer (IE) users I believe, do not experience this problem. Usually it occurs when you use jQuery AJAX functions in javascript setInterval() method. Basically, what happens is that Firefox can not see the changes been made to the page and thinks it’s the same with the old one. So Firefox loads it from cache and you don’t see the new version of your page. To resolve this issue, you should simply add a random string to the request like below.

The solution:

// Reload mypage.html every 5 seconds
var refresh = setInterval(function()
{
    // Minimized code, suggested by Kovacs
    $('#mydiv').load("mypage.htm?" + 1*new Date() );

}, 5000);