Javascript/Ajax/JQuery « Intelligrape Groovy & Grails Blogs

Archive for the ‘ Javascript/Ajax/JQuery ’ Category

JavaScript Profiling through Firebug’s Console API.

Monday, August 16th, 2010
Posted by Chandan Luthra

Sometimes we want to know which line of codes or methods in the JavaScript is taking time which slows up the page load. Many times our browser gets hanged due to execution of JavaScript.

Firebug allows us to profile the JavaScript. Following are the two methods that are used for profiling JavaScript:
console.profile()
console.profileEnd()

After the execution of the JS, Firebug generates a nice stats through which one can figure out the problematic line of code(if any).

Type this following code in an HTML file, save it and open it up with Firebug enabled Firefox(if Firebug is not enabled then press F12 key to activate it) :

<html>
<head><title>Firebug</title>
<script>
function bar(){
	console.profile('Measuring time')
	foo()
	console.profileEnd()
}
function foo(){
	loop(1000)loop(100000)loop(10000)
}
function loop(count){
	for(var i=0i<counti++){}
}
</script></head><body>
Click this button to profile JavaScript
<input type="button" value="Start" onclick="bar()"/>
</body></html>

Click on the button to start the JavaScript profiler. You would see table is generated in the Firebug’s Console panel.
JS profiling
Description and purpose of the columns:
Function: This column shows the name of each function.
Call: It shows the count of how many a particular function has been invoked. (3 times for loop() function in our case.)
Percent: It shows the time consuming of each function in percentage.
Own Time: It shows the duration of own script in a particular function. For example foo() function has none of its own code. Instead, it is just calling other functions. So, its own execution time will be approx ~0ms. If you want to see some values for that column, add some looping in this function.
Time: It shows the duration of execution from start point of a function to the end point of a function. For example foo() has no code. So, its own execution time is approx ~0ms, but we call other functions in that function. So, the total execution time of other functions is 4.491ms. So, it shows 4.54ms in that column which is equal to own time taken by 3 loop() function + own time of foo().
Avg: It shows the average execution time of a particular function. If you are calling a function one time only, you won’t see the differences. If you are calling more than one time, you will see the differences. The formula for calculating the average is:
Avg = Own time / Call
Min and Max columns: It shows the minimum execution time of a particular function. In our example, we call loop() for 3 times. When we passed 1000 as a parameter, it probably took only a few millisecond (let’s say 0.045ms.) and when, we passed 100000 to that function, it took much longer than first time (let’s say 4.036ms). So, in that case, 0.045ms will be shown in Min column and 4.036ms will be shown in Max column.
File: It shows the file name of file with line number where the function is located

Any comments and suggestions are welcome :)
~~Chandan Luthra~~
References:
Book https://www.packtpub.com/firebug-1-5-editing-debugging-and-monitoring-web-pages/book
Refcard http://refcardz.dzone.com/refcardz/getting-started-firebug-15

  • Share/Bookmark

What is Google Web Optimization, How to use or apply it in your project?

Thursday, August 12th, 2010
Posted by Tarun Pareek

Recently as part of POC, I need to apply the google web optimizer on various parts of page to determine which content user respond to best and will be most effective in getting conversions. For this you need to keep track of the various conversions, but how? Thats where google web optimizer come handy, providing reports based on experiments specified by you on various parts of page and also suggesting action to optimize your site for better business results.

Steps to apply google web optimization in your project :

1. Create an account in google web optimizer and sign in.

2. Then take some time to determine which aspect or parts of page you want to test and how.(for more valuable and better results).

3. Create an experiment in google web optimizer :

  • 3.1 Choose algo for experiment: Multivariate test or A/B test.
    • 3.1.1 Multivariate test allow you to apply variations on various part of same page.
    • 3.1.2 A/B test allow you to apply conversion between two pages. (Not on various part of page).
    • **In my case i choose multivariate test.
  • 3.2 Fill in details : Give your experiment unique name, specify the tracking page public URL on which various parts optimization is to be done and also specify the conversion page public URL on which user will be directed after successful conversion.(Very useful in term of form submission).

4. Tag Pages -> Now the optimizer provide you several tags, How to apply scripts/tags on your page for that particular experiment :

  • 4.1 Control Script : Randomly control the variations on parts of page. (Must Applied in header tag of page)
    	<!-- Google Website Optimizer Control Script -->
    	<script>
    	function utmx_section(){}function utmx(){}
    	(some script......................................................
    	length+1,j<0?c.length:j)}}}var x=f('__utmx'),xx=f('__utmxx'),h=l.hash;
    	d.write('<sc'+'ript src="'+
    	'http'+(l.protocol=='https:'?'s://ssl':'://www')+'.google-analytics.com'...........
    	................................. some more script text here
    	</script>
    	<!-- End of Google Website Optimizer Control Script -->
  • 4.2 Tracking Script : Track the user behaviour. (Applied at bottom of the page within body tag).
    	<!-- Google Website Optimizer Tracking Script -->
    	<script type="text/javascript">
    	Some script text here...................................
    	........................................................
    	<script type="text/javascript">
    	try {
    	var gwoTracker=_gat._getTracker("....some id for tracker..........");
    	gwoTracker._trackPageview("...tracker page.....");
    	}catch(err){}</script>
    	<!-- End of Google Website Optimizer Tracking Script -->
  • 4.3 How to apply Variation Script : Applied just before the part of code to be tested(headline, image, promotext, button) i.e. on which variation is to be applied and at the end of that code part “noscript” tag need to be applied to specify the region for variation and unique tag names for particular variation section.
    	<script>utmx_section("payment")</script>
    		Test Drive our product in <b>$10</b>
    	</noscript>
  • 4.4 Conversion Script : To be applied in body tag at bottom of converision page you specified.
    	<!-- Google Website Optimizer Conversion Script -->
    	    <script type="text/javascript">
    	    some script.....................................................
    	    '.google-analytics.com/ga.js"></sc'+'ript>')</script>
    	    <script type="text/javascript">
    	    try {
    	    var gwoTracker=_gat._getTracker("....some id for tracker..........");
    	    some script code here.....................................
    	    }catch(err){}</script>
    	<!-- End of Google Website Optimizer Conversion Script -->

5. Validate Pages -> First apply all the tags on your page as specified above and then validate the page with optimizer validate page link, that all the script are applied correctly.

  • 5.1 If you use validate pages button then it will use the public URL you specified for tracking and conversion page.
  • 5.2 To validate the pages offline, Optimizer provide option to manually provide pages that are to be validated.

Note : All the test need to be passed to apply optimization on your page.

6. Create a Variations -> After applying tags, create variations for the various part of page. Variation can include any type of string(it can be a html code, text, script etc).

Example : Within payment tag :

Original Variation : Test Drive our product in $10 (specified in your page)
Variation 1 named “Classic” :

		Test Drive our product in <b>$50</b>

Variation 2 named “Executive” :

		Test Drive our product in <b>$100</b> with additional privileges

7. Review and Launch the Experiment, in Google web optimizer.

Example :

	<html> 
	<head>   
	    <!-- Google Website Optimizer Control Script -->
		<script>
		function utmx_section(){}function utmx(){}
		some script.....................................................
		length+1,j<0?c.length:j)}}}var x=f('__utmx'),xx=f('__utmxx'),h=l.hash;
		d.write('<sc'+'ript src="'+
		some code here ...............................................
		+new Date().valueOf()+(h?'&utmxhash='+escape(h.substr(1)):'')+
		'" type="text/javascript" charset="utf-8"></sc'+'ript>')})();
		</script>
		<!-- End of Google Website Optimizer Control Script -->
	</head>
	<body>
             ............body code start here............................................................................
             ....................................................................................................................
	    <script>utmx_section("offer")</script>
			Secure your child future in <b>$10</b>
	    </noscript>
           ....................................................................................................................
           ....................................................................................................................
 
 
	    <!-- Google Website Optimizer Tracking Script -->
		<script type="text/javascript">
		some script.....................................................
		'.google-analytics.com/ga.js"></sc'+'ript>')</script>
		<script type="text/javascript">
		try {
		some code...................................................
		}catch(err){}</script>
		<!-- End of Google Website Optimizer Tracking Script -->
 
	</body>
	</html>

Hope this will help to improve your site business ;)

Regards,
Tarun Pareek
Intelligrape Software

  • Share/Bookmark
Comments Off

Creating select tag with optgroup in Grails

Tuesday, August 10th, 2010
Posted by Vishal Sahu

