Showing posts with label Jquery. Show all posts
Showing posts with label Jquery. Show all posts

Monday, June 27, 2016

Pagination using JSON + Jquery

Following is an example of Pagination using JSON and Jquery.

I need to paginate the table on my HTML page using Jquery. Following example illustrates how it can be done. The method paginateJSON creates a paginated table:

paginateJSON(empdata, tableId, createTable, createHeader);

Parameters:
  • empdata - the JSON object with list ob objects i.e. i our case its Employee records.
  • tableId - Table ID attribute
  • createTable - Set to true if table has to be created dynamically from JSON object provided i.e. Employee Data.
  • createHeader - True if the first object or row in JSON Data contains Header column names.

If Table exists call the following 
  • paginateJSON(empdata, "empDataTable", false, false);
else
  • paginateJSON(empdata, "empDataTable", true, true);

  • HTML 
Sample empDataTable to be paginated:


<table id="empDataTable">
<thead>
<tr>
<th>EMPID</th>
<th>NAME</th>
<th>ADDRESS</th>
</tr>
</thead>
<tbody>
<tr style="display: block;">
<td>1</td>
<td>John</td>
<td>1229,Wison Ave, Chicago, IL 60678</td>
</tr>
<tr style="display: block;">
<td>2</td>
<td>Mike</td>
<td>350 5th Ave, New York, NY 10118</td>
</tr>
<tr style="display: block;">
<td>3</td>
<td>Tommy</td>
<td>861 Milwaukee Ave, Chicago IL 60640</td>
</tr>
<tr style="display: block;">
<td>4</td>
<td>Jackson</td>
<td>738 Ashland Ave, Chicago IL 60678</td>
</tr>
<tr style="display: block;">
<td>5</td>
<td>Wilson</td>
<td>566 34th Ave, New York, NY 10118</td>
</tr>
<tr style="display: none;">
<td>6</td>
<td>Eric</td>
<td>1226 Grand St, Chicago IL 60611</td>
</tr>
<tr style="display: none;">
<td>7</td>
<td>Nate</td>
<td>350 5th Ave, New York, NY 10118</td>
</tr>
<tr style="display: none;">
<td>8</td>
<td>Julie</td>
<td>1112 York Rd, Chicago IL 60678</td>
</tr>
<tr style="display: none;">
<td>9</td>
<td>Monica</td>
<td>1514 Wilson St, Chicago IL 60678</td>
</tr>
</tbody>
</table>


  • Java Script

<script>

// Sample JSON Object empdata
       //For each item in our JSON, add a table row and cells to the content string
var empdata = [ {
empid : 'EMPID',
name : 'NAME',
address : 'ADDRESS'
}, {
empid : 1,
name : 'John',
address : '1229,Wison Ave, Chicago, IL 60678'
}, {
empid : 2,
name : 'Mike',
address : '350 5th Ave, New York, NY 10118'
}, {
empid : 3,
name : 'Tommy',
address : '861 Milwaukee Ave, Chicago IL 60640'
}, {
empid : 4,
name : 'Jackson',
address : '738 Ashland Ave, Chicago IL 60678'
}, {
empid : 5,
name : 'Wilson',
address : '566 34th Ave, New York, NY 10118'
}, {
empid : 6,
name : 'Eric',
address : '1226 Grand St, Chicago IL 60611'
}, {
empid : 7,
name : 'Nate',
address : '350 5th Ave, New York, NY 10118'
}, {
empid : 8,
name : 'Julie',
address : '1112 York Rd, Chicago IL 60678'
}, {
empid : 9,
name : 'Monica',
address : '1514 Wilson St, Chicago IL 60678'
}, ];


  • Making a call to paginate method from jquery ready() method.

$(document).ready(function() {

paginateJSON(empdata, "empDataTable", true, true);

});



  •  required Jquery variables

var pgnavDatatable;
var pgnavTotalItems = 0;
var pgnavItemsPerPage = 5;
var pgnavTotalPages = 0;
var pgnavFrom = 0;
var pgnavTo = 0;

/**
* paginateJSON method creates a table from the JSON object passed.
*
* pdata - JSON object containing data to be dynamically added to table.
* id - id attribute of the table.
* createTable - (true/false): If true creates table else assumes table exists in page.
* createHeader - (true/false): If true, creates head row for the table using first row to get header names.
*
*
*/
function paginateJSON(pdata, tableid, createTable, createHeader) {
pgnavTotalItems = pdata.length;
pgnavTotalPages = Math.ceil(pgnavTotalItems / pgnavItemsPerPage);

//drawTable(pdata, tableid, createTable, createHeader);
pgnavDatatable = $("#" + tableid);

/**
* Create a Div for pagination controls.
* Div contains two hidden fields i.e. currentPage and itemsPerPage.
*/
$('body')
.append(
'<div class=controls></div><input id=current_page type=hidden><input id=itemsPerPage type=hidden>');
$('#current_page').val(0);
$('#itemsPerPage').val(pgnavItemsPerPage);

var pgnavBlock = '<a class="prev" onclick="navPrevious()">Prev</a>';
var current_link = 0;
while (pgnavTotalPages > current_link) {
pgnavBlock += '<a class="page" onclick="navigateTo(' + current_link
+ ')" longdesc="' + current_link + '">'
+ (current_link + 1) + '</a>';
current_link++;
}
pgnavBlock += '<a class="next" onclick="navNext()">Next</a>';

$('.controls').html(pgnavBlock);
$('.controls .page:first').addClass('active');

pgnavDatatable.children('tbody').children().css('display', 'none');
pgnavDatatable.children('tbody').children().slice(0, pgnavItemsPerPage)
.css('display', '');
}

