Javascript/Ajax/JQuery « Intelligrape Groovy & Grails Blogs

Archive for the ‘ Javascript/Ajax/JQuery ’ Category

JQuery script to put focus on first field of any page

Posted by Vishal Sahu on January 13th, 2011

Hi,

In my recent grails project, i needed to put focus on the first field of any page whenever the page loads. The requirement is such that if the page contains errors then the focus should be on the first input field which has errors.

I searched a lot and with the help of my colleague we came out with a simple JQuery script to put focus on the first input field on any page whenever the page loads.

The script i used is:-


   if (jQuery('.errors').size() > 0) {
       jQuery('input.errors:first').focus();
       jQuery('.errors input:visible:first').focus();
     }
   else {
      jQuery('input:text:visible:first').focus();
    }

I put it in the layout and it works for every gsp which has that layout.

It worked for me.
Hope it Helps.

Vishal Sahu
vishal@intelligrape.com
www.intelligrape.com

  • Share/Bookmark

JQGrid Powerful Plugin With Cool Features

Posted by Tarun Pareek on January 12th, 2011

Recently i worked on a JQuery plugin named JQGrid, I found it very productive if you know how to code in JQuery and Javascript. As it also provide event handler and user API it make it more flexible and easier to code.
 
JQgrid provide plenty of features, some of its cool features such as,
 
- Solve problem regarding fixing table header while inner scroll is applied to the table data(body).
- Easy to implement Basic Grid, with searching, sorting and filtering with fix header and scalable table structure.
- Provide both XML and JSON support for data. You can also use local data and generate grid using it.
- Provide pagination, and virtual scrolling(Auto loading of data while scrolling)
- Multi language support(i18n)
- Provide subgrid implementation
- Provide Grouping
- Provide Tree grid
- Event Handling and various methods gives more flexibility
- Formatting is another cool feature, you can format the content of the cell and create your custom formatters also.
- Inline Editing in supported(text, textarea, checkbox, select, image, button type).
- Client side validation of entered data is supported.
- Form Editing is supported, full control of form, all features of editing including client side validation.
- Similarly support cell Editing.
- Searching and filtering,
   - custom search
   - toolbar search
   - complex form search
   - Advanced searching with criteria defined
- Support loadonce(load all the data at once)
- hideGrid Feature, work like accordian, collapse/expand of table on click of header.
- Remote data upload
- Navigator footer, you can add your own button to provide functionality on footer.
- Also provide row footer,
- UI DatePicker support, JQuery UI Themes etc.
 
Some Tricks :
- Use ignoreCase:true feature to apply case-insensitive filtering.
- To display All rows, either simply set the number of rows to rowNums or you can use ‘-1′, set rowNum:-1 it will display all the rows.
Note : Precaution leave always last row blank, as ‘-1′ deduct one row from all the record in the table.(I face the same problem)
- Use afterInsertRow Event, But Note: this event does not fire if gridview option is set to true.
 
A DrawBacks :
- Doesn’t support row and colspan :( That the one thing i feel is missed in plugin.
 
Else very powerful plugin. :)
 
This plugin provide so much feature which really make the table implementation with so much functionality on the tip of your hand.
 
Following Links that may Help you in implementation of JQgrid 3.8,
 
Demo : http://trirand.com/blog/jqgrid/jqgrid.html
Documentation : http://www.trirand.com/jqgridwiki/doku.php?id=wiki:jqgriddocs
Events : http://www.trirand.com/jqgridwiki/doku.php?id=wiki:events
Options : http://www.trirand.com/jqgridwiki/doku.php?id=wiki:options
Methods : http://www.trirand.com/jqgridwiki/doku.php?id=wiki:methods
Treegrid : http://www.trirand.com/jqgridwiki/doku.php?id=wiki:treegrid
 
Hope this, JQgrid plugin help you to improve your UI and implementation made much easier. (Powerful plugin with cool features.)
 
Thanks & regards,
Tarun Pareek
LinkedIn

  • Share/Bookmark

Sleep in Jquery.

Posted by Chandan Luthra on December 15th, 2010

Few days earlier, for achieving “Thread.sleep()” functionality in Jquery, I use javascript’s “setTimeout()” method.

I found that Jquery has a finer and better way for doing this, The “delay()” method

Example: If I want to show an element after 1000 mili seconds then I would do it in following way:

$("div .heading").delay(1000).show()

Hope this little sharing helps to you.

~Chandan Luthra~
chandan(at)intelligrape(dot)com

  • Share/Bookmark

Jquery : map and grep functions

Posted by Amit Jain on November 15th, 2010

Hi friends,

I was going through some utility funcitons being provided by jQuery. Found few methods like grep, map very userful that saves me from writing loops. I could relate them with grep, collect respectively as provided by Groovy, thought would share with you.

I will be taking examples with JSON objects say Student.
grep()

var students = [ {'id':1, 'name':'amit'},{'id':2, 'name':'ankit'}];
jQuery.grep(students,function(student){ return student.id>1});

//Output :  [{'id':2, 'name':'ankit'}]

jQuery.grep(students,function(student){ return student.id>1}, true) // invert the results

