jquery « Intelligrape Groovy & Grails Blogs

Posts Tagged ‘ jquery ’

Accessing remote data through cross-domain ajax call in jquery

Posted by on September 24th, 2012

While developing a mobile app using phonegap ( or otherwise also :) ), we can access remotely hosted mysql database using jquery ajax calls. But this interaction between jquery and mysql database cannot happen directly. We will need to specify a server side script(in PHP terminology) or a controller action(in Grails Terminology) that will fetch data from the mysql database and serve it to the jquery call. Jquery will simply make a cross-domain ajax request to the server side script and the script will send requested data as response.

For a successful cross-domain communication, we need to use dataType “jsonp” in jquery ajax call.
JSONP or “JSON with padding” is a complement to the base JSON data format which provides a method to request data from a server in a different domain, something prohibited by typical web browsers.

When we specify dataType as jsonp, a “callback” parameter is appended to the request url and jquery creates a function whose name is the value of callback parameter. On server side, the script receives the “callback” parameter value(which is name of the function) and sends the data as argument to that function. Alternatively, that data is also available in the success function of jquery.

Jquery Code :

	    function crossDomainCall(url,data,fnSuccess,fnError){
            $.ajax({
                type:'POST',
                url:url,
                contentType:"application/json",
                dataType:'jsonp',
                crossDomain:true,
                data:data,
                success:fnSuccess,
                error: fnError
            });
        }
	
        function authenticateUser(username, password) {
            var url = 'http://www.example.com/user/authenticate';
            var data={username:username, password:password};
            var fnSuccess=function (dataReceived) {
		    if(dataReceived) {
			    alert("Welcome "+dataReceived.name);
		    }else{
			    alert("Authentication failed")
		    }
            };

            var fnError=function (e) {
                alert(e);
            };
            crossDomainCall(url,data,fnSuccess,fnError);
        }

Server side code :

 
	def authenticate(String username, String password){
        	User user=User.findByNameAndPassword(username,password)
		    if (user) {
		        render "${params.callback}(${user as JSON})"
		    }else{
		        render "${params.callback}(null)"
		    }
    	}

Here, the function name is received from params.callback and data is sent in json form as an argument to the function.

Hope it helps.
Have Fun :)

jQuery : Associate data with dom element

Posted by on September 21st, 2012

There are times when we need to associate data with the DOM element say td, li, div etc. I used to sometimes provide attribute ‘rel’ to html tag, then access it using $(‘divId’).attr(‘rel’). This worked when we want to associate only one property, but doesn’t work so well when there are multiple properties to be associated with the same element. And I personally never liked this approach as there was no name given to the type of data attached.

Recently I found that jQuery provides a method called data(), which can be used to associate multiple data with the same element. Lets take a look at the example given below :

<div id='studentDetail' data-age='24' data-name='amit'>
......
</div>

<script type="text/javascript">

 $('#studentDetail').data('age')  // output : 24
 $('#studentDetail').data('name')  // output : amit

 $('#studentDetail').data('course', 'MCA')  // Associate new data to the element
 $('#studentDetail').data('course')  // output : MCA

 $('#studentDetail').data('course-duration', '3 Years')  // Associate new data to the element
 $('#studentDetail').data('course-duration')  // output : 3 Years
</script>

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

Tags: , ,

Implement Ajax call in Grails web-flow

Posted by on September 16th, 2012

In one of my recent project, i want to use grails web-flow with ajax call. It’s very easy to implement the web-flow with ajax call. Grails web-flow always track the actions on the basis of eventId & flow execution key. So, to implement ajax call in web-flow, we have to pass the event id & flow execution key.

1. Let us assume, we have the following web- flow code in grails.

def stepFlow ={
first{
action{
code.....
}on ("success"){code...}.to("second")
}
second{
on("third"){
}.to("fourth")
}
fourth();
}

In this case, step is web flow name, for each call we have to pass step as request uri . First, second and third are events, events are always tracked through flow execution key

2. We want to call the event third through ajax call. For this we have to write the following code in ajax.

function callAjaxFunctionInWebFlow(eventType,flowExecutionKey){

$.ajax({
url:"project-name/step",
type:'POST',
data:'_eventId=' + eventType + '&execution=' + flowExecutionKey,
success:function (result) {

},
error:function (jqXHR, textStatus, errorThrown) {
}
})
}

3. To call this function from GSP we have to write the following code.

<a href='javascript:void(0)' onclick="callAjaxFunctionInWebFlow('third','${request.flowExecutionKey}')">Click</a>

