javascript « Intelligrape Groovy & Grails Blogs

Posts Tagged ‘ javascript ’

Getting started with extJS

Posted by Anuj Aneja on April 14th, 2011

Ext.JS JavaScript Framework a cross-browser JavaScript library for building rich internet applications. It is built for developing high performance, customizable UI widgets and features a well designed, documented and extensible Component model. It is available in both Commercial and Open Source licenses are available.

Step 1:
First download the source css and js from here

Step 2:
Include the following css and js as

<link rel="stylesheet" type="text/css" href="../../resources/css/ext-all.css" />
<script type="text/javascript" src="../../adapter/ext/ext-base.js"></script>
<script type="text/javascript" src="../../ext-all.js"></script>

Now start writing the code in script tag or make js file.
jQuery and extJS comparisions:

Document is ready

//document is raedy in jQuery
<script type="text/javascript">
$(document).ready(function() {
  // do stuff when DOM is ready
});
</script>

//in extJS
<script type="text/javascript">
Ext.onReady(function() {
  // do stuff when DOM is ready
});
</script>

Selecting elements

// Selecting by ID in jQuery
var myDiv = $("#element-id");
// Selecting by ID in Extjs
var myDiv = Ext.get('element-id');
// Perform some action on it
// Add a class
myDiv.addClass('my-class');
// Set the width 100 px,
// true is for applying default animation on change
myDiv.setWidth(100, true);
// Retrive some information of the element
// Get the elements box info as object {x, y, width, height}
var box = myDiv.getBox();

extJS:

// Select elements with CSS Selector
var imgs = Ext.select("#my-div div.member img");
// or select directly from an existing element
var members = Ext.get('my-div');
var imgs = members.select('div.member img');
// Now, any Ext.Element actions can be performed on all the elements in this collection

Dom scripting

var el1 = Ext.get("my-1st-div");
var el2 = Ext.get("my-2nd-div");
// Appending elements
el1.appendChild("A new paragraph").appendTo(el2)
// Replcing, removing
var el3 = Ext.get("my-3rd-div");
Ext.get("my-4th-div").replace(el3).insertAfter(el2);
el2.remove()

Events

// Binding an event in jQuery
$(".btn").click(function() {
// Do something on button click
});

// Binding an event in Extjs
Ext.select('.btn').on('click', function() {
// Do something on button click
});

Ajax

// Basic request in jQuery
$.ajax({
type: "POST",
url: url,
data: { x: 'y },
success: function(msg){
alert( "Data Saved: " + msg );
}
});

// Basic request in Ext
Ext.Ajax.request({
url: url,
params: { x: 'abc' },
success: function(msg){
alert( "Data Saved: " + msg );
}
});

Here, I have listed the basic difference between jQuery and extJS for complete reference refer extJs API docs
hope it helps you guys :)

Anuj Aneja
Intelligrape Software

  • Share/Bookmark
Posted in Grails

Using Google Analytics for tracking Multiple Steps of a Webflow

Posted by Vivek Krishna on February 28th, 2011

In one of our projects, we are using a webflow for an order wizard. We needed to track the number of users converting a draft to a confirmed order using Google Analytics. This would have been simple if the URLs were different for each step. However, that is not the way webflows work and a similar URL is generated for multiple steps. After some searching around, we found that we could call a trackPageView method in Google Analytics API and set a name for the page being tracked. This could be done using

<script type="text/javascript">
    try {
        var pageTracker = _gat._getTracker("<ANALYTICS-KEY>");
        pageTracker._trackPageview("/enterDetails.html");
    } catch(err) {
    }
</script>

Replacing “/enterDetails.html” in each page with the corresponding step name did the trick. However, this is an old version of the Google Analytics API. Our application uses a newer version of the JavaScript code provided by Google.

In this, we had to use Virtual Page Tracking, which is a method explained in the Google Analytics API Docs under the section, Virtual Page Views. We had to write something like