Hi,
In one of my projects i needed to create a select-input tag with OPTGROUP options.
I searched a lot about it and found that g:select tag do not support OPTGROUP

So to solve this problem, i created a simple optgroup tag using Html and grails taglib.

I created a Map for the values to be used in the select tag and pass it to the test.gsp page from the controller.
Say Map dataMap=["Car":["Car A","Car B","Car C"],”Truck”:["Truck A","Truck B"]]

I put the tag in test.gsp where i want to display the select dropdown

 
         <test:optGroup name = "data" dataMap="${dataMap}" />

In my TestTaglib.groovy, i defined the tag as

 
class TestTagLib {
    static namespace = 'test'
 
    def optGroup = {attrs ->
        Map dataMap = attrs['dataMap']
        out << g.render(template: 'layouts/optSelect', model: [dataMap:dataMap])
    }
}

I created a template “_optSelect.gsp” under the layouts folder

 
<select name="mainList">
    <optgroup label="--"><option value="">(Select One)</option></optgroup>
    <g:each in="${dataMap}" var="data">
        <optgroup label="${data.key}">
            <g:each in="${data.value}" var="value">
                <option value="${value}">${value}</option>
            </g:each>
        </optgroup>
    </g:each>
</select>

This generated the required SELECT dropdown with OPTGROUP and solved the problem.

Hope it helps.

Regards:-

Vishal Sahu
vishal@intelligrape.com

  • Share/Bookmark

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

Tuesday, August 3rd, 2010
Posted by Vivek Krishna

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

Suppress Tracking of various scripts on test and development environment

Sunday, July 11th, 2010
Posted by Tarun Pareek

In my recent project, every time the page loads, it loads with lots of scripts making calls to and getting content from googleapis, fb, clixpy, cdn etc. to provide the functionality, due to which the page loads very slowly and this led to the wastage of time to test a certain functionality.

To overcome this problem in test and development environment and at the same time to run those script in the production environment, I added the “suppressTracker” tag that enable or disable the script on the basis of environment on which it is executing or on the basis of session set for tracker.

Step 1 : Create the suppressTracker tag in your tagLib,

import grails.util.Environment;
 
def suppressTracking = {attrs, body ->
        if (Environment.currentEnvironment==Environment.PRODUCTION && !session.suppressTracking){
            out<< body()
        }
}

Step 2 : Add suppressTracker tag on the script which you want to suppress for test and development environment,

<util:suppressTracking>
  <script type="text/javascript">
       Your Script Code ..........
  </script>
</util:suppressTracking>

Hope this code will help :)

~Regards,
Tarun
Intelligrape Software

http://in.linkedin.com/in/tarunpareek

  • Share/Bookmark

Rounded corner and CSS3 Gradient with border

Friday, July 2nd, 2010
Posted by umar

First download these files:
http://code.jquery.com/jquery-1.4.2.min.js
http://codelab.jomvideo.com/javascript/curvycorners-2.1-BETA/curvycorners.src.js

You can round corner DIV, LI tags and others
You add a class where you want round corner

Add this CSS:

.cornerBox ul li.corner{zoom:1;border:0;filter:progid:DXImageTransform.Microsoft.Gradient(GradientType=0,StartColorStr='#1f858f',EndColorstr='#329ba6');background:-webkit-gradient(linear, left top, left bottom, from(#1f858f), to(#329ba6));background:-moz-linear-gradient(top, #1f858f, #329ba6);background:#1f858f;}
.cornerBox ul div.outer {background:#fff;padding:0;margin-top:15px;}

Add this jQuery code:

 $(function(){
		 $('.corner').wrap('
 
');
		$('.corner').corner("round 3px").parent().css('padding', '1px').corner("round 3px")
		    });

Hope this helps !!

Umar Pahat
umar@intelligrape.com

http://www.intelligrape.com

  • Share/Bookmark

jQuery Alert Message without using traditional javascript alert-box.

Monday, June 14th, 2010
Posted by salil

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

How to send a POST request in window.open() function of JavaScript.

Monday, June 14th, 2010
Posted by Chandan Luthra

Hey,

Recently, I need to show some printing stuff using window.open() method of JavaScript. I got stuck when the implementation demands sending POST call to the server for generating the print view.

I googled a lot and found few JavaScript code snippets that provides some workaround for doing this stuff. Finally, I found some cool way for sending POST request in window.open(). I thought, it’ll be worth sharing.

Here is the code:

<form onsubmit="window.open(' ','myWindow','status=yes,scrollbars=yes,
width=100,height=100')" action="generatePrintMaterial.html" method="POST" target="myWindow">
...........................................................
...................//input fields.......................
..........................................................
<input name="Print" type="submit" />
</form>

Notice the name of the window (‘myWindow’) is same as the name given in form’s ‘target’ attribute. On submitting this form, javascript will open a new window and the output of the form will get rendered in that window.

Hope this helps..

~Chandan Luthra~
chandan(AT)intelligrape(DOT)com

http://in.linkedin.com/in/luthrachandan

http://twitter.com/chandanluthra

  • Share/Bookmark

JQuery: Send JSON Objects with an ajax request

Friday, June 11th, 2010
Posted by Amit Jain

Hi Friends,

Lets discuss today about sending JSON objects with ajax request using JQuery. We have number of functions in jQuery to kick-off an ajax request. But for sending JSON objects along with the request, I chose jQuer.ajax(). It takes various parameters url, type, data, dataType, beforeSend etc. Its API can be found here.

Lets look at example given below:

jQuery.ajax({
          url: <Url of the action>,
          type: "POST",
          data: {name: "amit", id:1 },
          dataType: "json",
          beforeSend: function(x) {
            if (x && x.overrideMimeType) {
              x.overrideMimeType("application/j-son;charset=UTF-8");
            }
          },
          success: function(result) {
 	     //Write your code here
          }
});

The above example works for simple JSON object. Now lets see how we can send JSON objects list as given below:

var jsonObjects = [{id:1, name:"amit"}, {id:2, name:"ankit"},{id:3, name:"atin"},{id:1, name:"puneet"}];
 
jQuery.ajax({
          url: <Url of the action>,
          type: "POST",
          data: {students: JSON.stringify(jsonObjects) },
          dataType: "json",
          beforeSend: function(x) {
            if (x && x.overrideMimeType) {
              x.overrideMimeType("application/j-son;charset=UTF-8");
            }
          },
          success: function(result) {
 	     //Write your code here
          }
});

If you notice, for sending my json objects it has not been written directly as data: jsonObjects. As it expects the JSON object passed to it written as key value pair. So we made students the key. And since we have json objects stored in a variable, we need to expand the json objects list using stringify(), otherwise it would be sent as a java script object.

Now on the server we can parse the JSON object, and use it as the list of objects of type map. For example

//this code is written in grails 
import grails.converters.JSON;
List<JSON> students = JSON.parse(params.students) //students in request params is parsed to json objects and stored in the List
println "Student id: " + students[0].studentId    //first element of the students list is accessed as a map holding a key studentId

Hope this helpled!

~~Amit Jain~~
amit@intelligrape.com

http://www.IntelliGrape.com

  • Share/Bookmark
Tags: , ,

Implementing feedback functionality using uservoice.

Thursday, June 10th, 2010
Posted by anshul

Hi,

Recently in our project , we need to implement the feedback functionality.
We implemented it using uservoice https://uservoice.com.

Steps for implementing user’s feedback :
1) Create the uservoice account https://uservoice.com/users/new
2) On admin dashboard under the widget tab you will get a generated javascript.
The format of the script will be as follows:

<script type="text/javascript">
    var uservoiceOptions = {
        /* required */
        key: 'appName',
        host: 'appName.uservoice.com',
        forum: '',
        showTab: true,
        /* optional */
        alignment: 'left',
        background_color:'#f00',
        text_color: 'white',
        hover_color: '#06C',
        lang: 'en'
    };
 
    function _loadUserVoice() {
        var s = document.createElement('script');
        s.setAttribute('type', 'text/javascript');
        s.setAttribute('src', ("https:" == document.location.protocol ? "https://" : "http://") + "cdn.uservoice.com/javascripts/widgets/tab.js");
        document.getElementsByTagName('head')[0].appendChild(s);
    }
    _loadSuper = window.onload;
    window.onload = (typeof window.onload != 'function') ? _loadUserVoice : function() {
        _loadSuper();
        _loadUserVoice();
    };
</script>

3) Copy the generated javascript in your webpage where you wants to display the feedback button.

Hope this will help you.

Cheers!

Anshul Sharma
anshul@intelligrape.com

  • Share/Bookmark