jquery « Intelligrape Groovy & Grails Blogs

Posts Tagged ‘ jquery ’

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

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: , ,

jQuery : Chaining of your custom function calls

Friday, June 4th, 2010
Posted by Amit Jain

Hi Friends,

I always used to think how jQuery provides the chaining mechanism, must be something really complex so never cared to find it out. Though there was a desire to to use the same concept in my own custom javascript functions. Recently I realised how easy it is, so thought would share with you with the help of an example.

jQuery.fn.getStudents= function(count) {  //count is the parameter name and getStudents is the function name.
//write your code here
...
return myObject  //return is optional
});

Now we can access the above function using dot operator on jQuery Object.

jQuery("#myListId").getStudents(5);

Please make a note the object returned by the previous function is made available to the chained functions as “this” object, that is one of the reason chaining became so useful. So in the above function getStudents(), “this” object would refer to the object returned by jQuery(“#myListId”).

Remember, to have chaining upto multiple levels, it becomes the obligation for the calling function to must return an object/value to the chained function being called on it.

jQuery.fn.highlightNames= function() {
//write your code here
jQuery(this).find(...);
...
});

Now we can access the above function i.e highlightNames() using dot operator even on another function.

jQuery("#myListId").getStudents(5).highlightNames();

Here I didn’t have to passes the students object to highlightNames, as it was available as a “this” object.

Hope it helped!

~~Amit Jain~~
amit@intelligrape.com

http://www.intelligrape.com

  • Share/Bookmark

Monitoring ajax call response

Thursday, March 4th, 2010
Posted by Bhagwat Kumar

Recently I have faced a problem of monitoring all the ajax calls. Based on the response from server I have to perform some task depending on the contents of response. If the html response contains some text input field, the first text input field should be automatically focused otherwise leave the response as it is.

Here is the javascript code :

<span id="ajax_spinner" style="display:none"></span>
<script type="text/javascript">
            jQuery("#ajax_spinner").ajaxComplete(function(event, xhr, options)
            {
                var data = jQuery.httpData(xhr,options.dataType);
		/* 
                 Now data contains the responseText if the response type
		 is text/html or text/palin otherwise it is undefined.
                 */
                var inputFieldIndex=-1;
                try{
			/* try-catch because data may be undefined as mentioned above. */
			inputFieldIndex=data.indexOf("<input");
		}catch(err){}
                if(inputFieldIndex>-1){	
                   /* response contains input tag */
                    jQuery('input:text:visible[disabled=false]:first').focus();
                }
            });
 
          });</script>

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

Helpful links :-
http://api.jquery.com/ajaxComplete/

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

  • Share/Bookmark
Tags: ,

Identify merchant provider from the given credit card no.

Wednesday, November 4th, 2009
Posted by Amit Jain

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

Monday, October 12th, 2009
Posted by Bhagwat Kumar

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

Creating File Explorer with Context Menu using jQuery File Tree Plugin

Tuesday, May 26th, 2009
Posted by Bhagwat Kumar
You can create a customized, fully-interactive file tree using jQuery File Tree plugin Written by Cory S.N. LaViska. For a demo on File Explorer click here.

Here are the quick steps to implement it in your application. For advanced information please go to the plugin website where you can find the detailed description of this plugin as well as links to demo, download etc pages.

At first glance this seems to be very lengthy blog but when you start copying and pasting the code shown here into your application you will get this lengthy explanation very useful.

Here is a snapshot of what we are going to achieve in few minutes.