//Output : [ {'id':1, 'name':'amit'}]

map()

 var students = [ {'id':1, 'name':'amit'},{'id':2, 'name':'ankit'}];
jQuery.map(students,function(student){ return student.name=student.name.toUpperCase()});

//Output : ["AMIT", "ANKIT"]
//Updated students list :  [ {'id':1, 'name':'AMIT'},{'id':2, 'name':'ANKIT'}];

jQuery.map(students,function(student){ return student.greetings="HELLO " + student.name});

//Output : ["HELLO AMIT", "HELLO ANKIT"]
//Updated students list : [ {'id':1, 'name':'AMIT', 'greetings' : 'HELLO AMIT'},{'id':2, 'name':'ANKIT', 'greetings' : 'HELLO ANKIT'}]

Hope this helped.

~~Amit Jain~~
amit@intelligrape.com

  • Share/Bookmark
Tags: , ,

Asynchronous behavior of AJAX

Posted by Bhagwat Kumar on September 14th, 2010

Ajax (shorthand for Asynchronous JavaScript and XML) is used to retrieve data from the server asynchronously without interfering with the display and behavior of the existing page. Forgetting this asynchronous behavior will produce incorrect result if it depends on the response from Ajax call.

Lets take an example(I am using JQuery to illustrate the example). Here is a JavaScript function to perform server side check of the form. Depending on the response of Ajax call the function either submits the form or does nothing.

function submitForm(){
	var isFormValid=false;
	var dataToBeSent=$('form').serialize();
	$.get(url, dataToBeSent, function(result){
		isFormValid=result;
	})
	if(isFormValid){
		$('form').submit();
	}
}

The statement $('form').submit() will never be called irrespective of the result (AJAX call response). After executing $.get statement it will execute the next statement  if(isFormValid) without waiting for the statement isFormValid=result inside the callback function to be executed.

There exist a dirty solution for the problem : using JavaScript sleep API. But how long you are going to halt the execution of JavaScript code. You are back to the same problem of getting the incorrect behavior.

One good solution is to make the $.get call synchronous by making changes to the global AJAX configuration like :

$.ajaxSettings.async=false;

or using calls like :

$.ajax({type: "GET", url: url, data: dataToBeSent, success: function(){
		isFormValid=result;
	}
});

Now the if(isFormValid) statement will be executed only after the $.ajax statement has completed its execution. However this approach has its own drawback. Obvious one is the execution of JavaScript halts until it receives the response.

However the better solution  is to execute $('form').submit() inside the callback function like :

$('submitButton').click(function(){
	var isFormValid=false;
	var dataToBeSent=$('form').serialize();
	$.get(url, dataToBeSent, function(result){
		isFormValid=result;
	if(isFormValid){
		$('form').submit();
	}
	})
return false;  // Needless if the button is not a submit button
})

return false statement at the end of the function prevents the form from being submitted. Now the form submission code will be executed only after the response to $.get statement is true.

There exist JQuery plugins (e.g. JQuery validation plugin) for doing form validation in a better way where you get support for server side validation also. But the case discussed above was to make you understand the asynchronous behavior of AJAX calls.

Hope this helps you while using Ajax.  :)

Cheers,
~~Bhagwat Kumar~~
bhagwat(at)intelligrape(dot)com

http://www.intelligrape.com

  • Share/Bookmark

jQuery: Floating message box which disappears in few seconds

Posted by Amit Jain on September 14th, 2010

Hi Friends,

Recently in one of the project I was working on, had a long web page and updates used to happen only through ajax calls that means no page refresh. The status messages used to appear on the top of the page, the user had no way but to scroll up to see the status message. There we thought of using floating message that always appears on the top and floats as and when page is scrolled and also disappears itself after specified amount of time. I found one blog by Roshan that helped a lot, which I tweaked a little as given below.

CSS code to be added :

#message_box {
    position: absolute;
    top: 0;
    left: 0;
    z-index: 1000;
    background: #ffc;
    padding: 5px;
    border: 1px solid #CCCCCC;
    text-align: center;
    font-weight: bold;
    width: 99%;
}

Html code containing message : :-

<div id="message_box">Your message goes here</div>

Call setupMessageBox() when message is available.

<script type="text/javascript">
  var updateTimer = 0;
  function setupMessageBox(){
    showMessage(); //displays message on page load
    jQuery(window).scroll(function() {
       showMessage();
    });    
    clearTimeout(updateTimer);
    activateTimer();
  });
 
  function activateTimer() {
    updateTimer = setTimeout('jQuery("#message_box").remove()', 5000);
  }
 
  function showMessage(){
      jQuery('#message_box').animate({top:jQuery(window).scrollTop() + "px" }, {queue: false,duration:350});
  }
</script>

Hope this helped!

Cheers,
~~Amit Jain~~
amit@intelligrape.com

http://www.intelligrape.com

  • Share/Bookmark

JavaScript Profiling through Firebug’s Console API.

Posted by Chandan Luthra on August 16th, 2010

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?

Posted by Tarun Pareek on August 12th, 2010

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

Posted by Vishal Sahu on August 10th, 2010

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

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