function navigateTo(pageNumber) {
var itemsPerPage = parseInt($('#pgnavItemsPerPage').val(), 0);

start_from = pageNumber * pgnavItemsPerPage;

end_on = start_from + pgnavItemsPerPage;

pgnavDatatable.children('tbody').children().css('display', 'none')
.slice(start_from, end_on).css('display', '');

$('.page[longdesc=' + pageNumber + ']').addClass('active').siblings(
'.active').removeClass('active');

$('#current_page').val(pageNumber);
}

function navPrevious() {
new_page = parseInt($('#current_page').val(), 0) - 1;
//if there is an item before the current active link run the function
if ($('.active').prev('.page').length == true) {
navigateTo(new_page);
}
}

function navNext() {
new_page = parseInt($('#current_page').val(), 0) + 1;
//if there is an item after the current active link run the function
if ($('.active').next('.page').length == true) {
navigateTo(new_page);
}
}

function drawTable(data, tableid, createTable, createHeader) {

if (data == null || data == 'undefined') {
return;
}
if (createTable) {
pgnavDatatable = $("<table id='" + tableid + "'></table>");
} else {
pgnavDatatable = $("#" + tableid);
}
var tablehead = $("<thead />");
var tablebody = $("<tbody />");
for (var i = 0; i < data.length; i++) {
var datarow = $("<tr />");
if (createHeader && i == 0) {
datarow.append($("<th>" + data[i].empid + "</th>"));
datarow.append($("<th>" + data[i].name + "</th>"));
datarow.append($("<th>" + data[i].address + "</th>"));
tablehead.append(datarow);

} else {
datarow.append($("<td>" + data[i].empid + "</td>"));
datarow.append($("<td>" + data[i].name + "</td>"));
datarow.append($("<td>" + data[i].address + "</td>"));
tablebody.append(datarow);
}
}
pgnavDatatable.append(tablehead);
pgnavDatatable.append(tablebody);

if (createTable) {
$('body').append(pgnavDatatable);
}
}
</script>


The above code can be tested at following jsfiddle link. Suggestions are welcome.

Pagination Example using Jquery and JSON

Tuesday, October 20, 2015

No converter found for return value of type: class java.util.ArrayList

I am testing a Spring MVC application , I am calling a database service which returns an ArrayList. I want to return this ArrayList as a Json response to my Jsp, where I am going to iterate through it and render search results through jquery.

 @RequestMapping(value = "/web/getprofiles", method = RequestMethod.GET)
    public @ResponseBody
    List getProfiles(HttpServletRequest request) {
        ArrayList<SearchDO> searchResults = profileService.getProfileSearch();
     return searchResults;

    }

Getting following exception while returning the ArrayList from Controller method :

Oct 20, 2015 10:45:20 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [appServlet] in context with path [/web] threw exception [Request processing failed; nested exception is java.lang.IllegalArgumentException: No converter found for return value of type: class java.util.ArrayList] with root cause
java.lang.IllegalArgumentException: No converter found for return value of type: class java.util.ArrayList
at org.springframework.util.Assert.isTrue(Assert.java:68)
at org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:124)

I am running this application on tomcat 7.0 with jdk 1.8 and Spring version 4.2.1.RELEASE.

Fix:

The exception here indicates that spring can not find a suitable converter to return ArrayList as a Json object as expected. To resolve this configure the resource resolver in your spring configuration xml.
Make you have specified <annotation-driven /> in spring configuration.



Spring configuration xml

          

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
<!-- Enables the Spring MVC @Controller programming model -->
<annotation-driven />

<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />

<context:component-scan base-package="com.testweb.controllers" />

<beans:bean
class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
    <beans:property name="useNotAcceptableStatusCode"
        value="false" />
    <beans:property name="contentNegotiationManager">
        <beans:bean
            class="org.springframework.web.accept.ContentNegotiationManager">
            <beans:constructor-arg>
                <beans:bean
                    class="org.springframework.web.accept.PathExtensionContentNegotiationStrategy">
                    <beans:constructor-arg>
                        <beans:map>
                            <beans:entry key="html" value="text/html" />
                            <beans:entry key="json" value="application/json" />
                        </beans:map>
                    </beans:constructor-arg>
                </beans:bean>
            </beans:constructor-arg>
        </beans:bean>
    </beans:property>

    <beans:property name="viewResolvers">
        <beans:list>
            <beans:bean
                class="org.springframework.web.servlet.view.BeanNameViewResolver"/>
            