<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'ANALYTICS-KEY']);
_gaq.push(['_trackPageview', '/enterDetails.html']);
(function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>

For usage on grails, we used a template, which takes in the pageName and uses /${controllerName}/${actionName}/${pageName} to  generate the virtual page name which is tracked. Now we are successfully tracking the conversions.

Hope this helps.

Vivek

http://in.linkedin.com/in/svivekkrishna

  • Share/Bookmark

File Uploading using plupload plugin of jquery.

Posted by Anuj Aneja on February 14th, 2011

In my grails project i was having the requirement of having multiple file uploading, but in current implementation there was the problem of button being not loaded in Internet Explorer.For that i found plupload very cool to implement this. It has very cool feature of drag and drop and support for almost all browser. Actually what it does is based on the browser, get the Runtime of the browser.For Documentation, js and css refer link

In gsp we need to include the js of pluplaod api as shown below:

<link rel="stylesheet" href="${resource(dir: 'css/plupload/css', file: 'plupload.queue.css')}" type="text/css" media="screen">
<link rel="stylesheet" href="${resource(dir: 'css/plupload/css', file: 'jquery.ui.plupload.css')}" type="text/css" media="screen">
<g:set var="fileExtension" value="${new FileExtension()}"></g:set>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<p:javascript src='jquery-1.3.2'/>
<script type="text/javascript" src="${resource(dir: "js/plupload", file: "gears_init.js")}"></script>
<script type="text/javascript" src="${resource(dir: "js/plupload", file: "browserplus-min.js")}"></script>
<!-- Load source versions of the plupload script files -->
<script type="text/javascript" src="${resource(dir: "js/plupload", file: "plupload.js")}"></script>
<script type="text/javascript" src="${resource(dir: "js/plupload", file: "plupload.gears.js")}"></script>
<script type="text/javascript" src="${resource(dir: "js/plupload", file: "plupload.silverlight.js")}"></script>
<script type="text/javascript" src="${resource(dir: "js/plupload", file: "plupload.flash.js")}"></script>
<script type="text/javascript" src="${resource(dir: "js/plupload", file: "plupload.browserplus.js")}"></script>
<script type="text/javascript" src="${resource(dir: "js/plupload", file: "plupload.html5.js")}"></script>
<script type="text/javascript" src="${resource(dir: "js/plupload", file: "jquery.plupload.queue.js")}"></script>
<script type="text/javascript">
    var button = '${buttonId}';
</script>

Now we need to write script to load and bind the plupload plugin shown below:

	<script type="text/javascript">
    var runtimesList;
    if (navigator.userAgent.indexOf("Firefox")!=-1){
        runtimesList='silverlight,browserplus,html4,gears,flash,html5';
    }else{
        runtimesList='html5,silverlight,browserplus,html4,gears,flash';
    }
    $(function() {
        var uploader = new plupload.Uploader({
            runtimes : runtimesList,
            browse_button : 'pickfiles',
            url : url,
            flash_swf_url : '${resource(dir: "js/plupload", file: "plupload.flash.swf")}',
            silverlight_xap_url : '${resource(dir: "js/plupload", file: "plupload.silverlight.xap")}',
            filters : [
                {title : "Image files", extensions : "gif,png"},
                {title : "Zip files", extensions : "zip"}
            ]
        });

        uploader.bind('Init', function(up, params) {
        });

        uploader.bind('FilesAdded', function(up, files) {
            $.each(files, function(i, file) {
                $('#filelist').append('<div id="' + file.id + '"><span class="mcentd9d" style="font-size:12px; color:green;">File: ' + file.name + ' uploaded successfully!(' + plupload.formatSize(file.size) + ')<b></b><\/span>' + '</div>');
            });
        });

        uploader.bind('UploadFile', function(up, file) {

        });

        uploader.bind('UploadProgress', function(up, file) {
            $('#' + file.id + " b").html(file.percent + "%");
        });

        uploader.bind('QueueChanged', function(up) {
            $('#uploadfiles').click();
        });

        uploader.bind('FileUploaded', function(up) {

        });
        uploader.bind('Error', function(up) {
            alert('Error in uploading file');
        });

        $('#uploadfiles').click(function(e) {
            uploader.start();
            e.preventDefault();
        });
        uploader.init();
    });

</script>
	<div class="attachment">
               <div id="filelist"></div>
                      <a href="#" class="plupload_button plupload_add" id="pickfiles" style="position: relative; z-index: 0; ">Select File</a>
                      <input type='hidden' id="uploadfiles"/>
          </div>

Now we need to handle the saving part of the file,for each file uploaded in Queue there is separate call to
the action.It saves the file to the filePath specified.

def saveAttachment={
      def files = request.getFileMap()
      def file=files.get("file")
      String fileName = file.getOriginalFilename()
      byte[] data=file.getBytes()
      File dir=new File(filePath)//some path...
      if(!dir.exists()){
         dir.mkdirs()
      }
      File actualFile=new File(filePath, fileName)
      actualFile.withOutputStream {out ->
             out.write data
      }
}

Disclaimer: As in some cases you might want to can the upload of all the files as there is a different call to action of you can save there files in session, but session for this plupload is different from current user session so you will have to make your own session handling for that!!!

Note:The total length of files upload and and total uploaded differs in case IE and Firefox. The comments and any suggestions are welcomed.

Hope it help you guys! Cheer! :)

