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
});
}
});
});
}
};
I'm new to the hapijs. Can someone tell me what's the difference between POST and GET in hapijs? For some reason my POST method doesn't work at all so I do is INSERT via GET function.
GET:
server.route({
method: 'GET',
path: '/index/{orderId}',
config: {
handler: test,
validate: {
params: {
orderId: Joi.string()
.required()
.description('Order indentifier')
}
}
}
});
And test function:
function test (request, reply) {
console.log(request.params.orderId);
var params = {orderId: request.params.orderId}
connection.query('INSERT QUERY HERE', function (err, res, fields) {
if (err) throw error;
console.log(res);
reply(res);
});
}
var users = m.request({
method: "GET",
url: "hoge.json",
unwrapSuccess: function(response) {
return response;
},
unwrapError: function(response) {
//return response.error;
return "404 error";
}
});
users.then(function(result) {
console.log(result);
});
After delete "hoge.json".
I want to catch "404 error",but
uncaught SyntaxError: Unexpected token <
2016/2/18 add
I want to test alert ("unwrapError");
Below code is always alert ("unwrapSuccess");
How to change below code?
What is the unwrapError?
▼js
var users = m.request({
method: "GET",
url: "hoge.json",
unwrapSuccess: function(response) {
alert ("unwrapSuccess");
return response;
},
unwrapError: function(response) {
alert ("unwrapError");
return "error";
}
});
users.then(function(result) {
console.log(result);
});
▼hoge.json
[{"name": "John"}, {"name": "Mary"}]
If you take a look at mithril's source code you will see that m.request is just a wrapper for the XMLHttpRequest API. And that's what happens when the request's readyState attribute changes:
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status >= 200 && xhr.status < 300) {
options.onload({type: "load", target: xhr})
} else {
options.onerror({type: "error", target: xhr})
}
}
}
So mithril's unwrapError callback will be called whenever the response status is not a 2xx.
I updated the fiddle calling a URL that returns a 500 response and now the unwrapError is called.
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.
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.