Click here to Skip to main content
Email Password   helpLost your password?

Introduction

ExtJS is a really cool library generating fancy looking GUI apps in JavaScript. I started using ExtJS for a bunch of database frontends and found that I needed to have a DataGrid that would change its contents based on an AJAX call that filtered data based on some search parameters.

Notionally, this was easy enough and it appeared there may be many ways to make this happen. As it turns out, there is one right way and many - seemingly plausible - options that don't work.

After extracting this functionality from a few postings that were doing far more impressive things and trawling through the documentation, I figured it might be helpful to post a bare-bones example of this functionality to make it easy for the next ExtJS newbie who finds her/himself wanting to do the same thing.

Using the Code

The JavaScript/ExtJS portion looks like this:

Ext.onReady(function(){
    Ext.QuickTips.init();

    var proxy = new Ext.data.HttpProxy({
        url: 'demo.data.php',
    method: 'post'
    });

    var dstore = new Ext.data.JsonStore({
    url: 'demo.data.php',
    proxy: proxy,
    fields: ['id', 'data'],
    totalProperty: 'totalCount',
    root: 'matches'
    });
    dstore.load();

    var grid = new Ext.grid.GridPanel({
    store: dstore,
        columns: [
        {id:'id', header: "Id", width: 60,  sortable: true, dataIndex: 'id'},
        {id: 'data', header: "Data", width: 200, sortable: true, dataIndex: 'data'}
        ],
        stripeRows: true,
        autoExpandColumn: 'data',
        height:350,
        width: 500,
        title:'Demo Data'
    });

    var search = new Ext.FormPanel({
        labelWidth: 150, 
        frame:true,
        title: 'Search Demo Data',
        bodyStyle:'padding:5px 5px 0',
        width: 500,
        defaults: {width: 230},
        defaultType: 'textfield',
        items: 
    [{
            fieldLabel: 'Search regular expression',
            name: 'pattern',
        id: 'pattern'
    }],
    buttons: [{
            text: 'Search',
        handler: function() {
        dstore.load({
            params: {
            pattern: document.getElementById('pattern').value
            }});
        
        }
        }]
    });

    search.render('search_form');
    grid.render('search_results');
});

The backend datasource (which happens to be from PHP) looks like this:

<?php
$items = Array(Array('id'=>1, 'data' => 'the first item'),
           Array('id'=>2, 'data' => 'the second item'),
           Array('id'=>3, 'data' => 'one fish'),
           Array('id'=>4, 'data' => 'two fish'),
           Array('id'=>5, 'data' => 'red fish'),
           Array('id'=>6, 'data' => 'blue fish')
           );

$matches = Array();

if(!isset($_REQUEST['pattern']) || $_REQUEST['pattern'] == '') {
  $matches = $items;
} else {
  foreach ($items as $item) {
    if (eregi($_REQUEST['pattern'], $item['data'])) {
      $matches[] = $item;
    }
  }
}

echo json_encode(Array('totalCount' => count($matches),
             'matches' => $matches
             )
           );

?> 

The HTML file (that really is just the standard stuff) is included in the ZIP file.

Points of Interest

MySQL/PHP Backend Data Source

For those looking to load database data (probably MySQL for PHP folk) into an ExtJS JSONStore, the PHP file supplies most of what you need to know. Basically you want an array of data that you then encode with json_encode(...). For MySQL, building the data would look a bit like:

$data = Array(); 
$qry = mysql_query("SELECT id, description FROM ...");
while ($vals = mysql_fetch_array($qry)) {
  $data[] = Array('id' => $vals['id'], 'description' => $vals['description'];
} 
echo  json_encode($data); 

Paging Control on DataGrid

If you are using a paging control on the grid, then you will want the parameters that are sent to the DataStore to persist between calls (i.e. for when they press the paging buttons to retrieve the next page of data). To do this, you need to set the baseParams property on the datastore rather than sending parameters via the params object of the load(...) call. A real world example is shown below:

function search_submit() {
  dstore.baseParams = {
      number: document.getElementById('number').value,
      title: document.getElementById('title').value,
      keywords: document.getElementById('keywords').value,
      typeid: document.getElementById('typeid').value,
      allversions: (document.getElementById('allversions').checked) ? 1 : 0,
    };
  dstore.load({
    params:  {
      start: 0,
      limit: 25
    }
  });
} 

HIstory

You must Sign In to use this message board.
 
 
Per page   
 FirstPrevNext
Generalmysql no closed parenthesis
fonder
14:26 10 Nov '09  
Hi

Code mysql:
$items = Array();
$qry = mysql_query("SELECT id, description FROM ...");
while ($vals = mysql_fetch_array($qry)) {
$items[] = Array('id' => $vals['id'], 'data' => $vals['description']);
}

$matches = Array();
$matches = $items;

echo json_encode(Array('totalCount' => count($matches),
'matches' => $matches
)
);


line 4 no closed parenthesis: )


Wink
GeneralRe: mysql no closed parenthesis
Paul Coldrey
16:48 10 Nov '09  
I know the human eye is really bad at matching brackets,... but I can't see the mismatch!!

Anyhoo, I have an updated version of the code that runs cleanly with PHP 5 (having removed the deprecated eregi function). I would update the article but I can't figure out how Hmmm

Paul Coldrey
http://www.lumient.com.au/

Question2 yuigrid with 2 datasource in the same page doesn't work !
David Zenou
14:59 11 Jun '09  
Have you got an example with 2 yuigrid in the same page with 2 datasources (one for each) ?

Si tu aimes ce que tu fais , tu finis par réussir !
(french proverb of David Zenou)

AnswerRe: 2 yuigrid with 2 datasource in the same page doesn't work !
Paul Coldrey
15:19 11 Jun '09  
I don't have a canned example but I have done this and it works fine.

What I would do is create two data stores, ie repeat the classes that start "var dstore = new Ext.data.JsonStore({",.. perhaps call them dstore1 and dstore2. Note that these will obviously point at different 'urls' (and hence different server-side PHP files) so that they can load different data. For each panel you will need to point the "store:" to the correct store and set the appropriate "columns:" properties. Also you will have to create another div in the HTML file into which you want to render the second grid. Viola,.. it should all work nicely.

I notice your title says ".... doesn't work" - what exactly didn't work?

Paul Coldrey
http://www.lumient.com.au/

QuestionExtJs Grid
ratikantasahoo
22:30 8 Jun '09  
Hello can We put a button in the extjs grid rows.

Brill

AnswerRe: ExtJs Grid
Paul Coldrey
15:23 11 Jun '09  
I have never done this but I would expect it is possible. Perhaps the place to start is the API documentation http://extjs.com/deploy/dev/docs/[^] and the examples http://extjs.com/deploy/dev/examples/samples.html[^] (although I don't think this is covered). There is also a post on their support forum that seems to cover this http://extjs.com/forum/showthread.php?t=3539[^]. I hope this helps,.. obviously the question doesn't have a lot to do with the article,.. but if I get some time in the next week or two I'll try to look into this further and write another article showing how it is done.

Paul Coldrey
http://www.lumient.com.au/

GeneralGreat Article
humexlakex
18:48 21 Jan '09  
Thank you! This helped me out a lot.

- Jeremiah
GeneralNice article
anil_mane
21:49 28 Jul '08  
Can you guide me similar example in asp.net.

I tried with .net but it looses either its row height or doesn't update with latest data.


GeneralRe: Nice article
Paul Coldrey
22:03 28 Jul '08  
Are you using coolite or generating the Javascript directly? If you want to send me your code (paul at ensigma dot com dot au) I'll have a look and see if I can tell what is going wrong.

PS If you like the article please give it a vote to make up for the anonymous goob who rated it with a 1,... otherwise no one else will ever read it Smile

Paul Coldrey
http://www.ensigma.com.au/


Last Updated 23 Jul 2008 | Advertise | Privacy | Terms of Use | Copyright © CodeProject, 1999-2010