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

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.

Related

Vee-validate (VueJS) - evaluating a condition asynchronously

Can I make a custom validation rule that returns true/false based on a AJAX request? the problem is that the validate call has finished running when the AJAX call completes.
Do I need to have the rule set/unset a boolean variable based on which the field is valid/invalid?
const isValidNameRule = {
getMessage(field)
{
return "The name must be unique."
},
validate(validatingName)
{
var formData = new FormData();
formData.append("validatingName", validatingName);
this.$http.post("/api/isValid?name=" + validatingName, formData)
.then(function (response) {
// success
return true;
}, function (response) {
// error
return false;
});
}
};
Didn't know how to work with Promises.
Eventually got it working by extending one of the official samples:
const customRule = {
getMessage(field, params, data) {
return (data && data.message) || 'Something went wrong';
},
validate(aValue) {
return new Promise(resolve => {
var formData = new FormData();
formData.append("nameFilter", aValue);
$.ajax({
type: "POST",
url: url,
data: {
action: "validate",
value: aValue,
}
}).done(function (data) {
if (!ok)
{
resolve({
valid: false,
data: {message: "Condition not met"}
});
}
else
{
resolve({
valid: !! aValue,
data: undefined
});
}
});
});
}
};

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.

How to pass Client Side data to Server Side using Ember.js

I'm studying Ember.js myself and I'm stuck with a problem I'm creating a sample app and I need to send the client side values to Server Side but I dont know how to do that I know the traditional way like the below code
function create() {
var data = {
'EmailID': $('#emailid').val(),
'password': $('#password').val()
}
$.ajax({
url: '/EmberNew/Home/Create',
type: 'POST',
data:data,
success: function (response) {
alert("hi");
}
});
return false;
}
but In Ember i dont Know How to do that my current code is given below
//Application
App = Em.Application.create();
//Model
App.Users = Em.Object.extend({
name: null,
password:null
});
//View
App.UserTextField = Em.TextField.extend({
insertNew: function () {
App.alertController.alertDetails();
}
});
App.PassTextField = Em.TextField.extend({
insertNew: function () {
App.alertController.alertDetails();
}
});
//controller
App.AlertController = Em.ObjectController.extend({
content: [],
username: '',
password: '',
alertDetails: function () {
var me = this;
var username = me.get("username");
var password = me.get("password");
alert('The User Name Is' + 'username' + 'And Password Is' + 'password');
}
});
App.alertController = App.AlertController.create();
I got the textbox values from alertDetails function and how can I pass them to server side
App.Record = Ember.Object.extend({
name: '',
other: ''
}).reopenClass({
records: [],
find: function() {
var self = this;
$.ajax({
url: "/api/records/",
type: "GET",
cache: false,
dataType: "json",
beforeSend: function() {
//if you want to call this often and need to clear + reload it
return self.records.clear();
},
success: function(results) {
var result;
for (_i = 0, _len = results.length; _i < _len; _i++) {
result = results[_i];
self.records.push(self.records.addObject(App.Record.create(result)));
}
},
error: function() {
return alert("error: failed to load the records");
}
});
return this.records;
}
});
Now that you have your model setup, you can call it from your route model hook
App.RecordsRoute = Ember.Route.extend({
model: function() {
return App.Record.find();
}
});
The find method returns an empty array right away, your template is then bound to it. When the ajax call returns w/ success and you update that array the handlebars template will update it for you w/out any DOM or jQuery glue code

sencha touch2 Login examples

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) {
}
});

How to navigate different to view in JSONP request "callback" method

//Below is my callback method which returns some response code.Now the thing is that i need to navigate to different view from the callback method.This logic i am using in userlogin. Provide me some solution that i can navigate to different view below i declared some code which i used to navigate to different view which works fine outside callback method not inside callback method.
Ext.data.JsonP.request({
url:'url',
method: 'POST',
callbackkey: 'callback',
params: {
userID: user_Id,
password: password,
format: 'json'
},
callback: function (response, value, request) {
//Logic should come here
}
else
{
}
},
failure: function (response, request) {
}
});
enter code here
//Below is the cofig entry
config: {
refs: {
homepage:'HP'
}
}
//I am adding below code in success block but getting error
var noteEditor = this.getHomepage();
Ext.Viewport.animateActiveItem(noteEditor, this.slideLeftTransition);
assuming you doing something like
Ext.data.JsonP.request({
url:'url',
method: 'POST',
callbackkey: 'callback',
params: {
userID: user_Id,
password: password,
format: 'json'
},
scope: this, /// fix handler scope
callback: function (response, value, request) {
if () {
//Logic should come here
var noteEditor = this.getHomepage();
Ext.Viewport.animateActiveItem(noteEditor, this.slideLeftTransition);
}
else
{
}
},
failure: function (response, request) {
}
});
you have to add a scope: this property to the ajax call.
Cheers, Oleg