PDA

View Full Version : a simple form submit



trinity
3 May 2007, 1:54 PM
:(( i'm gonna to be crazy but i don't know why my code doesn't work...
nevertheless it's a very very very simple and basic example of submitting a form :
the js file:


Ext.onReady(function(){
Ext.form.Field.prototype.msgTarget = 'side';
var testForm = new Ext.form.Form({
labelWidth: 75,
url: 'test.php'
});
testForm.add(
new Ext.form.TextField({
fieldLabel: 'First Name',
name: 'first',
width:175,
allowBlank:false
}),

new Ext.form.TextField({
fieldLabel: 'Last Name',
name: 'last',
width:175
})
);
testForm.addButton('Save', function(){
testForm.submit();
});
testForm.addButton('Cancel');
testForm.render('myForm');
});

the php file :


<?php
echo $_POST['first'];
echo $_POST['last'];
?>

sorry, it seems a stupid thing comparing to other posts but i really don't see why nothing happens when i click the Save button...

best regards

jsakalos
3 May 2007, 2:27 PM
Have you used firebug to see what you really send to server and what really comes back?

tryanDLS
3 May 2007, 2:30 PM
Have you used firebug to see if the request is even posting, and if so, whether the response is coming back?

trinity
3 May 2007, 2:52 PM
oups !
it was a test.php permission problem in the unix server...
but now, firebug notices me about the error :

test is not defined
decode("firstlast")ext-all-debug.js (ligne 6003)
handleResponse(Object tId=0 status=200 statusText=OK)ext-all-debug.js (ligne 21688)
processResponse(Object tId=0 status=200 statusText=OK)ext-all-debug.js (ligne 21590)
success(Object tId=0 status=200 statusText=OK)ext-all-debug.js (ligne 21658)
setProgId(Object conn=XMLHttpRequest tId=0, Object scope=Object timeout=30000, undefined)yui-utilities.js (ligne 15)
setProgId()yui-utilities.js (ligne 15)
[Break on this error] return eval("(" + json + ')');

plz; can any one recommend me a simple tutorial or a post about submitting values, reseting the initial form and receiving post values in a php file to trait them...

arigato !

jsakalos
3 May 2007, 2:55 PM
Good! This is progress.

Server has to respond with json "{success:true}" to report succes, or "{success:false,errors:'Error msg'}".

jsakalos
3 May 2007, 2:59 PM
One more link: http://extjs.com/deploy/ext/examples/form/xml-form.html (http://extjs.com/forum/../deploy/ext/examples/form/xml-form.html) It's not the must to communicate in xml format with server you can use json as well.

trinity
3 May 2007, 3:09 PM
Good! This is progress.

Server has to respond with json "{success:true}" to report succes, or "{success:false,errors:'Error msg'}".
thank you so much jsalalos !
just to not disturb you all time with my stupid questions but i was asking myself why i'm not finding those kind of informations any where in the doc ?!!

jsakalos
3 May 2007, 3:15 PM
Well, this will maybe sound a bit philosophic, nevertheless, if one is trying to solve the problem he/she will sooner or later become a part of the problem. Main reason is that one is not looking in broad enough area.

Therefore, it's always good to talk about a problem with someone to get new viewpoints. You see, I can stand developing for a couple of days and then I have to talk with someone. Such a talk always widens my horizons I'm getting new viewpoints and that what was before a problem becomes a piece of cake.

That's life :)

jsakalos
3 May 2007, 3:20 PM
Sorry, I haven't answered directly you question. I don't know if it is written directly in doc, but I found out either from doc or from forum or from firebug or from source code.

And, it also took some time to find out ;)

trinity
3 May 2007, 3:55 PM
it's always good to talk about a problem with someone to get new viewpoints. You see, I can stand developing for a couple of days and then I have to talk with someone. Such a talk always widens my horizons I'm getting new viewpoints and that what was before a problem becomes a piece of cake.
That's life :)
thanks God that there are guys like you that talk and share with others what it took them lot of time to discover and master =D>

jsakalos
3 May 2007, 4:34 PM
Trinity, if I may, one more advice:

Never think: What am I doing wrong?
Always think: How can I do it?

Good luck.

trinity
4 May 2007, 3:08 PM
Never think: What am I doing wrong?
Always think: How can I do it?

easy to say, difficult to do :s
buy the way, i think that you have to help ma again in my "How can I do it"...
i was playing with ext in my free time hopping creating a simple form and its grid together in the same page (the grid have to auto refresh after adding a new record)...
i guess that's noting for you heuh ;)
may be this post will be helpful for many newbies like me in the future...
this is the js file:


Ext.onReady(function(){
//Form ext code
Ext.form.Field.prototype.msgTarget = 'side';
var testForm = new Ext.form.Form({
labelWidth: 75,
action: 'post',
url: 'test-submit.php'
});
testForm.add(
new Ext.form.TextField({
fieldLabel: 'Name',
id: 'name',
name: 'name',
width:175,
allowBlank:false
}),

new Ext.form.DateField({
fieldLabel: 'Birth day',
id:'bdate',
name: 'bdate',
format: 'y/m/d',
width:175
})
);
testForm.addButton('Save', function(){
if (testForm.submit()){
Ext.MessageBox.alert('Message', 'Changes saved successfully.');
ds.load();
grid.render();
}
});
testForm.addButton('Cancel', function(){
testForm.reset();
});
testForm.render('form');
//Grid ext code
var ds = new Ext.data.Store({
proxy: new Ext.data.HttpProxy({url: 'test-data.php'}),
reader: new Ext.data.JsonReader({
root:"rows",
},
['id', 'name','bdate'])
});
ds.load();
var cm = new Ext.grid.ColumnModel([
{header: "Id", width: 50, sortable: true, dataIndex: 'id'},
{header: "Name", width: 125, sortable: true, dataIndex: 'name'},
{header: "Birth Date", width: 125, sortable: true, renderer: Ext.util.Format.dateRenderer('d/m/Y'),
dataIndex: 'bdate'}
]);
cm.defaultSortable = true;
var grid = new Ext.grid.Grid('grid', {
ds: ds,
cm: cm
});
grid.render();
grid.getSelectionModel().selectFirstRow();
});

the test-submit.php:


<?php
require_once "../../includes/adodb_setup.php";
$name = $_POST['name'];
$bdate = $_POST['bdate'];
//$name = 'fu';
//$bdate = '2007/01/02';
$sql = "insert into test(name, bdate) values('".$name."','".$bdate."')";
if ($db->Execute($sql)===false){
echo "{success:false,errors:'".$db->ErrorMsg()."'}";
} else {
echo "{success:true}";
}
?>

and the test-data.php


<?php
require_once "../../includes/adodb_setup.php";
require_once "../../includes/rs2json.php";
$sql = "select * from test";
$rs = $db->Execute($sql);
if(!$rs)
{
echo $db->ErrorMsg();
}
else
{
echo rs2json($rs);
}
?>

i already tested the php files and they seem to work fine... but it's not the case for ext javascript file...
those are my questions:
1- grid lines are empty ! the number of lines is exactly the database one but it looks like if the values text is transparent !!!!
2- when submitting new record, the database is successfully updated but the grid is not auto refreshed
3- the Ext.MessageBox.alert() is not displayed
4- How can i set the focus to the first textField
5- how can i set the encoding of posted form values (i have to post special characters like

jsakalos
4 May 2007, 3:18 PM
Let's change one big problem to a number of smaller ones. First, if you are going to master grid you MUST watch these videos:

http://extjs.com/forum/showthread.php?t=5141
http://extjs.com/forum/showthread.php?t=5498

in the above order.

trinity
5 May 2007, 3:04 PM
cool ! much better now...
I inspired from videos to correct my ext js code:


var TestUI = function(){
var ds;
var grid;
var columnModel;
var form;
function setupDataSource() {
ds = new Ext.data.Store({
proxy: new Ext.data.HttpProxy({url:'test-data.php'}),
reader: new Ext.data.JsonReader(
{root: 'rows', id: 'id'},
[
{name: 'id', type:'int'},
{name: 'name'},
{name: 'bdate', type:'date', dateFormat:'Y-n-j'}
]
)
}
);
ds.load();
}
function getColumnModel() {
if(!columnModel) {
columnModel = new Ext.grid.ColumnModel(
[
{
header: 'Id',
width: 50,
sortable: true,
dataIndex: 'id'
},

{
header: 'Name',
width:100,
sortable: true,
dataIndex: 'name'
},
{
header: 'Birth Date',
width:100,
sortable: true,
dataIndex: 'bdate',
renderer: Ext.util.Format.dateRenderer('d/m/Y')
}
]
);
}
return columnModel;
}
function buildGrid() {
gridForm = new Ext.BasicForm(
Ext.get("updategrid"),
{
}
);
grid = new Ext.grid.Grid(
'grid',
{
ds: ds,
cm: getColumnModel(),
autoSizeColumns: true,
selModel: new Ext.grid.RowSelectionModel({singleSelect:true}),
}
);
grid.render();
var gridHeaderPanel = grid.getView().getHeaderPanel(true);
var tb = new Ext.Toolbar(
gridHeaderPanel,
[
{
text: 'Delete Row',
/*onclick: function(e){
Ext.MessageBox.confirm('Confirm', 'Am I sure ?');
},*/
handler: function() {
selectedRow = grid.getSelectionModel().getSelected();
if(selectedRow) {
gridForm.submit(
{
waitMsg: 'Please wait...',
url:'test-delete.php',
params:{id:selectedRow.data.id},
success:function(form, action) {
ds.remove(selectedRow);
},
failure: function(form, action) {
alert('Error !');
}
}
);
}
}
}
]
);
}

function buildForm(){
Ext.form.Field.prototype.msgTarget = 'side';
form = new Ext.form.Form({
labelWidth: 75,
action: 'post',
url: 'test-submit.php'
});
form.add(
new Ext.form.TextField({
fieldLabel: 'Name',
id: 'name',
name: 'name',
width:175,
allowBlank:false
}),

new Ext.form.DateField({
fieldLabel: 'Birth day',
id:'bdate',
name: 'bdate',
format: 'y/m/d',
width:175
})
);
form.addButton('Add', function(){
form.submit(
{
success:function(form, action) {
ds.reload();
Ext.MessageBox.alert('Message', 'Changes saved successfully.');
},
failure: function(form, action) {
alert('Error!');
}
}
);
});
form.addButton('Reset', function(){
form.reset();
form.findField('name').focus();
});
form.render('form');
}
return {
init : function() {
buildForm();
setupDataSource();
buildGrid();
},

getDataSource: function() {
return ds;
}
}
}();
Ext.onReady(TestUI.init, TestUI, true);

but i still have some problems:
1- the adding new items from the form works fine but i still not found how the encode values to html entites before sending them to the php backend file?
2- i want to display a confirmed message box before processing of deleting an item from the grid toolbar
3- even without this Confirm message box, i have an error when trynig delete an item


gridForm.submit(
{
waitMsg: 'Please wait...',
url:'test-delete.php',
params:{id:selectedRow.data.id},
success:function(form, action) {
ds.remove(selectedRow);
},
failure: function(form, action) {
alert('Error !');
}
}
);

can you please tell where can i find more informations about the object passed to the submit action ?
this is the firebug error:
_31.elements has no properties
setProgId(div#updategrid.x-form, undefined, "javascript:false")yui-utilities.js (ligne 15)
getViewWidth(div#updategrid.x-form, "test-delete.php", Object scope=Object timeout=30000, "id=22", undefined, "javascript:false")ext-yui-adapter.j... (ligne 11)
run()ext-all-debug.js (ligne 21650)
apply()ext-yui-adapter.j... (ligne 9)
[Break on this error] YAHOO.util.Connect={_msxml_progid:["MSXML2.XMLHTTP.3.0","MSXML2.XMLHTTP","Micros...
thanks a lot

jsakalos
5 May 2007, 3:22 PM
As usually ;) let's make problem smaller. First of all I'm missing the purpose of the form. If I understand it well, you have a grid and if you want to enter new data in the grid you open the form.Then you want to save data to the server and then display that new row in the grid. Am I right?

If yes, you're overcomplicating. If you watched the second video too, you had seen that you can create new empty row directly in the grid, then user can fill it in directly in the grid and then just clicks the save button to save data to server.

The same is true for editing data of existing rows.

From this viewpoint you can remove all form code and improve the grid code instead.

trinity
5 May 2007, 3:39 PM
If yes, you're overcomplicating

it's not that, my ultimate goal is trying to practice and understand ext not to make the same thing as at the screencasts ;)
i have no problem with this part (data are well stored in the database and the grid is well refreshed too), i just have to find how to encode values in server side before sending them to php file...
in the other hand, i begun by trying deleting items which is more simple than editing but firebug gives me the previous error...
please can you at least told me in which part of doc can i find details about the object passed to the submit action of a button ?
and is this backend php code


<?php
require_once "../../includes/adodb_setup.php";
$id = $_POST['id'];
$sql = "delete from test where id=".$id;
if ($db->Execute($sql)===false){
echo "{success:false,errors:'".addslashes($db->ErrorMsg())."'}";
} else {
echo "{success:true}";
}
?>

is what have to be done for:


gridForm.submit(
{
waitMsg: 'Please wait...',
url:'test-delete.php',
params:{id:selectedRow.data.id},
success:function(form, action) {
ds.remove(selectedRow);
},
failure: function(form, action) {
alert('Error !');
}
}
);

Best regards

jsakalos
5 May 2007, 4:00 PM
Aaah, I got it now. It's just exercise ;)

OK, first, you do not need to encode anything you just submit data. There are several ways how to do it but what is most important is an options object. The rough minimal content is as follows:



options = {
url: '/your-server-url.php'
, method: 'post' // or get if you like but post is better
, params: {
name1: 'value1'
, name2: 'value2'
// ... etc
}
, scope: this // or you can omit this if you don't need it
, callback: function(options, bSuccess, response) {
// handle here your successful or failed response e.g. this way:
if(true === bSuccess) {
var o = Ext.decode(response.responseText);
if(true == o.success) { // server should respond with {success:true}
// handle your success
}
else {
// ...
}
}
}
};

// then
new Ext.data.Connection.request(options);


This is wholy "raw" method of saving data to server. I use it, for example, when user drags and drops an object somewhere and I want to have this changes saved.

There is other, maybe simpler method for forms, or grids.

Hope it gives you at least a clue.

trinity
5 May 2007, 4:23 PM
ok i see...
but for deleting, normally it should works for


gridForm.submit(
{
url:'test-delete.php',
params:{id:selectedRow.data.id},
method: 'post',
success:function(form, action) {
//ds.remove(selectedRow);
ds.reload();
},
failure: function(form, action) {
alert('Error !');
}
}
);

but i still have the error (attached image http://extjs.com/forum/attachment.php?attachmentid=310&stc=1&d=1178410890)
perhaps i forgot a required param ?

jsakalos
5 May 2007, 4:27 PM
I cannot even guess what's the reason...:(

But, you can include ext-all-debug.js instead of ext-all.js and trace the error to it's source.

Does your server return "{success:true}" ?

trinity
5 May 2007, 5:30 PM
i'm sure it's not backend server problem cause i already tested with returning only "{success:true}" instead of the other code.
sorry, i can't find how to trace error with the ext debug file... do you know another post or screencast for that ?
i found a same error like mine in this page http://extjs.com/forum/showthread.php?t=5289&highlight=debug
so i decided to just tested the deleting from a normal form button;


form.addButton('dell', function(){
selectedRow = grid.getSelectionModel().getSelected();
alert (selectedRow.data.id);
if(selectedRow) {
form.submit(
{
url:'test-delete.php',
params:{id:selectedRow.data.id},
method: 'post',
success:function(form, action) {
ds.remove(selectedRow);
},
failure:function(form, action) {
alert('Error !');
}
}
);
}
}, form);

this time no 31 error but in all the cases, it's the failure function which is called (even if the test-delete.php returned only the {success:true})... and nothing noticed by firebug !!!
any idea ?!!

jsakalos
5 May 2007, 5:44 PM
I have no idea about the error itself.

On the picture of the firebug error messge you have posted there is a little plus sign if you click it you get the stack trace where you can see which function was called down to the error.

Another thing: ext-all.js is minified. That means it is very hardly human readabe an undebugabble by firebug. ext-all-debug.js, on the other hand, contains human readable debuggable code. You should include debug version in the case of troubles and minified version for production system.

Then, you set a breakpoint(s) in the code before the error (e.g. in the failure funcion) and you run your code.

When script execution stops at BP then you go step by step until you find the cause of the error.

It's worth to master debugging techniques as it can speed up the devel time tremendously.

trinity
6 May 2007, 11:00 AM
Hi jsakalos
the last error that i did was in


form.addButton('dell', function(){
selectedRow = grid.getSelectionModel().getSelected();
alert (selectedRow.data.id);
if(selectedRow) {
form.submit(
{
url:'test-delete.php',
params:{id:selectedRow.data.id},
method: 'post',
success:function(form, action) {
ds.remove(selectedRow);
},
failure:function(form, action) {
alert('Error !');
}
}
);
}
}, form);

actually, when i put my code into form.submit(), it's not url:'test-delete.php' which is executed but the url of the form itself (the one that i use for insert statement :"> )
so this what i did to fix the problem


form.addButton('Delete', function(){
selectedRow = grid.getSelectionModel().getSelected();
if(selectedRow) {
Ext.MessageBox.confirm('Confirm', 'Am I sure ?', function(btn, text){
if (btn == 'yes'){
DeleteItem(selectedRow.data.id);
}
});
}
});

and for the DeleteItem function:


function DeleteItem(itemId){
var success = function (o)
{
form.reset();
form.findField('name').focus();
ds.remove(selectedRow);
};
var failure = function (o)
{
alert('Error !');
};
var url = 'test-delete.php';
var params = {id:itemId};
params = Ext.urlEncode(params);
Ext.lib.Ajax.request('POST', url, {success: success, failure: failure}, params);
}

by the way, the "new Ext.data.Connection.request(options);" didn't work so i did it with Ext.lib.Ajax.request() like i found in a previous post (may be we can do it more easily with the UpdateManager... i don't know, i can't understand any thing from the doc without examples ;)
ok, thanks very much for your assistance =D>
best regards

jsakalos
6 May 2007, 11:02 AM
You're welcome.
I'm glad I helped.