jquery « Intelligrape Groovy & Grails Blogs

Posts Tagged ‘ jquery ’

JQuery : create URL query string from JSON/Array

Posted by Amit Jain on May 4th, 2011

Hi Friends,
(more…)

  • Share/Bookmark

File Uploading using plupload plugin of jquery.

Posted by Anuj Aneja on February 14th, 2011

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

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

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

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

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

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

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

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

        });

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

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

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

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

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

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

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

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

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

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

Hope it help you guys! Cheer! :)

Anuj Aneja

http://www.Intelligrape.com

  • Share/Bookmark

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

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

jQuery Alert Message without using traditional javascript alert-box.

Posted by Salil on June 14th, 2010

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

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

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

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

Cheers!!
Salil Kalia



  • Share/Bookmark

JQuery: Send JSON Objects with an ajax request

Posted by Amit Jain on June 11th, 2010

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

Posted by Amit Jain on June 4th, 2010

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

Posted by Bhagwat Kumar on March 4th, 2010

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