Skip to content

Instantly share code, notes, and snippets.

@cristianogregnanin
Last active August 29, 2015 14:03
Show Gist options
  • Save cristianogregnanin/78a5bb9c9e686727a0b0 to your computer and use it in GitHub Desktop.
Save cristianogregnanin/78a5bb9c9e686727a0b0 to your computer and use it in GitHub Desktop.
Extjs. Populate grid with ajax call
//click in search button ==> start the ajaxSearch_function() retrive the form data parameters and call the load method. ==>
//load method start an ajax call. Retrive the data from the server and populate the store.
//The grid is not yet populated. ==> The load method lunch the callback. ==> when callback terminate the grid is populated
Ext.onReady(function(){
var store = new Ext.data.JsonStore({
url: "my/json/url",
idProperty: "name",
root: "data",//parsing the json starting from data field. Ex: {"results":1,"errors":"","success":true,"data":[{"msg":"SomeData"}]}
fields: ["msg"] //retrive the content of 'msg' key
});
var form = new Ext.FormPanel({
title: 'ajax search Form',
defaultType: 'textfield',
items: [{
fieldLabel: 'search',
name: 'search',
id: 'search'
}],
buttons: [{
text: 'Search', handler: ajaxSearch_function //reference the function, don't execute it! http://stackoverflow.com/a/3246964/1066183
}]
});
form.render('ajax-search_form'); // put the form html in the ajax-search_form div
function ajaxSearch_function(){
var query = Ext.getCmp('search').getValue(); //retrive the value of the search field
store.load({// start the ajax coll. If the 'params' is provide the http method is POST else is GET. So in this case is POST
params: {query: query}, //query is the name field in the http post request. Inspect the htto req to see the naming of parameters
//when the ajax call is finished the store is automatically populated with the server response data.
callback: storeLoadCallback // start the callback function. this function is usefull to manipulate the store data.
});
}
function storeLoadCallback(records, operation, success){
if (success) {
console.log("ok");
} else {
console.log("error");
}
return "FooBar";
}
var grid = new Ext.grid.GridPanel({
store: store, //this is the var istanziate before. store is populated by ajax response.
columns: [{
id :'title',
header : 'title',
dataIndex: 'msg'//this name MUST match with the field name provided in the store costructor definition.
}],
title: 'ajax grid',
stateId: 'ajax-Grid',
id: 'ajax-Grid'
});
grid.render('ajax-grid');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment