Tuesday, October 20, 2009

Using ExtJS Form to store data to mysql database using PHP

1. simple-form.html
<html>
 <head>
  <title>Extjs Form Example</title>
  
  <link rel="stylesheet" href="ext-2.2/resources/css/ext-all.css" />
 
  
  <script type="text/javascript" src="ext-2.2/adapter/ext/ext-base.js"></script>
 
  
  <script type="text/javascript" src="ext-2.2/ext-all.js"></script> 
 
  
  <script type="text/javascript" src="simple-form.js"></script>
 </head> 
 <body>
 
  
  <div id="simple-form"></div>
 
 </body>
</html>

2. simple-form.js
Ext.onReady(function(){
 
 Ext.QuickTips.init();
 
 var simpleForm = new Ext.FormPanel ({
  labelWidth: 75,   // label settings here cascade unless overridden
        url:'save-form.php', // when this form submitted, data goes here
        frame:true,
        title: 'Add Pirates Crew',
        bodyStyle:'padding:5px 5px 0',
        width: 350,
        defaults: {width: 230},
        defaultType: 'textfield',
 
        items: [{
    /*
     here same as  in HTML
    */
                fieldLabel: 'Name',
                name: 'name',
                allowBlank:false
            },{
                fieldLabel: 'Position',
                name: 'position'
            },{
                fieldLabel: 'Ambition',
                name: 'ambition'
  }],    
 
        buttons: [{
            text: 'Save',   
   handler: function () {
    // when this button clicked, sumbit this form
    simpleForm.getForm().submit({
     waitMsg: 'Saving...',  // Wait Message
     success: function () {  // When saving data success
      Ext.MessageBox.alert ('Message','Data has been saved');
      // clear the form
      simpleForm.getForm().reset();
     },
     failure: function () {  // when saving data failed
      Ext.MessageBox.alert ('Message','Saving data failed');
     }
    });
   }
        },{
            text: 'Cancel',
   handler: function () {
    // when this button clicked, reset this form
    simpleForm.getForm().reset();
   }
        }]
 
 });
 
 // finally render the form
 simpleForm.render ('simple-form'); // render form to simple-form element (see simple-form.html)
 
});
 
3. save-form.php

 $conn = mysql_connect ("localhost", "root", "") or die (mysql_error ());
 mysql_select_db ("extjs") or die (mysql_error ());
 
 $q=mysql_query ("
  INSERT INTO strawhats (name, position, ambition) VALUES ('".$_POST['name']."','".$_POST['position']."','".$_POST['ambition']."')
 ") or die ('{"success":"false"}');
 
 // json output to notify the insert is success or not
 if ($q) {
  echo '{"success":"true"}';
 }
 else {
  echo '{"success":"false"}';
 }
 
?>

 

No comments: