sencha-touch: Login request-response - sencha-touch

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

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();

Form submit isn't working

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

Android back button click showing blank page

I am new to sencha. Almost spent 2 day to understand sencha routing/history support to implement android back button. but ended up with blank screen always although navigation is working. Please help me to find out what wrong am i doing or what is wrong with my application architecture.
app.js
Ext.application({
name: "WorkFlow",
models: [],
stores: [],
controllers: ["WFController"],
views: ["LoginForm","WorkList"],
launch: function () {
var loginForm = {
xtype: "loginform"
};
var workList = {
xtype: "worklist"
};
Ext.Viewport.add([loginForm,workList]);
// set up a listener to handle the back button for Android
if (Ext.os.is('Android')) {
document.addEventListener("backbutton", Ext.bind(onBackKeyDown, this), false);
function onBackKeyDown(e) {
e.preventDefault();
// you are at the home screen
if (Ext.Viewport.getActiveItem().xtype == loginForm.xtype ) {
navigator.app.exitApp();
}else {
this.getApplication().getHistory().add(Ext.create('Ext.app.Action', {
url: 'loginForm'
}));
}
}
}
}
});
LoginForm.js
var formPanel = null;
Ext.define("WorkFlow.view.LoginForm", {
extend: "Ext.form.Panel",
alias: "widget.loginform",
initialize: function () {
this.callParent(arguments);
formPanel = Ext.create('Ext.form.Panel', {
fullscreen: true,
items: [{
xtype: 'titlebar',
title: 'Login',
docked: 'top'
},
{
xtype: 'fieldset',
items: [
{
xtype: 'textfield',
name : 'username',
label: 'Username',
},
{
xtype: 'passwordfield',
name : 'password',
label: 'Password',
},
{
xtype: 'textfield',
name : 'deviceId',
label: 'Device Id',
}
]
}]
});
formPanel.add({
xtype: 'toolbar',
docked: 'bottom',
layout: { pack: 'center' },
items: [
{
xtype: 'button',
text: 'Login',
handler: this.onLoginTap,
scope: this
},
{
xtype: 'button',
text: 'Cancel',
handler: function() {
formPanel.reset();
}
}
]
});
},
onLoginTap: function() {
this.fireEvent("loginCommand", this);
},
});
WorkList.js
Ext.define("WorkFlow.view.WorkList", {
extend: "Ext.form.Panel",
alias: "widget.worklist",
config:{
html: 'This is worklist...',
}
});
WFController.js
Ext.define("WorkFlow.controller.WFController", {
extend: "Ext.app.Controller",
config: {
refs: {
loginForm: "loginform",
workList: "worklist",
},
control: {
loginForm: {
loginCommand: "onLoginCommand",
}
},
routes: {
'loginForm': 'activateLoginFormPage'
}
},
activateLoginFormPage: function(){
Ext.Viewport.animateActiveItem(this.getLoginForm(), this.slideRightTransition);
},
slideLeftTransition: { type: 'slide', direction: 'left' },
slideRightTransition: { type: 'slide', direction: 'right' },
onLoginCommand: function () {
var values = formPanel.getValues();
window.plugins.AuthPlugin.authenticate(values.username,values.passwordvalues.deviceId,values,
function loginCallBack(result){
if(result=="PASSWORD_MATCH"){
loginForm.onLoginSuccess();
}
});
},
onLoginSuccess: function(){
this.getApplication().getHistory().add(Ext.create('Ext.app.Action', {
url: 'loginFormroute/workList'
}));
Ext.Viewport.animateActiveItem(this.getWorkList(), this.slideRightTransition);
},
launch: function () {
},
init: function () {
}
});
Not totally sure of what you are trying to accomplish, but if it is just regular navigation (press back to return to previous tab etc.) then you do not need to bind anything to the android back button. You should use routes and create a history item for every step the user takes.
Example: I have an app with two tabs, in one of the tabs there is a list of locations and in the second one there is a map with the same locations marked. Pressing on wither a list item or a location in the map generates the same details screen. So this is what I got to get this to work:
Routes:
routes: {
'tab/:tabId': 'gotoTab',
'details/:stnId': 'viewDetails'
},
Important part: ensure that you create history items for each step, I basically have two in this app, one for changing tabs and one for opening a details page.
So, tabs:
//If I change to the 'map' tab, it will navigate the browser to myapp.com/#tab/map
// and therefore creating a history item.
onTabpanelActiveItemChange: function(container, value, oldValue, options) {
this.getApplication().getHistory().add(new Ext.app.Action({
url: 'tab/' + value.id
}), true);
},
Similar for my details page, only it is a function that is called from two seperate handlers (one for the list and one for the map):
showDetails: function(record, staticUrl, doUpdate) {
/*some logic stripped out*/
this.getApplication().getHistory().add(new Ext.app.Action({
url: 'details/' + record.data.id
}), true);
}
After this you are more or less ready to go, if you can guarantee that users always start at the main page. If you enable deep-linking etc. than you will need to restore a state for those links. e.g. a #/tab/map/ link should open the app with the map tab active.
If we take my details page as an example, we have a few things to do. First of all re-create history (press back on details page returns to tab-list by default in my app) and then ensure that stores are loaded and so on.
So as a final example, my viewDetails route:
var store = Ext.StoreManager.get("dcStations");
//recreate history
this.getApplication().getHistory().add(new Ext.app.Action({
url: 'tab/list'
}), true);
this.getApplication().getHistory().add(new Ext.app.Action({
url: 'details/' + stnId
}), true);
//make sure the store is loaded, then show the details page with passed id
store.on("load", function() {
this.showDetails(Ext.StoreManager.get("dcStations").getById(stnId));
}, this);
Hope that this boosts your efforts in getting started with routes and history management

Variables between List

My problem is... I have a list who is completed by a store and this store comes from a proxy (json). When i clik in a item of the list i need a detail information, and this detail information comes from anothe json.
For example:
ArtistList and ArtistDetail
When i click in an item of artistList i need a call to
http://localhost/json-detail/45
if i click in another item...
http://localhost/json-detail/50 etc...
My problem is that i can't send the parameter to the other view... or maybe the error is in my concept of lists... :S
This is my list view:
var listaArtistas = {
xtype: 'list',
title: 'Artistas',
height: 240,
store: {
autoLoad: true,
fields: ['node'],
proxy: {
type: 'ajax',
url: 'http://localhost/json-artistas',
reader: {
type: 'json',
rootProperty: 'nodes'
}
}
},
listeners: {
itemtap: function(lista,index,target,record,e,eOpts)
{
var artistDetail = new Ext.create('app.view.ArtistDetail');
artistDetail.setArtistID('45');
panelHomeNav.push(artistDetail);
}
},
itemTpl: tpl
};
This is my detail:
Ext.define('app.view.ArtistDetail',{
extend: 'Ext.Panel',
xtype: 'artistdetail',
style: "background-image:url('/resources/images/fondoartista.png');",
config:{
title: 'Artistas',
iconCls: 'star',
ArtistID: '',
items:
{
title: 'Artistas',
items: [artistDetailPanelContenedor]
}
}});
And need something like this
var listaEspectaculo = {
xtype: 'list',
title: 'Artistas',
store:
{
autoLoad: true,
fields: ['node'],
proxy: {
type: 'ajax',
url: 'http://localhost/json-artistasdetail/'+getArtistID, <<<<<<<<<<------ PROBLEM
reader: {
type: 'json',
rootProperty: 'nodes'
}
}
},
listeners: {
itemtap: function(lista,index,target,record,e,eOpts)
{
var eventDetail = new Ext.create('app.view.EventDetail');
panelHomeNav.push(eventDetail);
}
},
itemTpl: tplEspectaculo
};
THx for help !!!
Maybe this could help:
How to pass value from controller to data store in sencha touch
handler: function () {
Ext.dispatch({
controller: MyApp.controllers.controller,
action: 'myActionOnController',
id: e.get{'id'}
});
}
You can call ext.dispatch from your "itemtap", then in the controller you can call a new view with you parameters, remember use something like this:
myActionOnController: function (options) {
var city = options.id; //if you want to use your parameters
var newView = Ext.create('MyApp.view.viewOfSomething');
this.getMain().push(newView);
},

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