sencha touch2 Login examples - sencha-touch-2

I need a cross-domain user login request instance, please help me, thank you!!
My code
Ext.data.JsonP.request({
url: 'http://25.30.2.3:8080/newvbo/applyaction!longin',
params: {
username:'13881901678',
password:'111111',
},
success: function(response, opts) {
alert('1');
},
failure: function(response, opts) {
alert('2');
}
});
My question is, I not receive the server returns the value, I wrong?

You can Try this
Ext.Ajax.request({
method:'GET',
contentType:'application/json; charset=utf-8',
dataType:'json',
url:'http://........Login',
disableCaching: false,
withCredentials: true,
useDefaultXhrHeader: false,
callbackKey: 'callback',
params: {
EmailId:Ext.getCmp('usernametwoway').getValue(),
Password:Ext.getCmp('loginpasswordtwoway').getValue(),
},
success:function(response)
{
console.log(response);
var res = response.responseText;
var jsonarr = Ext.decode(response.responseText);
console.log(jsonarr);
var myres = jsonarr[0].Result;
console.log(myres);
switch(myres)
{
case '1':
console.log("Registration response is successfully");
Ext.Viewport.setActiveItem({xtype:'passengerdetailstwoway'});
break;
case '0':
console.log("Failed");
Ext.Msg.alert("Error","Login Failed",Ext.emptyFn);
break;
Based on the responce you can Specify the Switch case..

Hi #jesse you can try for cross-domain something like this,
Ext.Ajax.request({
url: 'your_url_path',
timeout: 90000,
params: {
withCredentials: true,
useDefaultXhrHeader: false,
username:'13881901678',
password:'111111',
},
success: function(response, o) {
if(response != '') {
alert('1')
}
},
failure: function(response, o) {
alert('2')
}
})
For cross-domain you need put withCredentials: true and useDefaultXhrHeader: false.
I hope help you.

I would like to suggest you a different approach because sending login credentials as GET parameter to remote server over http is not a good idea, instead you should use POST method over HTTPS. Now you would think JSONP doesn't support POST so how can I do this, but if you are going to install your app on Phone or iPad it would do remote call from browser without using JsonP, which means you can use normal AJAX proxy to do whatever you want. Check this out:
How to use json proxy to access remote services during development
Which means this should work:
var obj = new Object();
obj.userId = username;
obj.password = password;
var data = Ext.JSON.encode(obj);
Ext.Ajax.request({
url : 'https://login_url',
method : "POST",
headers: {
'Content-Type': 'application/json'
},
params : data,
useDefaultXhrHeader : false,
withCredentials: true,
success : function(response) {
},
failure : function(response) {
}
});

Related

Hapi.js reply.redirect() is not working after image upload

I have the following code, in my server. I'm uploading an image using mongoose and s3 and then want to redirect the user to another page but this isn't happening. (the upload is successful).
Routes.js:
{path: '/success', method: 'GET', config: controller.success} ......
controller.js:
imageUpload: {
payload: {
maxBytes: 209715200,
output: 'file',
parse: true
},
handler: function(request, reply) {
var userName = request.auth.credentials.username;
members.findMemberByUsername(userName, function(err, member){
if (err) {
return reply.view('upload', {error: err});
} else if (member) {
var IDImagePath = request.payload.uploadedIDname.path;
console.log(IDImagePath);
members.addID(member, IDImagePath, function(err1){
console.log("add id error", err1);
if (err1){
return reply.view('upload', {error: err1, member: member});
} else {
console.log("SUCCESSFUL!");
return reply.redirect('/success');
}
});
}
});
}
},
success: {
handler: function (request, reply){
request.auth.session.clear();
console.log("success handler working!!");
return reply.view('success');
}
}
The code hits both console.log("SUCCESSFUL") and console.log("success handler working!!") in the controller but the redirect doesn't take place. By the way I'm using 'Jade' as the templating language so I have a success.jade. Thanks.
I found out what the problem was. I'm using AJAX on the client side but didn't have a 'success' method to reload the page:
$('#submitID').click(function(){
var formData = new FormData($('#uploadID')[0]);
$.ajax({
url: '/api/image',
type: 'POST',
xhr: function() { // Custom XMLHttpRequest
var myXhr = $.ajaxSettings.xhr();
if(myXhr.upload){
console.log(myXhr.upload);
}
return myXhr;
},
success: function(data) {
window.location.href = "/success"
},
data: formData,
cache: false,
contentType: false,
processData: false
}, "json");
});
I needed window.location.href = "/success" to reload the page. Please note the jQuery Ajax SUCCESS method is different to my '/success' route, they just happen to be the same word.

Sending data to Restful WCF service using ExtJS

This is how my WCF service is defined to authenticate a user:
[OperationContract]
[WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest, ResponseFormat = WebMessageFormat.Json)]
string validateUser(string username, string password);
It simply returns "Validated" or "NotValidated" as result.
And my ExtJS code is:
function loginclick(btn) {
var form = mainPanel.getForm();
if (form.isValid()) {
var userget = Ext.getCmp('txtuser').value;
var passget = Ext.getCmp('txtpass').value;
var myparams = { 'username': userget, 'password': passget };
Ext.Ajax.request({
url: 'http://localhost:52984/ExtJsRestfulService.svc/validateUser',
params: Ext.encode(myparams),
method: 'POST',
headers: this.header || { 'Content-Type': 'application/json;charset=utf-8' },
success: function (response, options) {
var s = response.responseText;
Ext.MessageBox.alert('Success', s);
},
failure: function (response, options) {
Ext.MessageBox.alert('Failed', 'Unable to get');
}
});
}
}
When i click on the login button, I get bad request(400) error. My service is not in the same solution. When I post the data to an aspx form in the same solution it works. What am I doing wrong?
What about:
Ext.Ajax.request({
url: 'http://yourdomain:52984/ExtJsRestfulService.svc/validateUser?username='+userget+'&password='+passget,
params: Ext.encode(myparams),
method: 'GET',
headers: this.header || { 'Content-Type': 'application/json;charset=utf-8' },
success: function (response, options) {
var s = response.responseText;
Ext.MessageBox.alert('Success', s);
},
failure: function (response, options) {
Ext.MessageBox.alert('Failed', 'Unable to get');
}
});
Can you fetch the params from the url?
Have you tried without encoding?
try
params: {
'username': userget,
'password': passget
}
Why do you have two times the params config?
You shouldn't use Ext.getCmp instead use Ext.ComponentQuery.query('myXtype[itemId=myItemId]')[0]; http://docs.sencha.com/extjs/4.2.2/#!/api/Ext.ComponentQuery
or
define the service in a manner that the call to it would be fullfilled like
string validateUser();
then inside the service do something similar to:
String pass = request.getParameter("password");
Like in java

Ajax request issue in sencha touch 2

I have a problem with sending an ajax request for the authentification..
i dont get errors but Network in chrome says : method : get , status : canceled , type : pending
and no response from this request ..
when i click on the file connection.js it point in this line :
// start the request!
xhr.send(requestOptions.data);
& my path name and the method get have the color RED
here is my code :
Ext.onReady(function() {
Ext.Ajax.request({
url: 'https://api.mysite.com/api/oauth/',
method: 'GET',
useDefaultXhrHeader:false,
disableCaching: false,
timeout:120000,
params: {
client_id: 'xxxxxx',
client_secret: 'xxx',
format: 'json'
},
success: function(response) {
var resultat = Ext.JSON.decode(response.responseText);
//the response is : {"status":"ok","auth_token":"xxxxxxxxxxx"}
if (resultat.status === "ok") {
if (!resultat.access_token === "") {
access_token = resultat.access_token;
me.sessionToken = resultat.sessionToken;
}
else
{
new Ext.Ajax.request({
url: 'https://api.mysite.com/api/oauth/signin',
method: 'post',
params: {
username: username,
password: password,
authtoken: resultat.access_token,
format: 'json'
},
success: function(response) {
var loginResponse = Ext.JSON.decode(response.responseText);
if (loginResponse.success === "true") {
// The server will send a token that can be used throughout the app to confirm that the user is authenticated.
me.sessionToken = loginResponse.sessionToken;
me.signInSuccess(); //Just simulating success.
} else {
me.signInFailure(loginResponse.message);
}
},
failure: function(response) {
me.sessionToken = null;
me.signInFailure('Login failed. Please try again later.');
}
});
}
// The server will send a token that can be used throughout the app to confirm that the user is authenticated.
} else {
//exception
}
}
,
failure: function(response) {
me.sessionToken = null;
Ext.Msg.alert('failed !!'); // its what it shows me
}
});

Sencha Touch: Using proxy and POST request and URL generation

I have been trying to do a post request using a proxy. I have tried the direct proxy, rest and ajax proxy, and haven't been able to find a working example for a POST request.
Is it possible? Because all the examples that I have seen seen to be using only GET.
Any working examples, or pointers in this direction?
Also, I couldn't figure what is the correct way to generate URLs for a proxy at run-time, for example, calling a function to return the URL.
It appears that this might not be possible:
http://www.sencha.com/forum/showthread.php?205557-Using-Ext.data.proxy.Ajax-via-a-POST-with-jsonData
If you look at the source code for Ext.data.proxy.Rest you'll see a config object for actionMethods. They're not documented, but you should be able to pass that as a config on your proxy to override it.
For example:
proxy: {
type: 'ajax',
url: 'path/to/foo',
actionMethods: {
create : 'POST',
read : 'POST',
update : 'PUT',
destroy: 'DELETE'
},
reader: {
type: 'json',
rootProperty: 'root',
totalProperty : 'totalCount'
}
}
Easiest example of POST request could be like this:
var obj = new Object();
obj.userId = username;
obj.password = password;
var data = Ext.JSON.encode(obj);
Ext.Ajax.request({
url : 'http://myservice/auth/login?_type=json', // url : this.getUrl(),
method : "POST",
headers: {
'Content-Type': 'application/json'
},
params : data,
useDefaultXhrHeader : false,
withCredentials: true,
success : function(response) {
Ext.Msg.alert("Success", "Welcome "+respObj.user.name);
},
failure : function(response) {
var respObj = Ext.JSON.decode(response.responseText);
Ext.Msg.alert("Error", respObj.status.statusMessage);
}
});
Please note here you can customize url as per your convenience.

how to get the server response.responseText after store load extjs 4

I'm having one problem with getting the response.responseText from the server response in extjs 4.
Below is my code to load the store:
store.load({
params: {
'projectid': this.projectid
},
callback: function (records, operation, success, response) {
console.log(records);
console.log(response.responseText);
}
});
Actually, when I made the request with the below function, I properly get the reponse.responseText.
Ext.Ajax.request({
url: 'login/GetLoginCheck.action',
method: 'GET',
params: {
'username': values['username'],
'password': values['password']
},
scope: this,
success: function(response) {
Ext.Msg.alert(response.responseText);
var redirect = response.responseText;
window.location.href = "" + redirect + ".jsp";
},
failure: function(response) {
Ext.Msg.alert('INVALID USERNAME OR PASSWORD');
}
});
So please suggest me how can I get the response.responseText from the store.load() having a callback function.
callback has 3 parameters...
try this :
store.load({
params: {
'projectid': this.projectid
},
callback: function (records, operation, success) {
console.log(operation.response.responseText);
}
});
I have faced a similar problem using Model.load(...), but in my case, operation.response was not defined. So, I have found another way to get it :
Model.load(1, {
success: function () {
// I haven't tested inside this callback yet
},
failure: function (record, operation) {
var response = operation.request.proxy.reader.rawData;
alert(response.message);
}
});
You may also try this..
Ext.create('Ext.data.Store',{
fields[],
proxy:{url:'store_url.json', reader:{type:'json',root:'data'}},
autoLoad:true,
listeners:{
load:function(store, record, success, opts){
var response_text = store.proxy.reader.rawData;
console.log(response_text);
}
}
})
In extjs 3.4 you can use this:
this.historyInvoiceHeaderGrid.store.load({
params:{start:0, limit:20},
callback: function (records, operation, success) {
console.log(this.reader.jsonData);
}});
This property store.reader.jsonData will return full response.
Maybe for someone it would be usefull in extjs 3.
You must set messageProperty in proxy reader in your 'Ext.data.Store'.
reader: {
type: 'json',
root: 'myDataList',
totalProperty: 'myTotalRecord',
successProperty: 'mySuccess',
messageProperty : 'myMsg'
}
when mySuccess returns false then invoked callback: function.
store.load({
params: {start: 0, limit: 15},
callback: function (records, operation, success) {
if (!success) {
try {
Ext.Msg.alert('Sorry !', operation.getError());
// operation.getError() returns myMsg value
}catch (e){
Ext.Msg.alert('Exception !', e);
}
}
}
});
Here is a json return from Java Servlet.
Map<String, Object> myDataMap = new HashMap<>(3);
try {
// Something
myDataMap.put("mySuccess", true);
myDataMap.put("myMsg", "Whats up khomeni !");
} catch (Exception e) {
myDataMap.put("mySuccess", false);
myDataMap.put("myMsg", "Whats wrong with me.");
}
String json = new Gson().toJson(myDataMap);
In Extjs 4.x it is working like this
myStore.load({
url: 'myurl',
method: 'GET',
callback: function(records, operation, success) {
var jsonStr = Ext.JSON.decode(operation.response.responseText);
alert(jsonStr.message);
}
});
In Extjs 5 you have to do like this
myStore.load({
url: 'myurl',
method: 'GET',
callback: function(records, operation, success) {
var message=forecastMethodStore.getProxy().getReader().rawData.message;
}
});
But the key point here is you should set the message in JSON response from java side.
Sample: {"Root":[], "message":"duplicates"}"
Hope this will help someone.