Blog Archive

ExtJs PagingMemoryProxy example using JSON data from Java Servlet AJAX request

The following example is built on the ExtJs user extension Ext.ux.data.PagingMemoryProxy, Paging Memory Proxy which allows to use paging grid with in memory dataset. In the example below data is coming in the form of a JSON object from a Java Servlet using an AJAX request which is more practical that using local data. Also provided is a filter that will locally filter complete stored data not just the grid data which is just the page that it displays.

The example is based on the MVC architecture provided in ExtJs 4.



ExtJs PagingMemoryProxy Ajax JSON data from Java Servlet with Grid Filter
ExtJs PagingMemoryProxy Ajax JSON data from Java Servlet with Grid Filter

Step 1: Application starting point index.html

<html>
<head>
    <title>ExtJs PagingMemoryProxy Ajax JSON data from Java Servlet with Grid Filter</title>

    <link rel="stylesheet" type="text/css" href="extjs/resources/css/ext-all.css">
   
    <script type="text/javascript" src="extjs/ext-all-debug.js"></script>
    <script type="text/javascript" src="app.js"></script>

</head>
<body></body>
</html>

Step 2: Application JavaScript file app.js

Ext.Loader.setPath('Ext.ux', 'extjs/ux');

Ext.Loader.setConfig({ 
    enabled: true 
    });

Ext.require([
             'Ext.data.*',
             'Ext.grid.*',
             'Ext.ux.data.PagingMemoryProxy'
         ]);


Ext.application({
    name: 'SAMPLE',

    appFolder: 'app',
   
    controllers: [
                  'Countries'
              ],

    launch: function() {
        console.log("Launching the application!");
        Ext.Ajax.request({
        loadMask: true,
        url: 'CountryServlet',
        scope: this,
        success: function(response, callOptions) {
            myData = Ext.decode(response.responseText);
            myTempData = Ext.decode(response.responseText);
            Ext.create('Ext.container.Viewport', {
                items: [
                    {
                        xtype: 'countrylist',
                    }
                ]
            });
        },
        failure: function(response, callOptions) {
           // Use the response
        }
    });
       
    }
});

Step 3: JavaScript source file for country model Country.js

Ext.define('SAMPLE.model.Country', {
    extend: 'Ext.data.Model',
    fields: [
             'code',
             'name',
             'continent',
             'region',
             'lifeExpectancy',
             'gnp'
             ]
});

Step 4: JavaScript source file for country store Countries.js

var myData;
var myTempData;

Ext.define('SAMPLE.store.Countries', {
    extend: 'Ext.data.Store',
    model: 'SAMPLE.model.Country',
    pageSize: 10,
    listeners: {
        beforeload: function(store, operation, options){
            console.log("My Store data is loading!");
        }
    }
});

Step 5: JavaScript source file for country grid panel CountryList.js

Ext.define('SAMPLE.view.CountryList' ,{
    extend: 'Ext.grid.Panel',
    alias : 'widget.countrylist',
    title : 'List of Countries',
    store : 'Countries',
    loadMask: true,
    autoheight: true,
    width: 1000,
    dockedItems: [{
        xtype: 'pagingtoolbar',
        store: 'Countries',  
        dock: 'bottom',
        displayInfo: true,
        items: [
                { 
                    xtype: 'tbseparator' 
                },
                {
                    xtype : 'trigger',
                    itemId : 'gridTrigger',
                    fieldLabel: 'Filter Grid Data',
                    triggerCls : 'x-form-clear-trigger',
                    emptyText : 'Start typing to filter grid',
                    size : 30,
                    minChars : 1,
                    enableKeyEvents : true,
                    onTriggerClick : function(){
                        this.reset();
                        this.fireEvent('triggerClear');
                    }
                }
        ]
    }],
    initComponent: function() {
       
        this.columns = [
            {header: 'Country Code', dataIndex: 'code',  flex: 1},
            {header: 'Name', dataIndex: 'name', flex: 1},
            {header: 'Continent', dataIndex: 'continent', flex: 1},
            {header: 'Region', dataIndex: 'region', flex: 1},
            {header: 'Life Expectancy', dataIndex: 'lifeExpectancy', flex: 1},
            {header: 'GNP', dataIndex: 'gnp', flex: 1}
        ];

        this.callParent(arguments);
    }

   
  
});

Step 6: JavaScript source file for the application controller Countries.js

Ext.define('SAMPLE.controller.Countries', {
            extend : 'Ext.app.Controller',

            stores : ['Countries'],
            models : ['Country'],
            views  : ['CountryList'],
            refs: [{
                ref: 'myGrid', 
                selector: 'grid'
            }],  

            init : function() {
                this.control({
                            'viewport > panel' : {
                                render : this.onPanelRendered
                            },
                            'countrylist #gridTrigger' : {
                                keyup : this.onTriggerKeyUp,
                                triggerClear : this.onTriggerClear
                            }
                        });
                },

                onPanelRendered : function() {
                    console.log('The panel was rendered');
                    this.getCountriesStore().setProxy({
                        type: 'pagingmemory',
                        data: myTempData,
                        reader: {
                            type: 'json',
                            totalProperty: 'totalCount',
                            root: 'countries',
                            successProperty: 'success'
                        }
                    });
                this.getCountriesStore().load();
                },
               
                onTriggerKeyUp : function(t) {
                    console.log('You typed something!');
                   
                        var thisRegEx = new RegExp(t.getValue(), "i");
                        var grid = this.getMyGrid();
                        records = [];
                        Ext.each(myData.countries, function(record) {
                            for (var i = 0; i < grid.columns.length; i++) {
                                // Do not search the fields that are passed in as omit columns
                                if (grid.omitColumns) {
                                    if (grid.omitColumns.indexOf(grid.columns[i].dataIndex) === -1) {
                                        if (thisRegEx.test(record[grid.columns[i].dataIndex])) {
                                            if (!grid.filterHidden && grid.columns[i].isHidden()) {
                                                continue;
                                            } else {
                                                records.push(record);
                                                break;
                                            };
                                        };
                                    };
                                } else {
                                    if (thisRegEx.test(record[grid.columns[i].dataIndex])) {
                                        if (!grid.filterHidden && grid.columns[i].isHidden()) {
                                            continue;
                                        } else {
                                            records.push(record);
                                            break;
                                        };
                                    };
                                };
                            }  
                        });
                        myTempData.countries = records;
                        myTempData.totalCount = records.length;
                        this.getCountriesStore().load();
                },
               
                onTriggerClear : function() {
                    console.log('Trigger got reset!');
                    myTempData.countries = myData.countries;
                    myTempData.totalCount = myData.totalCount;
                    this.getCountriesStore().load();
                }
           
        });

ExtJs PagingMemoryProxy Ajax JSON data from Java Servlet with Grid Filter
Click here for the Java Servlet sample code used in this Tutorial