<!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
<beans:bean id="jspView"
                class="org.springframework.web.servlet.view.InternalResourceViewResolver">
                <beans:property name="prefix" value="/WEB-INF/views/" />
                <beans:property name="suffix" value=".jsp" />
            </beans:bean>
        </beans:list>
    </beans:property>

    <beans:property name="defaultViews">
        <beans:list>
            <beans:bean
                class="org.springframework.web.servlet.view.json.MappingJackson2JsonView" />
        </beans:list>
    </beans:property>
</beans:bean>

</beans:beans>


             



Make sure you have added required jackson dependencies in your pom.xml

<!-- Jackson JSON Mapper -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.5.2</version>
</dependency>

<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.5.2</version>
</dependency>

<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.5.2</version>
</dependency>

<dependency>
<groupId>com.fasterxml.jackson.jaxrs</groupId>
<artifactId>jackson-jaxrs-json-provider</artifactId>
<version>2.5.2</version>
</dependency>

<dependency>
<groupId>com.fasterxml.jackson.module</groupId>
<artifactId>jackson-module-jaxb-annotations</artifactId>
<version>2.5.2</version>

</dependency>

Tuesday, August 11, 2015

A sample project using Spring MVC, Jquery and JQGrid to display the list of Object returned as a JSON object:

Following is a sample project using Spring MVC, Jquery and JQGrid to display the list of Employees returned as a JSON object:

The jsp in screenshot shows the list of employees.

I assume the user already knows how spring MVC works, so I am not explaining how Spring MVC works in this post.

You can download this sample maven project from github. 
https://github.com/SanjayIngole/jqgrid-example-parent

Here is an overview:
1. Jquery makes an Ajax call in Spring Controller method to get the ArrayList of objects (Employees).


 $.when($.getJSON('/jqgridexample/views/web/getemployees')).then(function (data) {

.....
 Rest of the code
....

));

2. In Spring Controller we map a method getEmployees to url '/web/getemployees' called from jquery. 
This method returns the ArrayList of Employees. Spring MVC takes care of converting this to a JSON Object.

@RequestMapping(value = "/web/getemployees", method = RequestMethod.GET)
public @ResponseBody
ArrayList<Employee> getEmployees(HttpServletRequest request) {


final ArrayList<Employee> employees = getMockEmployees();

return employees;
}

3. Jquery receives a list of employees as a JSON object.

[{"empID":100,"firstName":"John","lastName":"Oliver","address":"123 Hollywood Blvd, LA","phone":"4572312222"},{"empID":101,"firstName":"Barack","lastName":"Obama","address":"001 White House, DC","phone":"1010100101"},{"empID":102,"firstName":"Tom","lastName":"Cruise","address":"333 Sunset Blvd, LA","phone":"8272828222"},{"empID":103,"firstName":"Ed","lastName":"Sheeran","address":"6377 Kings Drive, London","phone":"9298292222"}]

4. This list is used to populate the jqgrid. In this case we are mapping individual fields before passing to jqgrid.

$("#employees").jqGrid({
   datatype: "local",
   height: 250,
   width: 700,
   colNames: ['EMPLOYEE ID', 'FIRST NAME', 'LAST NAME', 'ADDRESS', 'PHONE'],
   colModel: [{
       name: 'empID',
       index: 'empID',
       width: 10,
       sorttype: "int"},
   {
       name: 'firstName',
       index: 'firstName',
       width: 50},
   {
       name: 'lastName',
       index: 'lastName',
       width: 50},
   {
       name: 'address',
       index: 'address',
       width: 100},
   {
       name: 'phone',
       index: 'phone',
       width: 10}
   ],
});

var names = ['empID', 'firstName', 'lastName', 'address', 'phone'];
var employeedata = [];

for (var i = 0; i < data.length; i++) {
   employeedata[i] = {};
   employeedata[i][names[0]] = data[i].empID;
   employeedata[i][names[1]] = data[i].firstName;
   employeedata[i][names[2]] = data[i].lastName;
   employeedata[i][names[3]] = data[i].address;
   employeedata[i][names[4]] = data[i].phone;
}

for (var i = 0; i <= employeedata.length; i++) {
   $("#employees").jqGrid('addRowData', i + 1, employeedata[i]);
}

$("#employees").jqGrid('setGridParam', {ondblClickRow: function(rowid,iRow,iCol,e){alert('double clicked');}});

});

This example can be downloaded from github. Please drop me a question if required.

https://github.com/SanjayIngole/jqgrid-example-parent