Form submit isn't working - sencha-touch

I am creating login system with Sencha Touch 2. I am getting an issue while submitting my form. It is not getting response data from server. Below is my code
Controller:
Ext.define("MyMobile.controller.LoginController", {
extend: "Ext.app.Controller",
views: ['LoginView'],
config: {
refs: {
loginForm: "#loginFormPanel"
},
control: {
'button[action=login]': {
tap: "authenticateUser"
}
}
},
authenticateUser: function (button) {
this.getLoginForm().submit({
url: 'login/authenticate',
method: 'POST',
success: function (form, result) {
debugger; //This block of code is not executing even after JSON response
var jsonoutput = Ext.decode(result); // json parsing
Ext.MessageBox.alert('Error', "Success");
},
failure: function (form, result) {//This block of code is not executing even after JSON response
Ext.MessageBox.alert('Error', "Invalid username/password");
}
});
}
});
View
Ext.define("MyMobile.view.LoginView", {
extend: "Ext.form.FormPanel",
alias: "widget.mylogin",
id: 'loginFormPanel',
config: {
margin: '0 auto',
name: 'loginform',
frame: true,
url: 'login/Authenticate',
title: 'Login',
items: [
{
xtype: 'fieldset',
itemId: 'LoginFieldset',
margin: '10 auto 0 auto ',
title: '',
items: [
{
xtype: 'textfield',
label: 'User Name',
name: 'my-username',
required: true,
placeHolder: 'Username'
},
{
xtype: 'emailfield',
label: 'Email',
name: 'Email'
},
{
xtype: 'passwordfield',
label: 'Password',
name: 'my-password',
required: true,
placeHolder: 'Password'
}
]
},
{
xtype: 'button',
id: 'loginButton',
margin: '25 auto 0 auto ',
style: '',
maxWidth: 200,
ui: 'action',
width: '',
iconCls: 'user',
iconMask: true,
text: 'Login',
action: 'login'
}
]
}
});
App.JS
Ext.application({
name: "MyMobile",
appFolder: "myapp",
controllers: ["LoginController"],
views: ['LoginView'],
launch: function () {
var loginPanel= Ext.create('Ext.Panel', {
layout: 'fit',
items: [
{
xtype: 'mylogin'
}
]
});
Ext.Viewport.add(loginPanel);
}
});
Can some one could figure out what should be the problem?
Below was the JSON response i am getting from server.
{"UserName":"Murali","isAdmin":true,"isAuthenticated":true}
Even after getting a JSON and 200 ok result, my code form submit function goes into failure callback. In failure call back function failure:function(form,result) i am getting result param as my JSON. But why it is in failure?

Make your server return a JSON response like below:
If success:
{
"success":true,
"UserName":"Murali",
"isAdmin":true,
"isAuthenticated":true
}
If failure:
{
"success":false
}
Read more here: http://docs.sencha.com/touch/2-0/#!/api/Ext.form.Panel-method-submit

Related

how to get the form values and insert that values in the db using sencha touch

I want to store the login form details in the database .for that,i wrote the following code .
In my view code
Ext.define('SampleForm.view.LoginForm', {
extend: 'Ext.form.Panel',
//id:'loginform',
requires:[
'Ext.field.Email',
'Ext.field.Password'
],
config: {
fullscreen: true,
layout:{
type:'vbox'
},
items: [
{
xtype: 'fieldset',
title: 'Login',
id: 'loginform',
items: [
{
xtype:'textfield',
label:'Name',
name:'name'
},
{
xtype: 'emailfield',
name: 'email',
label: 'Email'
},
{
xtype: 'passwordfield',
name: 'password',
label: 'Password'
}
]
},
{
xtype: 'button',
width: '30%',
text: 'Login',
ui: 'confirm',
action:'btnSubmitLogin'
}
]
}
});
In controller
Ext.define("SampleForm.controller.LoginForm", {
extend: "Ext.app.Controller",
config: {
view: 'SampleForm.view.LoginForm',
refs: [
{
loginForm: '#loginform',
Selector: '#loginform'
}
],
control: {
'button[action=btnSubmitLogin]': {
tap: "onSubmitLogin"
}
}
},
onSubmitLogin: function () {
alert('Form Submitted successfully');
console.log("test");
var values = this.getloginform();
/* Ext.Ajax.request({
url: 'http://www.servername.com/login.php',
params: values,
success: function(response){
var text = response.responseText;
Ext.Msg.alert('Success', text);
}
failure : function(response) {
Ext.Msg.alert('Error','Error while submitting the form');
console.log(response.responseText);
}
});*/
form.submit({
url:"http://localhost/sencha2011/form/login.php"
});
},
launch: function () {
this.callParent();
console.log("LoginForm launch");
},
init: function () {
this.callParent();
console.log("LoginForm init");
}
});
when i click the submit button,alert message coming,but values aren't stored in the database.and in console im getting this error,Uncaught TypeError: Object [object Object] has no method 'getloginform'.
Can anyone help me to how to insert the values in the db.
Javascript is case-sensitive. From Sencha Touch docs:
These getter functions are generated based on the refs you define and
always follow the same format - 'get' followed by the capitalized ref
name.
To use the getter method for ref, loginForm, and to get the form values use:
var values = this.getLoginForm().getValues();

Issue while Loading JSON with Store

I am trying to get some master data from server in JSON format and bind it to selectfield with the help of Store.
Find my code below
Model
Ext.define('Mobile.model.OrganizationModel', {
extend: 'Ext.data.Model',
config: {
fields: [
{ name: 'Name', type: 'string' },
{ name: 'Id', type: 'int' }
]
}
});
Store
Ext.define('Mobile.store.OrganizationStore', {
extend: 'Ext.data.Store',
model: 'Mobile.model.OrganizationModel',
autoLoad: true,
proxy: {
type: 'ajax',
url: 'login/GetOrgList',
method: 'GET',
reader: {
type: 'json'
}
}
});
View
Ext.define("Mobile.view.LoginView", {
extend: "Ext.form.FormPanel",
alias: "widget.login",
id: 'loginFormPanel',
config: {
margin: '0 auto',
name: 'loginform',
frame: true,
url: 'login/Authenticate',
title: 'something',
items: [
{
xtype: 'fieldset',
itemId: 'LoginFieldset',
margin: '10 auto 0 auto ',
title: '',
items: [
{
xtype: 'selectfield',
label: 'Organization',
name: 'Organization',
store: 'OrganizationStore',
displayField: 'Name',
valueField: 'Id',
placeHolder: 'Select a Value'
}
]
},
]
}
});
APP.js
Ext.application({
name: "Mobile",
controllers: ["LoginController"],
views: ['LoginView', 'HomeView'],
models: ['UserModel', 'OrganizationModel'],
stores: ['OrganizationStore'],
launch: function () {
var loginPanel = Ext.create('Ext.Panel', {
layout: 'fit',
items: [
{
xtype: 'login'
}
]
});
Ext.Viewport.add(loginPanel);
}
});
JSON Data format is
[{"Id":1,"Name":"Company 1"},{"Id":2,"Name":"Company 2"},{"Id":3,"Name":"Company 3"}]
The problem is it is not sending request to server and loading JSON data and binds. Any idea about this issue?
update you store code to
Ext.define('Mobile.store.OrganizationStore', {
extend: 'Ext.data.Store',
config:{
model: 'Mobile.model.OrganizationModel',
autoLoad: true,
proxy: {
type: 'ajax',
url: 'login/GetOrgList',
method: 'GET',
reader: {
type: 'json'
}
}
}
});

sencha-touch: Login request-response

I am very new to sencha-touch & started to build simple Login form.
My UI is ready but now I am stuck on how to write code for login request response.
As important, how can I point to specific url to make POST/GET request?
Also how to get & parse the json data.?
I read the sench-touch documentation but I didnt understood, how to use that model, store, proxy.
Suggestions upon how to create model, store, proxy to make simple login are very helpful.
Thanks in advance.
Edited to insert image:
var loginForm = Ext.create('Ext.form.Panel', {
fullscreen: true,
items: [{
xtype: 'fieldset',
items: [
{
xtype: 'textfield',
name : 'name',
label: 'Username'
},
{
xtype: 'passwordfield',
name : 'password',
label: 'Password'
}
]
}]
});
loginForm.add({
xtype: 'button',
text: 'Login',
ui: 'confirm',
badgeText: '1',
// handler: function(){
// // alert("handler invoked");
// },
listeners : {
tap : function() {
var form = Ext.getCmp('form-id');
var values = form.getValues();
Ext.Ajax.request({
url: 'https://102.XXX.X.XX:XXXX/QuizMasterServer/rest/login',
params: values,
success: function(response){
var text = response.responseText;
Ext.Msg.alert('Success', text);
},
failure : function(response) {
Ext.Msg.alert('Error','Error while submitting the form');
console.log(response.responseText);
}
});
}
}
});
loginForm.add({
xtype: 'toolbar',
// id:'loginPressed',
docked: 'bottom',
// layout: { pack: 'center' },
items: [
{
xtype: 'button',
text: 'Login',
ui: 'confirm',
// action: 'login',
handler: function() {
loginForm.setValues({
name: 'vs',
password: 'vs'
})
}
},
{
xtype: 'button',
text: 'Clear',
ui:'decline',
handler: function() {
loginForm.reset();
}
},
{
xtype: 'button',
centered: true,
text: 'Sign Up',
handler: function() {
alert('New User?');
}
},
{
xtype: 'container',
html: 'New User? ',
style: {
color: 'yellow',
}
},
]
});
Exemplo usando ajax request:
Example using ajax request:
Ext.Ajax.request({
url: domain.com/auth/signIn/',
method: 'post',
scope: this,
params: {
email: username,
password: password
},
success: function (response) {
var result = Ext.JSON.decode(response.responseText);
if (result.meta.code==200)
{
/**
* Salvando dados do usuário em localStorage
* Save user data on localStorage
*/
window.localStorage.setItem('myID', result.response.id);
window.localStorage.setItem('email', result.response.email);
window.localStorage.setItem('token', result.response.token);
window.localStorage.setItem('fName', result.response.fName);
window.localStorage.setItem('lName', result.response.lName);
window.localStorage.setItem('photo', result.response.photo);
window.localStorage.setItem('gender', result.response.gender);
window.localStorage.setItem('relationship', result.response.relationship);
window.localStorage.setItem('interest', result.response.interest);
this.signInSuccess();
this.verifyDeviceToken(result.response.id, 'signin');
}
else
{
this.signInFailure('Error', 'The data reported are invalid');
}
},
failure: function (response) {
}
});
You are almost there!
add your code to the success callback.
Note, success() callback if fired if ajax returns ok, otherwise failure(). Callback callback() fire in both cases.
Ext.Ajax.request({
url: 'https://102.XXX.X.XX:XXXX/QuizMasterServer/rest/login',
params: values,
success: function(response){
var text = response.responseText;
// for example
var result = Ext.decode(text); // json parsing
if (result.ok) {
//create new widget
var homeView = Ext.widget('homePage', {...});
Ext.Viewport.remove(formLogin);
Ext.Viewport.add(homeView);
///... etc
homeView.show()
}
Ext.Msg.alert('Success', text);
},
failure : function(response) {
Ext.Msg.alert('Error','Error while submitting the form');
console.log(response.responseText);
}
});
Disclaimer. Of course the code is not tested...
cheers, Oleg

Sencha Touch Tree Store 'Object has no method getRootNode'

I am developing an Android 2.3.3 app using PhoneGap and Sencha Touch 2 ...
I have an Login view from which i redirect to nested list view in my app ... I used an inline store for the nested list and i defined the type as 'tree' for the store ...
The first time i am trying to load the app and when i click on Login it is giving me an error ... The error is stated below :
Uncaught TypeError: Object [object Object] has no method 'getRootNode' at file:///android_asset/www/sencha/sencha-touch-all.js:15
But after getting the error if i force close the app and open it again everything is working fine ...
My code is :
Login.js
Ext.define("DDLApp.view.Login", {
//extent panel class
extend: "Ext.form.Panel",
//DOM in fieldset
requires: "Ext.form.FieldSet",
xtype: 'formLogin',
id:'loginForm',
config: {
scrollable: 'vertical',
id: 'login',
items: [
{
xtype: "toolbar",
docked: "top",
},
{
xtype: "toolbar", //Toolbar with heading as login
docked: "top",
title: "Login",
ui:'light',
id:"idHeaderTwo",
cls:"clsLoginHeader"
},
{
xtype: 'textfield', //textfield for username
name: 'Username',
required: true,
id:"idUserName",
cls:"clsUserName",
useClearIcon: false
},
{
xtype: 'passwordfield', //textfield for password
name: 'password',
required: true,
id:"idPassword",
cls:"clsPassword",
useClearIcon: false
},
{
xtype: 'button', //Login button
text: 'Login',
ui: 'confirm',
cls:'btnLogin',
width:'30%',
handler: function(SuccessFlag) { //Login button handler
ui: 'confirm',
console.log('Login Button pressed');
var form = Ext.getCmp('login');
//get username and password from form elements
var user = form.getValues().Username;
var pwd = form.getValues().password;
var msg = new Ext.MessageBox();
onLoad();
if(user == "" || pwd == "")
{
var errMsg = '';
if(user == "")
{
errMsg+= 'Username is required<br/>';
}
if(pwd == "")
{
errMsg+= 'Password is required';
}
msg.show({
title: 'LOGIN ERROR',
message: errMsg,
ui:'light',
cls: 'vm_error',
showAnimation: 'fadeIn',
hideAnimation: 'fadeOut',
buttons: [{text:'OK',itemId:'ok'}],
fn:function(){
Ext.emptyFn();
}
});
}
else
{
form.setMasked({
xtype:'loadmask',
message:'Loading...'
});
//Check for network connectivity
if(onDeviceReady())
{
//Fire a json service
Ext.util.JSONP.request({
url: DDLApp.app.oneTimeServiceUrl,
dataType: "jsonp",
params: {
type:'fetch',
username:user,
password:pwd
},
success: function (result) {
//if username and password matches
if(result.Success == true)
{
//setLocalStorage(result);
localStorage.setItem('userName',user);
localStorage.setItem('userPassword',pwd);
localStorage.setItem('totalData',JSON.stringify(result.Data));
localStorage.setItem('userData',JSON.stringify(result.Data.user));
localStorage.setItem('userIncidentData',JSON.stringify(result.Data.incidentList));
localStorage.setItem('impactData',JSON.stringify(result.Data.impact));
localStorage.setItem('incidentTypeData',JSON.stringify(result.Data.incident_type));
localStorage.setItem('categoryData',JSON.stringify(result.Data.category));
localStorage.setItem('statusData',JSON.stringify(result.Data.statusDropdown));
var indexPanel = Ext.create('DDLApp.view.Main');
Ext.Viewport.add(indexPanel);
Ext.Viewport.setActiveItem(indexPanel,{type: 'slide', direction: 'right'});
form.unmask();
}
else{
msg.show({
title: 'LOGIN ERROR',
message: 'Invalid Username/Password',
ui:'light',
cls: 'vm_error',
showAnimation: 'fadeIn',
hideAnimation: 'fadeOut',
buttons: [{text:'OK',itemId:'ok'}],
fn:function(){
Ext.emptyFn();
}
});
form.unmask();
}
}
});
}
////If network is not present
else
{
form.unmask();
msg.show({
title: 'NETWORK CONNECTION ERROR',
message: "We're Sorry but it appears your device is not connected to the internet . Please check your internet settings and try again.",
ui:'light',
cls: 'vm_error',
showAnimation: 'fadeIn',
hideAnimation: 'fadeOut',
buttons: [{text:'Retry',itemId:'retry'}],
fn:function(){
window.location.reload();
}
});
}
}
},
},
{
xtype: 'button', //clear button
text: 'Clear',
width:'30%',
ui: 'confirm',
cls:'btnClear',
style: 'background:#4A4245;',
handler: function() {
this.up('formpanel').reset(); //reset all form elements
},
}
]
},
});
IncidentsList.js
Ext.define("DDLApp.view.IncidentsList", {
extend: "Ext.Container",
xtype: 'incidentsList',
id: 'idIncList',
requires:[
'Ext.dataview.NestedList',
'Ext.data.proxy.Memory',
'Ext.data.TreeStore',
],
alias:'widget.incidentslist',
config: {
id: 'idIncidentList',
layout:'fit',
items: [
{
xtype: "toolbar",
docked: "top",
cls:'clsDDLHeader',
items: [
{xtype:'spacer'},
{ xtype: 'title' ,
cls: 'clsRightTitle',
id: 'idIncidentsListTitle',
title:"Welcome",
},
]
},
{
xtype: "toolbar",
ui:'light',
id:"idHeaderTwo",
cls:"clsHeaderTwo" ,
items: [
{ xtype: 'title' ,
cls: 'clsLeftTitle',
title: "My Incidents",
},
{xtype:'spacer'}
]
},
{
xtype: 'nestedlist',
id:'idIncidentList',
onItemDisclosure:true,
cls:'clsNestedIncidentList',
toolbar:{id:'idNestedIncidentList'},
loadingText: "Loading Incidents...",
emptyText: "<div class=\"empty-text\">No Incidents Found.</div>",
getItemTextTpl: function() {
var tplConstructor =
'<tpl if="TKT_STATUS_NAME == \'CLOSED\'">'+
'<div class="vm_statusRed">'+
'</tpl>'+
'<tpl if="TKT_STATUS_NAME == \'OPENED\'">'+
'<div class="vm_statusYellow">'+
'</tpl>'+
'<tpl if="TKT_STATUS_NAME == \'ASSIGNED\'">'+
'<div class="vm_statusGreen">'+
'</tpl>'+
'<tpl if="TKT_STATUS_NAME == \'PENDING\'">'+
'<div class="vm_statusRed">'+
'</tpl>'+
'<tpl if="TKT_STATUS_NAME == \'RESOLVED\'">'+
'<div class="vm_statusOrange">'+
'</tpl>'+
'<tpl if="TKT_STATUS_NAME == \'REOPEN\'">'+
'<div class="vm_statusYellow">'+
'</tpl>'+
'<div class="vm_dvList"><h4 class="vm_txtName"><span class="vm_listHeader"><label>Inci.#{TKT_ID} by </label><label class="vm_txtFirstName"><i>{FIRST_NAME:ellipsis(15, true)}</i></label></span><div class="date vm_clsDate">{CREATED_ON:date("d-M-y H:i")}</div></h4>'+
'<div class="vm_title">{TKT_SUBJECT}</div>'+
'<div class="vm_subDesc">{TKT_DESC}</div></div></div>';
return tplConstructor;
},
store: {
type: 'tree',
fields: ['TKT_ID', 'CREATED_ON', 'FIRST_NAME', 'TKT_STATUS_NAME', 'TKT_SUBJECT', 'TKT_DESC', 'SEV_DESC', 'SERVICE_NAME', 'CATEGORY_NAME', {
name: 'leaf',
defaultValue: true
}],
root: {
leaf: false
},
data : localStorage.userIncidentData,
proxy: {
type: 'memory',
reader: {
type: 'json',
rootProperty: 'incidentList'
}
}
},
detailCard: {
xtype: "fieldset",
scrollable: true,
id: "idIncidentDetails",
items: [
{
xtype: 'textfield',
name: 'TKT_SUBJECT',
label: 'Subject',
labelAlign: 'top',
cls:'vm_textFields',
clearIcon:false,
disabled:true
},
{
xtype: 'textareafield',
name: 'TKT_DESC',
label: 'Description',
labelAlign: 'top',
cls:'vm_textFields',
clearIcon:false,
disabled:true
},
{
xtype: 'textfield',
name: 'SEV_DESC',
label: 'Impact',
labelWidth:'45%',
cls:'vm_textFields',
clearIcon:false,
disabled:true
},
{
xtype: 'textfield',
name: 'SERVICE_NAME',
id:'displayIncident',
cls:'vm_textFields',
label: 'IncidentType',
labelWidth:'45%',
disabled:true
},
{
xtype: 'textfield',
label: 'Category',
name: 'CATEGORY_NAME',
cls:'vm_textFields',
id:'getCategory',
labelWidth:'45%',
disabled:true
},
],
},
listeners: {
itemtap: function(nestedList, list, index, element, post) {
this.getDetailCard().items.items[0].setHtml(post._data.TKT_SUBJECT);
this.getDetailCard().items.items[1].setHtml(post._data.TKT_DESC);
this.getDetailCard().items.items[2].setHtml(post._data.SEV_DESC);
this.getDetailCard().items.items[3].setHtml(post._data.SERVICE_NAME);
this.getDetailCard().items.items[4].setHtml(post._data.CATEGORY_NAME);
}
}
},
{html:'No Incidents Found....',id:'idEmptyText'}],
},
initialize: function() {
this.callParent(arguments);
var incidentStore = Ext.getCmp('idIncidentList').getStore();
Ext.getCmp("idEmptyText").hide();
var getLoginData = localStorage.getItem('userData');
var parseData = JSON.parse(getLoginData);
var fname = parseData[0].FIRST_NAME;
var getIncidentData = localStorage.getItem('userIncidentData');
var parseIncidentData = JSON.parse(getIncidentData);
this.down("#idIncidentsListTitle").setTitle("Welcome, " + fname);
if(localStorage.userIncidentData != '[""]')
{
Ext.getCmp("idEmptyText").hide();
incidentStore.setData(localStorage.userIncidentData).load();
}
else
{
this.down("#inclist").hide();
this.down("#idEmptyText").show();
var msg = new Ext.MessageBox();
msg.show({
title: 'NO INCIDENTS FOUND',
message: 'No Incidents have reported by this user',
ui:'light',
cls: 'vm_error',
showAnimation: 'fadeIn',
hideAnimation: 'fadeOut',
buttons: [{text:'OK',itemId:'ok'}],
fn:function(){
Ext.emptyFn();
}
});
}
},
});
I need to get rid of this error as soon as possible ... Everything in my app is working fine from the second time onwards ... I think the problem is with the store i have defined ... Please help me guys ... Thanks in Advance ...!!!
My store is defined inline in my IncidentList View itself ...
store: {
type: 'tree',
fields: ['TKT_ID', 'CREATED_ON', 'FIRST_NAME', 'TKT_STATUS_NAME', 'TKT_SUBJECT', 'TKT_DESC', 'SEV_DESC', 'SERVICE_NAME', 'CATEGORY_NAME', {
name: 'leaf',
defaultValue: true
}],
root: {
leaf: false
},
data : localStorage.userIncidentData,
proxy: {
type: 'memory',
reader: {
type: 'json',
rootProperty: 'incidentList'
}
}
},
This is true: Object [object Object] has no method getRootNode
This method is no longer available in ST2, take a look at the API docs.
Actually, this is the only place in ST code that has this method left. Try editing sencha code in TreeStore
removeAll: function() {
this.getRootNode().removeAll(true);
this.callParent(arguments);
},
to
removeAll: function() {
this.getRoot().removeAll(true);
this.callParent(arguments);
},

Touch form ignoring submitted values

I'm submitting a form, but magically my form values don't get posted.
The onBeforeSubmit fires with the expected values and I can even do this.getValues() just before this.submit()
MyForm= function(config){
if ( typeof config !== 'object' ) {
config.url='test.php';
// config.standardSubmit = true;
config.items= [{
xtype: 'fieldset',
title: 'Login Details',
instructions: 'Please enter the information above.',
defaults: {
required: true,'
},
items: [{
xtype: 'textfield',
name : 'username'
}, {
xtype: 'passwordfield',
name : 'password'
}]
}];
var tbarBottom = {
xtype: 'toolbar',
dock: 'bottom',
items: [{
text: 'Login',
ui: 'confirm',
handler: function() {
this.onLoginClick();
},
scope: this
}]
};
config.listeners= {
beforesubmit: function(formpanel, values, options) {
console.log(values);//yup they are there
},
scope:this
}
config.dockedItems= [tbarBottom];
MyForm.superclass.constructor.call(this,config);
};
Ext.extend( MyForm, Ext.form.FormPanel,{
onResetClick: function() {
this.reset()
},
onLoginClick: function() {
console.log(this.getValues());//yup they are there
this.submit()
}
});
TL;DR This submits to the server, but I have no values being posted, do you have any idea why?
As per http://docs.sencha.com/touch/1-1/#!/api/Ext.data.Request-cfg-method the default for method is GET, it should be changed to POST in the config obj. (Eg config.method='POST') and off you go