Anuj Aneja

http://www.Intelligrape.com

  • Share/Bookmark

JQGrid Expanding SubGrid on page load

Posted by Tarun Pareek on February 13th, 2011

Hi,
 
Recently guys, i faced problem while expanding the JQGrid SubGrid onLoad of the page.
 
Initially, i used the following code on gridComplete Event of JQGrid, Using the code given below, i am only able to expand grid but without data populated in subgrid.

gridComplete: function() {
                var rowIds = $("#testTable").getDataIDs();
                $.each(rowIds, function (index, rowId) {
                        $("#testTable").expandSubGridRow(rowId);                   
                });
            }

After trying different ways, and many efforts i came up with this solution and it worked for me.
Solution to above problem given below :

gridComplete: function() {
                var timeOut = 50;
                var rowIds = $("#testTable").getDataIDs();
                $.each(rowIds, function (index, rowId) {
                    setTimeout(function() {
                        $("#testTable").expandSubGridRow(rowId);
                    }, timeOut);
                    timeOut = timeOut + 200;
                });
            }

It worked for me. Hope it help you too.

Thanks & regards,
Tarun Pareek
LinkedIn

  • Share/Bookmark

Sharing Session Information between Wordpress and Grails using Cookies and base64 encoding

Posted by Vivek Krishna on August 3rd, 2010

A scenario arose in one of our projects that we had to share some information between the grails application (which was taking care of dynamic content) and wordpress (which was used to maintain the static pages about the application). The information was the logged in user’s name so that we could display that on the header. After giving it some thought, we decided that setting a cookie with the logged in user’s name from the grails application and then reading it from the wordpress application using javascript was one way of doing so.

This was achieved by setting the cookie with code on grails side as

Cookie cookie = new Cookie('userNameCookie', fullname);
cookie.setVersion(-1)  // unknown version bypasses quoting logic
cookie.path = "/"
cookie.maxAge = 30 * 60 * 60; //30 minutes life
response.addCookie(cookie)

There is an excellent jQuery cookie plugin to read cookies using javascript. All that needs to be done is include the javascript file and call the method given below to get the value from it

jQuery.cookie('userNameCookie')

However, there was an issue with this approach. The usernames could have unicode characters like ä, ö etc. The cookie was not getting set from the grails application and threw an Exception because the unicode characters weren’t escaped. The exception also suggested that we could use decodeBase64(). But since it was due to encode, we decided to convert the fullname to bytes, encode it to base64, call the toString() method and then set the value. What we did was to change the cookie value to from grails

Cookie cookie = new Cookie('usercookie', fullname.bytes.encodeBase64().toString());

In order to decode this base64 encoded string on the client side, we used the jQuery Base 64 Functions plugin. This can be used to decode a base64 encoded string as

jQuery.base64Decode(jQuery.cookie('userNameCookie'));

This worked like a charm.

Hope this helps

Vivek

http://in.linkedin.com/in/svivekkrishna

vivek[at]intelligrape.com

  • Share/Bookmark

jQuery Alert Message without using traditional javascript alert-box.

Posted by Salil on June 14th, 2010

This post might help you if you want to display alert messages without using tradition javascript (irritating) alert.
To achieve this you need jQuery for your frontend UI.

Below is the javascript method (code snapshot) which displays your message for 5 seconds. And then fades out automatically.

function displayAlertMessage(message) {
var timeOut = 5
jQuery('#messageBox').text(message).fadeIn()
jQuery('#messageBox').css("display", "block")
setTimeout(function() {
jQuery('#messageBox').fadeOut()
jQuery('#messageBox').css("display", "none")
}, timeOut * 1000);
}

messageBox is id of your div tag where you want to display the Alert Message.
timeOut is number of seconds you want to hold message on screen.
That’s it. So simple and quite comfortable from a user’s perspective Isn’t it? :-)

Cheers!!
Salil Kalia



  • Share/Bookmark

Tracking Image Clicks using Google Analytics

Posted by Vivek Krishna on February 25th, 2010

In one of the projects, it was required to track the number of times an image (which linked to another page) was clicked using Google Analytics. We found a very informative article here. It talks about tracking external links and file downloads. This wasn’t exactly our purpose, but the javascript downloaded from there acted as a very good starting point.

What we did was to add a code block like this after line no. 13 of the javascript code from the link given above.

var imgs = document.getElementsByTagName("img");
for(var l=0; l <imgs.length; l++) {
       try {
               var path = imgs[l].getAttribute('src');
               var isDoc = path.match(/\.(?:jpg|png|gif|svg)($|\&|\?)/);
               startListening(imgs[l],"click", trackImageClicks);
       }
       catch(e){
           continue;
       }
    }

And a method before the Analytics script provided by Google for the site

function trackImageClicks(evnt) {
    var e = (evnt.srcElement) ? evnt.srcElement : this;
    var lnk = (e.getAttribute("src").charAt(0) == "/") ? e.getAttribute("src") : "/" + e.getAttribute("src");
    if (typeof(pageTracker) == "object") pageTracker._trackPageview(lnk);
    while (e.tagName != "A") {
        e = e.parentNode;
    }
     lnk = (e.pathname.charAt(0) == "/") ? e.pathname : "/" + e.pathname;
    if (e.search && e.pathname.indexOf(e.search) == -1) lnk += e.search;
    if (e.hostname != location.host) lnk = e.hostname + lnk;
    if (typeof(pageTracker) == "object") pageTracker._trackPageview(lnk);
}

Now, the clicks on each image were getting tracked.

  • Share/Bookmark

Identify merchant provider from the given credit card no.

Posted by Amit Jain on November 4th, 2009

Hi Friends,

I was working on the financial application, where the user doesn’t want to select merchant provider while feeding in credit card details and yet we needed to know the merchant provider. Following is the code that helped:

function getMerchantProvider(cardNo){                      //cardNo is the credit card number
    var cards = new Array();
    cards [0] = {cardName: "Visa",prefixes: "4"};
    cards [1] = {cardName: "Mastercard", prefixes: "51,52,53,54,55"};
    cards [2] = {cardName: "DinersClub", prefixes: "300,301,302,303,304,305,36,38,55"};
    cards [3] = {cardName: "CarteBlanche", prefixes: "300,301,302,303,304,305,36,38"};
    cards [4] = {cardName: "American Express", prefixes: "34,37"};
    cards [5] = {cardName: "Discovery",  prefixes: "6011,650"};
    cards [6] = {cardName: "JCB", prefixes: "3,1800,2131"};
    cards [7] = {cardName: "enRoute", prefixes: "2014,2149"};
    cards [8] = {cardName: "Solo", prefixes: "6334, 6767"};
    cards [9] = {cardName: "Switch", prefixes: "4903,4905,4911,4936,564182,633110,6333,6759"};
    cards [10] = {cardName: "Maestro", prefixes: "5020,6"};
    cards [11] = {cardName: "VisaElectron", prefixes: "417500,4917,4913"};
    var prefix
    var cardType

    for(cardType=0; cardType<cards.length; cardType++){
        prefix = cards[cardType].prefixes.split(",");
        for (i=0; i<prefix.length; i++) {
             var exp = new RegExp ("^" + prefix[i]);
             if (exp.test (cardNo))
                  return cards[cardType].cardName;      
       }
    }
     return "Invalid";       
}

The above function returns merchant provider name if matching pattern is found and Invalid if not. Please make a note, this function doesn’t validates the credit card no.

For the credit card number validation I used jquery extended validation plugin for credit card, which also needed to know the merchant provider for validation so this code helped. Extended credit card validation plugin can be found at http://www.ihwy.com/labs/jquery-validate-credit-card-extension.aspx

Thanks!

~~Amit Jain~~
amit@intelligrape.com
IntelliGrape Softwares

  • Share/Bookmark

Ajax Request Progress Indicator

Posted by Bhagwat Kumar on October 12th, 2009

In my current project, I used ajax to fetch data from the server to provide Desktop Application like Experience. I wanted to automatically show an indicator when an AJAX request is ongoing, and hide it when there is no such request. So I found the following solution for both the Prototype library and the JQuery library.

Make sure the following HTML is included on every page where AJAX requests are made. (Place it in body of the main layout so that you do not have to repeat this HTML on each page.

<span id="ajax_spinner" style="display:noneposition:absolute top:50% left:50% z-index:3000">
       <-- Design Busy indicator here -->
       <img src="/yoursite/images/spinner.gif"/>
</span>

Make sure the following javascript code has been executed before any AJAX request is made. (Move this to a js file and include it in Heading part of the main layout).

<script type="text/javascript">
 
/*
  Registering responders for prototype library.
  (If you are not using  prototype library then there is no need of the next statement.)
*/
 
Ajax.Responders.register({
          onCreate: function() {
              jQuery("#ajax_spinner").show();
          },
          onComplete: function() {
              jQuery("#ajax_spinner").hide();
          }
});
 
/*
   Registering responders for jQuery AJAX calls.
*/
 
jQuery("#ajax_spinner").ajaxStart(function() {
              jQuery(this).show();
 });
jQuery("#ajax_spinner").ajaxStop(function() {
              jQuery(this).hide();
});
 
/*
    Note : If you are not using jQuery you can show/hide the div
         using javascript(e.g. document.getElementById) to do the same
*/
</script>

The above trick worked for me and hope it works for you guys too.

Helpful links :-
http://www.prototypejs.org/api/ajax/responders
http://docs.jquery.com/Ajax/jQuery.ajax
http://blogs.aarohan.biz/2009/05/26/get-started-with-jquery-ajax-and-json-in-your-perl-web-applications (Thanks to Amit)

~~~~Bhagwat Kumar~~~
bhagwat@intelligrape.com

  • Share/Bookmark

Add hotkeys to the web application

Posted by Amit Jain on September 28th, 2009

Let us have a look at the simple javascript code, that can be used to add hotkeys to our web application. I tried using jquery hotkeys plugin and two more plugins, but they didn’t work for me.

So I ended up handling the keydown event of my own.

var isAlt = false;
document.onkeyup = function(e) {
    if (e.which == 18) //18 is the keycode for 'Alt'
	isAlt = false;
}
document.onkeydown = function(e) {
    if (e.which == 18)
	 isAlt = true;
    else if (e.which == 69 && isAlt == true) { //69 is the keycode for 'e'
        function1(); 	 // executed when alt+e is pressed
        return false;
    } else if (e.which == 71 && isAlt == true) {
        function2(); 	 // executed when alt+g is pressed
        return false;
    }
    ...
}

Hope this helped.

Cheers!
~~Amit Jain~~
amit@intelligrape.com
IntelliGrape Softwares

  • Share/Bookmark