File Explorer with context menu

  1. Install jquery plugin

  2. jQuery File Tree requires jQuery 1.2 or above.If you have already installed this plugin then you can skip this step.
    To install jQuery plugin use the following command :

    grails install-plugin jquery

    To get the list of commands to manage plugins (eg. create, install, uninstall, list of plugins) use the following command :

    grails --help | grep plugin

  3. Download jQuery File Tree plugin files

  4. You can download the required files from the plugins website or Click here to download.

    Unzip the downloaded zip file. The unzipped folder ‘jqueryFileTree’ contains a folder ‘connector’ that you can safely delete because we will write our own connector specific to grails.

  5. place the unzipped folder into web-app folder

  6. Using operating system file explorer tool move/copy the unzipped folder ‘jqueryFileTree’ to the applications web-app folder. If you are not interested in such an easy step then you can move the jqueryFileTree.js file to web-app/js folder, jqueryFileTree.css file to web-app/css and all the files from jQueryFileTree/images to web-app/images folder and correspondingly change the reference to these files in gsp page we will be creating next. I assume you followed the easier way i.e. copied the entire folder into web-app folder.

  7. Decide the controller, action and gsp page

  8. Suppose we have a controller ‘FileBrowser’(…grails-app/controllers/FileBrowserController.groovy) and its ’showBrowser’ action renders the view (we call it : …/grails-app/views/FileBrowser/FileBrowser.gsp). The controller looks like

    class FileBrowserController {
    //...............
    def showBrowser = {
    //.................
    render( view : 'FileBrowser')
    }
    //................
    }

  9. Create gsp page and customize it

    Here is the contents of “/grails-app/views/FileBrowser/FileBrowser.gsp” file :

    <html>
    <head>
    <title>File Explorer</title>
    <script src=”${createLinkTo(dir: ‘js/jquery’, file: ‘jquery-1.3.2.js’)}” type=”text/javascript”></script>
    <link rel=”stylesheet” href=”${createLinkTo(dir: ‘jqueryFileTree’, file: ‘jqueryFileTree.css’)}”>
    <script src=”${createLinkTo(dir: ‘jqueryFileTree’, file: ‘jqueryFileTree.js’)}” type=”text/javascript”></script>
    <script type=”text/javascript”>

    function YourFunctionToProcessThisFilePath(file){
    alert(‘You selected : ‘+file);
    }

    $(document).ready(function() {
    $(‘#file_list’).fileTree({
    root:’/',    /*DESCRIPTION 1*/
    script: ‘generateFileList.gsp’,    /*DESCRIPTION 2*/
    expandSpeed: 1000,
    collapseSpeed: 1000,
    multiFolder: false
    }, function(file) {
    YourFunctionToProcessThisFilePath(file); /* DESCRIPTION 3*/
    });
    });
    </script>
    </head>
    <h1>File Explorer</h1>
    <body>
    <div id=”file_list”>    <!– DESCRIPTION #4 –>
    <%=”Empty”%>
    </div>
    </body>
    </html>

    • DESCRIPTION #1: absoulute path of the folder which will be treated as root level folder in our file explorer. There exists a potential for malicious individuals to be able to view your entire directory structure by spoofing the root parameter. However you can control this from the script file described in DESCRIPTION #2.
    • DESCRIPTION #2: connector file(server side script) that generates the list of files and subdirectories for the selected folder. This is a gsp file where you get the absolute path of the folder in dir attribute of params map for which the files and subfolders is to be found and output an unsorted list in the following format:
      We will create this gsp page parallel to FileBrowser.gsp i.e. …/grails-app/views/FileBrowser/generateFileList.gsp in Step 6. Later we will move this logic into an action and hence no need of connector script (see step 8).
    • DESCRIPTION #3: this javascript function is called with absolute path to the selectd file whenever a file is clicked in the file browser page.
    • DESCRIPTION #4: The id of the div tag is used in jQuery. So it must match at both places.
  10. Create connector script

  11. Here is the code for connector script "...grails-app/views/FileBrowser/generateFileList.gsp"

    <%
    String dir = params?.dir
    if (dir == null) {
        return;
    }
    /* you can put here your own custom check with dir variable to protect from malicious request.  */
    if(!dir.endsWith(File.separator)){
        dir+=File.separator
    }
    
    File f=new File(dir)
    if (f.exists()) {
        List<File> files=[]
    
        f.eachFile { File file->
            if(!file.hidden)
                files<<file
        }
    
        files.sort{File file-> file.name.toUpperCase()}
        StringBuffer output=new StringBuffer('<ul class="jqueryFileTree" style="display: none;">')
        // All dirs
        files.each{File file->
            if(file.directory){
                output.append("""<li class="directory collapsed"><a href="#" rel="${dir+file.name+File.separator}">${file.name}</a></li>""")
            }
        }
        // All files
        files.each{File file->
            if(file.file){
                int dotIndex = file.name.lastIndexOf('.');
                String ext = dotIndex > 0 ? file.name.substring(dotIndex + 1) : "";
                output.append("""<li class="file ext_${ext}"><a href="#" rel="${dir+file.name}">${file.name}</a></li>""");
            }
        }
        output.append("</ul>");
        println output.toString()
    }
    %>
    
  12. Test Your File Explorer

    It’s time to test your file explorer. If everything went perfectly then you have successfully created your file explorer. Type the url of the action responsible for rendering FileBrowser.gsp.You can also experiment with various Parameters that are passed as an object to the fileTree() function in FileBrowser.gsp. List of Valid options can be found at the pluging website under ‘Configuring the File Tree’ heading.

  13. Moving the connector script  to an action of the controller

    Here is the modified controller FileBrowserController having an action generateFileList. This contains the same code as in generateFileList with few new statements appended and obviously <% and %> has been removed.The modified lines has been shown in different color.

    class FileBrowserController {
    //……………
    def showBrowser = {
    //……………..
    render( view : ‘FileBrowser’)
    }
    def generateFileList={
    String dir = params?.dir
    if (dir == null) {
    return;
    }
    /* you can put here your own custom check with dir variable to protect from malicious request.  */
    if(!dir.endsWith(File.separator)){
    dir+=File.separator
    }

    File f=new File(dir)
    if (f.exists()) {
    List<File> files=[]

    f.eachFile { File file->
    if(!file.hidden)
    files<<file
    }

    files.sort{File file->
    file.name.toUpperCase()
    }

    StringBuffer output=new StringBuffer(‘<ul class=”jqueryFileTree” style=”display: none;”>’)
    // All dirs
    files.each{File file->
    if(file.directory){
    output.append(“”"<li class=”directory collapsed”><a href=”#” rel=”${dir+file.name+File.separator}”>${file.name}</a></li>”"”)
    }
    }
    // All files
    files.each{File file->
    if(file.file){
    int dotIndex = file.name.lastIndexOf(‘.’)
    String ext = dotIndex > 0 ? file.name.substring(dotIndex + 1) : “”
    output.append(“”"<li class=”file ext_${ext}” id=”${dir+file.name}”><a href=”#” rel=”${dir+file.name}”>${file.name}</a></li>”"”)
    }
    }
    output.append(“</ul>”)
    OutputStream out = response.getOutputStream()
    out.write (output.toString().getBytes())
    out.flush()
    out.close()

    }
    }
    //…………….
    }

  14. Making changes to FileBrowser.gsp to use generateFileList action instead of generateFileList.gsp file

    Here are the modified lines of FileBrowser.gsp file (Modified lines shown in different color ) :

    $(document).ready(function() {
    $(‘#file_list’).fileTree({
    root:’/',
    script: “${createLink(action:’generateFileList’)}”, /* you can also explicitly specify the controller */
    expandSpeed: 1000,
    collapseSpeed: 1000,

    After this change, you can test your File Explorer and if everything works perfectly, you can safely delete the file generateFileList.gsp.

  15. Forwarding to an action when a file is clicked

    To do so we will modify FileBrowser.gsp page to include a form and a hidden field for absolute path of the selected file.
    The modified FileBrowser.gsp(with modified lines shown in different color) is now :

    <html>
    <head>
    <title>File Explorer</title>
    <script src=”${createLinkTo(dir: ‘js/jquery’, file: ‘jquery-1.3.2.js’)}” type=”text/javascript”></script>
    <link rel=”stylesheet” href=”${createLinkTo(dir: ‘jqueryFileTree’, file: ‘jqueryFileTree.css’)}”>
    <script src=”${createLinkTo(dir: ‘jqueryFileTree’, file: ‘jqueryFileTree.js’)}” type=”text/javascript”></script>
    <script type=”text/javascript”>

    function YourFunctionToProcessThisFilePath(file){
    //        alert(‘You selected : ‘+file);
    document.getElementById(’selectedFile’).value = file
    document.getElementById(‘fileBrowserForm’).submit()
    }

    $(document).ready(function() {
    $(‘#file_list’).fileTree({
    root:’/',    /*DESCRIPTION 1*/
    script: “${createLink(action:’generateFileList’)}”, //’generateFileList.gsp’,
    expandSpeed: 1000,
    collapseSpeed: 1000,
    multiFolder: false
    }, function(file) {
    YourFunctionToProcessThisFilePath(file); /* DESCRIPTION 3 */
    });
    });
    </script>
    </head>
    <h1>File Explorer</h1>
    <body>
    <div id=”file_list”>    <!– DESCRIPTION #4 –>
    <%=”Empty”%>
    </div>
    <g:form name=”fileBrowserForm” action=”processThisFile” method=”post”>
    <g:hiddenField name=”selectedFile” />
    </g:form>
    </body>
    </html>

    Now add an action ‘processThisFile’ or whatever you have used as forms action in FileBrowser.gsp file. Here is the modified FileBrowserController :

    class FileBrowserController {
    //……………
    def processThisFile={
    println params.selectedFile
    render(params.selectedFile)
    }

    //…………….
    }

  16. Installing the plugin for Context Menu(Right Click)

    Now we are going to add Context Menu functionality to our File Explorer. For this purpose we will be using one more plugin jQuery Context Menu Plugin Written by Cory S.N. LaViska(same author has written jQuery File Tree plugin). For advanced details go to the plugin website where you can see a demo as well as download necessary files to use this plugin. Click here to download the plugin.

    After you have downloaded the zip file, unzip it and copy it in applications web-app folder as you did for jQuery File Tree Plugin in Step 3.

  17. Create context menu options by Modifying FileBrowser.gsp file

    create a list in FileBrowser.gsp that will be the markup for your context menu:
    Actions are specified in the href attribute, preceeded by a # symbol. When selected, this is what will be passed back to the action parameter in the callback. You can add class attributes to the list items to assist with styling, but they have no functional meaning. Thus, class names do not have to correspond with actions.

    Let’s create a contextMenu (UL with id myFolderMenu) with four options cut, paste, rename and delete also a separator beteween paste and rename option which is displayed whenever a folder is right-clicked. When you click an option from the displayed context menu the javascript function HandleFolderContextMenu is called with parameters action and folderPath. action contains the href attribute excluding # character of the selected context menu option and folderPath contains the absolute path of the selected folder i.e. on which it was right clicked.

    Similarly a contextMenu(UL with id myFileMenu) with two options Open… and Properties which is displayed whenever a file is right-clicked has been created. Like Context Menu for folders, this time HandleFileContextMenu javascript function is called with action and filePath parameters.

    You can follow the similar steps as described in Step 10 to forward request to an action where it will be processed depending on the action and absolute path to the selected file or folder.

    <html>
    <head>
    <title>File Explorer</title>
    <script src=”${createLinkTo(dir: ‘js/jquery’, file: ‘jquery-1.3.2.js’)}” type=”text/javascript”></script>

    <link rel=”stylesheet” href=”${createLinkTo(dir: ‘jqueryFileTree’, file: ‘jqueryFileTree.css’)}”>
    <script src=”${createLinkTo(dir: ‘jqueryFileTree’, file: ‘jqueryFileTree.js’)}” type=”text/javascript”></script>

    <link rel=”stylesheet” href=”${createLinkTo(dir: ‘jquery.contextMenu’, file: ‘jquery.contextMenu.css’)}”>
    <script src=”${createLinkTo(dir: ‘jquery.contextMenu’, file: ‘jquery.contextMenu.js’)}” type=”text/javascript”></script>

    <script type=”text/javascript”>
    function HandleFolderContextMenu(action, folderPath){
    alert(action+’\n\n Folder Path : ‘+folderPath);
    }
    function HandleFileContextMenu(action, filePath){
    alert(action+’\n\n File Path : ‘+filePath);
    }

    function showMenu(){
    $(‘.directory>a’).contextMenu({
    menu: ‘myFolderMenu’
    },
    function(action, el, pos) {
    var folderPath=$(el).attr(‘rel’);
    HandleFolderContextMenu(action, folderPath);
    }
    );
    $(‘.file>a’).contextMenu({
    menu: ‘myFileMenu’
    },
    function(action, el, pos) {
    var filePath=$(el).attr(‘rel’);
    HandleFileContextMenu(action, filePath);
    }
    );
    }

    </script>

    <script type=”text/javascript”>

    function YourFunctionToProcessThisFilePath(file){
    //        alert(‘You selected : ‘+file);
    document.getElementById(’selectedFile’).value = file
    document.getElementById(‘fileBrowserForm’).submit()
    }

    $(document).ready(function() {
    $(‘#file_list’).fileTree({
    root:’/',    /*DESCRIPTION 1*/
    script: “${createLink(action:’generateFileList’)}”, //’generateFileList.gsp’,
    expandSpeed: 1000,
    collapseSpeed: 1000,
    multiFolder: false
    }, function(file) {
    YourFunctionToProcessThisFilePath(file); /* DESCRIPTION 3 */
    });
    });
    </script>
    </head>
    <h1>File Explorer</h1>
    <body>
    <div id=”file_list”>    <!– DESCRIPTION #4 –>
    <%=”Empty”%>
    </div>
    <g:form name=”fileBrowserForm” action=”processThisFile” method=”post”>
    <g:hiddenField name=”selectedFile” />
    </g:form>
    <ul id=”myFolderMenu” class=”contextMenu”>
    <li class=”copy”><a href=”#copy”>Copy</a></li>
    <li class=”paste”><a href=”#paste”>Paste</a></li>
    <li class=”separator rename”><a href=”#rename”>Rename</a></li>
    <li class=”deleteFolder”><a href=”#deleteFolder”>Delete</a></li>
    </ul>
    <ul id=”myFileMenu” class=”contextMenu”>
    <li class=”open”><a href=”#open”>Open…</a></li>
    <li class=”properties”><a href=”#properties”>Properties</a></li>
    </ul>
    </body>
    </html>

    Finally modify generateFileList action by adding a statement output.append(““) as shown below the modified lines of generateFileList action to get the changes made to FileBrowser.gsp to work. It just calls the showMenu javascript function defined in FileBrowser.gsp which in turn enables the context menu for the explored folder.

    def generateFileList={
    //…………………..
    output.append(“</ul>”)
    output.append(“<script>showMenu(); </script>”)
    OutputStream out = response.getOutputStream()
    out.write (output.toString().getBytes())
    //…………………..
    }

Hope this helps you guys in creating file explorer with context menu.

Bhagwat Kumar
bhagwat@intelligrape.com

  • Share/Bookmark

How to use $.getJSON() method of jQuery with grails?

Monday, March 2nd, 2009
Posted by Chandan Luthra

How to use $.getJSON() method of jQuery with grails?

Retriving a JSON string from Grails is very easy. You have to just write the following in your controller’s action

Let me explain you with an example of populating a HTML table using JSON response:
In this example, we have table with columns – name,address and gender. We want the table to be populated without doing a full page refresh, using an Ajax call.

Domain Class:

class MyDomain {
    String name
    String address
    String gender
}

Controller Class :

class MyController {
   def someaction = {
      List myDomains = MyDomain.findAllByGender(params.gender)
      <em>/*Let say 5 objects are retrieved*/</em>
      render myDomains as JSON
   }
}

The above code in action will render a JSON string in the following format:

[
{
"name" : "John",
"address" : "New York",
"gender" : "Male"
},
{
"name" : "Rob",
"address" : "Indonasia",
"gender" : "Male"
},
{
"name" : "Shayam",
"address" : "New Delhi",
"gender" : "Male"
},
{
"name" : "Chang",
"address" : "Thailand",
"gender" : "Male"
},
{
"name" : "Ali",
"address" : "London",
"gender" : "Male"
}
]

following script would be writtent on the client Side (in the GSP):

<script>
$.document.ready(function(){
$('#someid').click(function(){
<strong>$.getJSON</strong>("${createLink(controller:'my',action:'someaction')}",{gender:'Male', ajax: 'true'}, function(myDomains){
var myHTMLString = ''
for(var i = 0 ; i < myDomains.length ; i++)
{
myHTMLString = myHTMLString + '<tr><td>' + myDomains[i].name + '</td>'
myHTMLString = myHTMLString + '<tr><td>' + myDomains[i].address + '</td>'
myHTMLString = myHTMLString + '<tr><td>' + myDomains[i].gender + '</td></tr>'
}
$('table#mytable').html(myHTMLString)
})
})
})
</script>

The HTML code would be like this :

<div id=”someid”>
Click for JSON Response
</div>
<table id=”mytable”>
<!–empty table –>
</table>

When you click on the displayed text the html page would become like following:

<div id="someid">
Click for JSON Response
</div>
<table id="mytable">
<tr>
<td>John</td>
<td>New York</td>
<td>Male</td>
</tr>
<tr>
<td>Rob</td>
<td>Indonasia</td>
<td>Male</td>
</tr>
<tr>
<td>Shayam</td>
<td>New Delhi</td>
<td>Male</td>
</tr>
<tr>
<td>Chang</td>
<td>Thailand</td>
<td>Male</td>
</tr>
<tr>
<td>Ali</td>
<td>London</td>
<td>Male</td>
</tr>
</table>

any kind of suggestions and comments are welcome……

Regards,
Chandan Luthra

http://www.IntelliGrape.com

  • Share/Bookmark

Using jQuery and Grails to create chained selects / drop-downs

Thursday, July 17th, 2008
Posted by admin

In web application development, use of frameworks has become essential . One of those frameworks which help us in making things simpler and life easy is jQuery.

Why jQuery ?

  • Fully Documented
  • Great Community
  • Tons of plugins
  • Small size(14kb)
  • Everything works in IE 6+,Firefox,Safari 2+,and Opera 9+

jQquery is a very efficient framework which helps us in developing many things in a much easier way than they would be without using any framework.

At IntelliGrape we are using Grails and jQuery on a project.

In this blog, I want to share one of my experiences that I had met in this course of time. A series of mails/questions in Grails mailing list on creating chained selects/drop-downs prompted me to write this blog; since I had already done this.

Chain select basically means populating the next drop-down on the basis of what you select in the present drop-down.

In this example, we have two drop-downs – manufacturer and model. We want the model drop-down to be populated on the basis of what the user selects in the manufacturer drop-down, without doing a full page refresh, using an Ajax call.

Here are my classes, not the whole class but a part of the class

Vehicle Class

public  class Vehicle {Manufacturer manufacturer

Model model}

The Manufacturer and model classes look like this

Manufacturer Class

public class Manufacturer {
  String manufacturerName
  static belongsTo = Vehicle
  static hasMany = [models: Model]
}

Model Class

public class Model {
  String modelName
  static belongsTo = Manufacturer
}

For this the vehicleCreate.gsp should look like this

/vehicle/create.gsp

            Home
            Vehicle List

Create Vehicle

${flash.message}
 
* id="vehicleManufacturerDropDown" optionKey="id" from="${VehicleManufacturer.list()}" name="vehicleManufacturerDropDown" value="">
* id="model" optionKey="id" from="${VehicleModel.list()}" name="model" value="">
$(document).ready(function() { $("#vehicleManufacturerDropDown").change(function() { $.ajax({ url: "/ChainDropDown/vehicle/manufacturerSelected", data: "id=" + this.value, cache: false, success: function(html) { $("#models").html(html); } }); }); });

Now we will look at how this chained selection works using jQuery.

Now what all we are left-out with is handling this event in the VehicleController which is as simple as any other controller action. Just add manufacturerSelected action in the controller and we are done!VehicleController

class VehicleController {
  def manufacturerSelected = {
    def manufacturer = VehicleManufacturer.findById(params.id)
    render g.select(optionKey: 'id', from: manufacturer.models, id: 'model', name: "model")
  }
}

You can download the complete source code for a working sample app with the examples used in this blog.

Hope this helps somebody.

Pradeep Garikipati

  • Share/Bookmark