In this function callAjaxFunctionInWebFlow(‘third’,'${request.flowExecutionKey}’) third is eventId that we want to call, request.flowExecutionKey gives the current execution key that need to pass through each ajax call.

Hope it will help.

Thanks & Regards,

Mohit Garg

mohit@intelligrape.com

@gargmohit143Thanks & Regards,
Mohit Garg
mohit@intelligrape.com
@gargmohit143

Posted in Grails, Groovy

Getting started with jQuery Mobile

Posted by on September 15th, 2012

JQuery mobile provides set of features which are supported on almost all smartphones such as touch UI, ajax navigation, animated page transitions. Building jQuery mobile page is very simple, here’s how:

  1. A jQuery Mobile site must start with an HTML5 ‘doctype’ to take full advantage of all of the framework’s features.
  2. First of all you need jQuery, jQuery mobile, mobile theme stylesheets from CDN.
  3. Reference all styles & scripts in the head of page.
  4. <!DOCTYPE html>
    <html>
    <head>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Page Title</title>
    <link rel="stylesheet" href="css/jquery.mobile-1.1.1.css"/>
    <script src="js/jquery-1.8.0.min.js"></script>
    <script src="js/jquery.mobile-1.1.1.min.js"></script>
    </head>
  5. A meta viewport tag in the head sets the screen width to the pixel width of the device.
  6. Inside body of html page a div with data-role of page is used as a wrapper for whole page.
  7. For header bar add a div with data-role of header.
  8. For content region add a div with a data-role of content & add content between this div.
  9. <body>
    <div data-role="page">
            <div data-role="header">
                    Header
            </div>
            <div data-role="content">
                    <p>This is jquery mobile test page</p>
            </div>
            <div data-role="footer">
                   ©intelligrape
            </div>
    </div>
    </body>
    
  10. There are many features provided by jQuery mobile. Here i am explaining one of them which is list. For list, simply add ul tag with attribute data-role of listview between

    .
  11. To make it look like an inset module add an attribute data-inset=”true”.
  12. For dynamic search filter just add another attribute data-filter=”true”.
  13. <div data-role="content">
        <ul data-role="listview" data-inset="true" data-filter="true">
              <li>Blue</li>
              <li>Black</li>
              <li>Green</li>
              <li>Yellow</li>
              <li>White</li>
        </ul>
    </div>
    

Smart way of focussing a text input on page load for heavy pages

Posted by on August 27th, 2012

Let’s say you have a login page which contains a form with username and password field in it (offcourse, along with a submit button).
Let’s say being much focussed towards user convenience with the user interface, you want to put the cursor in the username field of your form as soon as the page loads. You just go ahead and write-

$(document).ready(function{
	$("#username").focus();
});

And you think, voila, its done. That was pretty easy.
This code is good enough for small to average sized pages. However, if the html page is huge or if the user is on a slow connection, you have just planted a source of big frustation for him.

You might have fallen into a scenario, where you need to enter username and password to log in. You just go ahead and type your username, press tab to switch to password field and start typing and in the halfway, the cursor went back to the username field and you end up typing remaining half of your password in the username field. Annoying isn’t it? This keeps on happening with me when i try to log in to my gmail account, and I hate google for this(I hope they are not reading my blog). But to your surprise, the jquery code written at the beginning of the blog is the real culprit!

What’s happening here is, the user see and start typing into the username field before the entire page is loaded(remember, the page may contain heavy images and text fields are loaded and become visible to user much before than the images). When the entire page is loaded, $(“#username”).focus(); is fired and the cursor is put into the username field.

There are two ways to deal with this situation.

1. Don’t wait till the entire page loads. Use inline javascript to put the cusor in username field as soon as the field is loaded.

<input name="username" id="username" type="text"/>
<script type=text/javascript>
	$("#username").focus()
</script>

2. If you want to stick with $(document).ready(), you can take the following approach.

$(document).ready(function(){
	var $username=$("#username");
	if($username.val()==''){
		$username.focus()
	}
});

Hope it helps and saves your users from a lot frustation.

Raj Gupta
raj.gupta@intelligrape.com

Replace All using JQuery and Regex

Posted by on August 24th, 2012

I recently found out that use of Regex with jQuery and replace function can turn out to be a very powerful tool for replacing/loading data in html dynamically

The use of replace is made like

var a = "Some text here text";
a=a.replace(/text/g,"one")

This will replace all “text” with “one”

Now imagine how good it would be if we could replace the part of html like “##title##” with a title’s value in a JSON.
We would be able to replace/load an entire html code dynamically by merely sending a JSON (or a list of JSON) that would replace the content of HTML in javascript.

Let us consider that we have a html code which is somethinng like:

<a title='##title##' onclick='showRecipeDetail(\"##friendlyUrl##\", this)'> <img src=\"##imageUrl##\" height='75' width='75' /><div class='recipeTitle'>##title##</div></a>

And we want to load this html with JSON content:

{{title:"abc", friendlyUrl:"xyz", imageUrl:"123"},{title:"pqr", friendlyUrl:"stu", imageUrl:"456"}}

What we will do is that we will identified the values to be replaced by using regex and then replaced all of them using replace function. For eg.:

var data= [{title:"abc", friendlyUrl:"xyz", imageUrl:"123"},{title:"pqr", friendlyUrl:"stu", imageUrl:"456"}]
var HTML_Template = "<a title='##title##' onclick='showRecipeDetail(\"##friendlyUrl##\", this)'> <img src=\"##imageUrl##\" height='75' width='75' /><div class='recipeTitle'>##title##</div></a>";
jQuery(data).each(function(index, recipe) {
			var html = HTML_Template;
			jQuery.each(recipe, function(key, value){
				var regExp = new RegExp("##" + key + "##", 'g');
				html = html.replace(regExp, value)
			});
        });

And hence we will have a our html replaced by merely few line of javascript code and a list of JSON (which we might be getting from ajax responce).

Hope this blog was helpful to you.. :)

Thanks and Regard,
Gaurav Sharma
(gauravs@intelligrape.com)

JQuery : create URL query string from JSON/Array

Posted by on May 4th, 2011

Hi Friends,
(more…)

File Uploading using plupload plugin of jquery.

Posted by 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

JQuery script to put focus on first field of any page

Posted by 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

Jquery : map and grep functions

Posted by 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

Tags: , ,