Extjs4, wait for ajax request - extjs4

I should run multiple ajax requests in one button click, but all requests should wait until the first one is executed. I have tried to put all requests in the success callback of the first one but this gives this error:
TypeError: o is undefined
return o.id;
And just the first request is executed.
This is my code:
if(form1.isValid()) {
form1.submit(me._genFormSubmitAction('my_DB','my_Action', function() {
console.log('form1 success');
//Submit Form2
if(form2.isValid()) {
form2.submit(me._genFormSubmitAction('my_DB','my_Action', function() {
console.log('form2 success');
}));
//Submit Form3
....
_genFormSubmitAction:
_genFormSubmitAction: function(db,action, successCallback) {
var me = this;
return {
clientValidation : true,
url : me.getApplication().apiUrl,
waitMsg : '<p align=right>..الرجاء الإنتظار</p>',
async:false,
params : {
_module: 'administrationcassocial',
_action: action,
_db:db
},
success : function(form, action) {
if(action.result.success == true) {
Ext.callback(successCallback, me);
form.owner.destroy();
} else {
console.log('url=',url);
Ext.Msg.alert(action.result.error, action.result.errormessages.join("\n"));
}
},
failure : function(form, action) {
switch (action.failureType) {
case Ext.form.action.Action.CLIENT_INVALID:
Ext.Msg.alert('Failure', 'Form fields may not be submitted with invalid values');
break;
case Ext.form.action.Action.CONNECT_FAILURE:
Ext.Msg.alert('Failure', 'Ajax communication failed');
break;
case Ext.form.action.Action.SERVER_INVALID:
Ext.Msg.alert(action.result.error, action.result.errormessages.join("\n"));
}
}
};
}

This is a scope issue.
The callback of form1.submit happens in the callback own scope, so it has no idea what form2 is.
You can try:
if(form1.isValid()) {
var me = this;
form1.submit(me._genFormSubmitAction('my_DB','my_Action', function() {
console.log('form1 success');
//Submit Form2
if( me.form2.isValid() ) {
form2.submit(me._genFormSubmitAction('my_DB','my_Action', function() {
console.log('form2 success');
}));
}
}));
}
Or the more proper solution in my view:
// Added aScope var
_genFormSubmitAction: function( db,action, aScope, successCallback ) {
var me = this;
return {
// ...
scope: aScope
}
}
Then you call:
form1.submit(me._genFormSubmitAction('my_DB','my_Action', this, function() {
}));

Related

How to call function on XMLHttpRequest status = true in Vue 2? I get "this.xxxx not a function" error

I have the following code, which works fine except for the "makeToast" function that I'm trying to call when status response is true. I get a "this.makeToast is not a function" error on the console.
This function is working fine if I call it after the XMLHttpRequest code. The data is also not being assigned to the msgForm property. I could not figure out why. The "alert(..." message work fine.
<script>
import ToastMixins from '/src/mixins/ToastMixins'
let config = {
headers: {
}
}
export default {
name: 'ModalDestaque',
mixins: [
ToastMixins
],
methods: {
myFunction() {
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
console.log('onreadystatechange');
console.log('responseText 1', xhr.responseText);
this.loading = false;
if (xhr.status == 200) {
console.log('responseText 2', xhr.responseText);
let responseObj = JSON.parse(xhr.responseText);
console.log('responseObj', responseObj);
if (responseObj.status == true) {
//alert('Ok');
// this is not working:
this.msgForm = "Message success!";
this.makeToast('b-toaster-bottom-right', true, 'success');
} else {
alert('Not ok...');
}
}
}
};
}
}
}
What am I doing wrong?
I've found the solution while reading the docs at W3 Schools.
W3 Schools AJAX XMLHttp - Multiple Callback Functions
Although, I haven't found a working example anywhere.
In my code, at the button click event that triggers the XMLHttpRequest, I've added the function name "callToast" as a variable, so:
#click="onClickSubmit(myValue, myId, myTitle, callToast)"
Then in the script:
<script>
onClickSubmit(amount, id, title, cFunction) {
// stuff
if (xhr.status == 200) {
let responseObj = JSON.parse(xhr.responseText);
if (responseObj.status == true) {
// here I call the callToast function:
cFunction(this);
alert('Ok');
} else {
alert('Not ok...');
}
}
},
callToast() {
this.msgForm = "Message success!";
this.makeToast('b-toaster-bottom-right', true, 'success');
}
</script>

How to avoid duplicate entries in IBM JSONStore

WL.JSONStore.get(collectionName).change(data, options) method does not seem to work for duplicate values. I get duplicate values entered whenever data is loaded through the adapter. Below is the code that I have used to avoid duplicate entries.
init(){
console.log('JSONStore init function callled');
let collections = {
activities: {
searchField: {serialKey: 'string'},
adapter: {
name: 'ServiceAdapter',
add: 'pushActivities',
remove: 'removeActivity',
replace: 'replaceActivity',
load: {
procedure: 'getActivities',
params: [],
key: 'rows'
}
}
}
}
WL.JSONStore.init(collections).then((success) => {
console.log('-->JSONStore init success')
}, (failure) => {
console.log('-->JSONStore init failed', failure)
})
}
load() {
let dataRequest = new
WLResourceRequest("/adapters/ServiceAdapter/getActivities",
WLResourceRequest.GET);
dataRequest.send().then(
(response) => {
this.data = response.responseJSON.rows;
this.activityService.put(this.data);
})
}
put(data){
console.log('--> JSONStore put function called');
let collectionName = 'activities';
let options = {
replaceCriteria: ['serialKey'],
addNew: true,
markDirty: false
};
WL.JSONStore.get(collectionName).change(data, options).then((success) => {
console.log('--> JSONStore put success')
}, (failure) => {
console.log('--> JSONStore put failed', failure)
})
}
Adapter Function:
function getActivities() {
var path = 'employees' + '/_all_docs?include_docs=true';
var input = {
method : 'get',
returnedContentType : 'json',
path : path,
};
var response = MFP.Server.invokeHttp(input);
if (!response.rows) {
response.isSuccessful = false;
return response;
} else {
var results = [];
for (var i=0; i < response.rows.length; i++) {
results.push(response.rows[i].doc);
}
return {'rows': results};
}
}
I have even tried by:
searchFields: {serialKey: 'string',serialId: 'string'}
replaceCriteria: ['serialKey','serialId']
But no luck.
NOTE: There is no error in the former one, whereas the later results in an error.
ERROR : PROVISION_TABLE_SEARCH_FIELDS_MISMATCH (I have already tried to destroy the collection and perform the change, as the link suggests.
I have followed the below link:
https://www.youtube.com/watch?v=Ep6w1zXoI-k
I am using the below versions:
mfpdev : 8.0.0-2017102406
Let me know if you need any more details.

Bind validation results from ajax request to form model in mithril

Hi I would like to bind html inputs with validation response model returned from API like that:
{"userName":[{"memberNames":["UserName"],"errorMessage":"Field User Name is required."}],"acceptTerms":[{"memberNames":["AcceptTerms"],"errorMessage":"Accepting terms is requried"}]}
And my component in mithril
var RegisterPage = {
vm: {
userName: m.prop(),
password: m.prop(),
confirmPassword: m.prop(),
acceptTerms: m.prop(false)
},
controller: function (args) {
this.title = 'Register new user account';
this.vm = RegisterPage.vm;
this.register = function (e) {
e.preventDefault();
apiRequest({ method: "POST", url: "http://localhost:12116/auth/register", data: RegisterPage.vm }).then(RegisterPage.vm.registerResult)
}
},
view: function (ctrl, args) {
return m('form.input-group',
[
m('.input-row', [m('label', 'Email'), m('input[type=email][placeholder=Your email address like myemail#email.com]', { onchange: m.withAttr("value", ctrl.vm.email) })]),
m('.input-row', [m('label', 'Password'), m('input[type=password][placeholder=your password]', { onchange: m.withAttr("value", ctrl.vm.password) })]),
m('.input-row', [m('label', 'Confirm password'), m('input[type=password][placeholder=your password]', { onchange: m.withAttr("value", ctrl.vm.confirmPassword) })]),
m('.input-row', [m('label', 'Accept terms and conditions'), m('input[type=checkbox]', { onchange: m.withAttr("checked", ctrl.vm.acceptTerms) })]),
m('button[type=submit].btn btn-positive btn-block', { onclick: ctrl.register }, 'Register account')
]);
}
}
I am looking for some generic solution. I would like to mark invalid fields with css class and add field validation message.
UPDATE
In my project I use some wrapper around m.request to get more details when 400 is thrown
function apiRequest(args) {
NProgress.start();
if (!args.unwrapError) {
args.unwrapError = function (data, xhr) {
if (xhr.status === 401)
{
layout.badRequestMsg(xhr.statusText);
}
NProgress.done();
return data;
}
}
if (!args.unwrapSuccess) {
args.unwrapSuccess = function (data, xhr) {
NProgress.done();
return data;
}
}
return m.request(args);
}

Why could not load data from Adapter into JSONStore?

function getListPhoneNumbers() {
var data = {listContacts:[{name:'Ho Cong Vi',number:'12345666'},{name:'hcv',number:'6543218'}]};
WL.Logger.info('Data:'+JSON.stringify(data));
return data;
}
function addListPhoneNumber(data) {
WL.Logger.debug('Add Data to JSONStore: ' + data);
return;
}
function updateListPhoneNumber(data) {
WL.Logger.debug('Updata Data from JSONStore: ' + data);
return;
}
function deleteListPhoneNumber(data) {
WL.Logger.debug('Delete Data from JSONStore: ' + data);
return;
}
This is my code in main.js:
$('#show-all-btn').on('click', showAllData);
var collectionName = 'Contacts',
collections = {};
collections[collectionName] = {
searchFields: {
name: 'string',
number: 'string'
},
adapter: {
name: 'listPhoneNumbers',
add: 'addListPhoneNumber',
replace: 'updateListPhoneNumber',
remove: 'deleteListPhoneNumber',
load: {
procedure: 'getListPhoneNumbers',
param: [],
key: 'listContacts'
}
}
};
WL.JSONStore.init(collections)
function showAllData() {
$('#show-all-btn').on("click", function() {
$('#info').show();
});
WL.JSONStore.get(collectionName).load().then(function(res) {
alert('ok' + JSON.stringify(res));
}).fail(function(errorObject) {
alert(errorObject);
});
}
This is the error:
[wl.jsonstore] {"src":"load","err":18,"msg":"FAILED_TO_LOAD_INITIAL_DATA_FROM_ADAPTER_INVALID_L‌​OAD_OBJ","col":"Contact","usr":"jsonstore","doc":{},"res":{}
The error message is saying the load object you passed is invalid. This is probably because you passed param instead of params. Notice the s at the end.
Also, this code:
WL.JSONStore.init(collections)
function showAllData() {
$('#show-all-btn').on("click", function() {
$('#info').show();
});
WL.JSONStore.get(collectionName).load().then(function(res) {
alert('ok' + JSON.stringify(res));
}).fail(function(errorObject) {
alert(errorObject);
});
}
Looks wrong, maybe what you meant to write is something like this:
WL.JSONStore.init(collections).then(function () {
WL.JSONStore.get(collectionName).count().then(function (numberOfDocsInCollection) {
if(numberOfDocsInCollection < 1) {
WL.JSONStore.get(collectionName).load().then(function(res) {
//handle success
})
}
})
});
I omitted handling failures for brevity. Note that the load will will duplicate items in the collection if those items already exist, hence the count to check if the collection is empty or not.

Inheritance for durandal (HotTowel) viewmodels?

Simple question, pretty sure it's a complicated answer :)
Is it possible to implement some form of inheritance for viewmodels in Durandal?
So if you have a viewmodel something like this:
define(['durandal/app', 'services/datacontext', 'durandal/plugins/router', 'services/logger'],
function (app, datacontext, router, logger) {
var someVariable = ko.observable();
var isSaving = ko.observable(false);
var vm = {
activate: activate,
someVariable : someVariable,
refresh: refresh,
cancel: function () { router.navigateBack(); },
hasChanges: ko.computed(function () { return datacontext.hasChanges(); }),
canSave: ko.computed(function () { return datacontext.hasChanges() && !isSaving(); }),
goBack: function () { router.navigateBack(); },
save: function() {
isSaving(true);
return datacontext.saveChanges().fin(function () { isSaving(false); })
},
canDeactivate: function() {
if (datacontext.hasChanges()) {
var msg = 'Do you want to leave and cancel?';
return app.showMessage(msg, 'Navigate Away', ['Yes', 'No'])
.then(function(selectedOption) {
if (selectedOption === 'Yes') {
datacontext.cancelChanges();
}
return selectedOption;
});
}
return true;
}
};
return vm;
//#region Internal Methods
function activate(routeData) {
logger.log('View Activated for id {' + routeData.id + '}, null, 'View', true);
});
}
//#endregion
function refresh(id) {
return datacontext.getById(client, id);
}
});
Is it possible to make that into some kind of base type and inherit further viewmodels from it, being able to extend the requires list and so on?
There is another question on this, but the viewmodels don't appear to be quite the same as the one's that I build for durandal/HotTowel.
Thanks.
I'm pretty sure this can be accomplished with jQuery's extend method. This just occurred to me, so there may be something that I'm missing, but a basic example would be something along the lines of:
basevm.js
... your mentioned viewmodel
inheritingvm.js
define(['basevm'], function (basevm) {
var someNewObservable = ko.observable();
var vm = $.extend({
someNewObservable : someNewObservable
}, basevm);
return vm;
});
Please let me know if this works. I just coded from the top of my head and it hasn't been tested.
Just based off what your saying I came up with this. Let me know if this works for you and if it doesn't then let me know what I did wrong.
Thanks.
viewmodelBase
define(['durandal/app', 'services/datacontext', 'durandal/plugins/router', 'services/logger'],
function (app, datacontext, router, logger) {
var vm = function () {
var self = this;
this.someVariable = ko.observable();
this.isSaving = ko.observable(false);
this.hasChanges = ko.computed(function () { return datacontext.hasChanges(); });
this.canSave = ko.computed(function () { return datacontext.hasChanges() && !self.isSaving(); });
};
vm.prototype = {
activate: function (routeData) {
logger.log('View Activated for id {' + this.routeData.id + '}', null, 'View', true);
},
refresh: function (id) {
return datacontext.getById(client, id);
},
cancel: function () {
router.navigateBack();
},
goBack: function () { router.navigateBack(); },
save: function() {
var self = this;
this.isSaving(true);
return datacontext.saveChanges().fin(function () { self.isSaving(false); })
},
canDeactivate: function() {
if (datacontext.hasChanges()) {
var msg = 'Do you want to leave and cancel?';
return app.showMessage(msg, 'Navigate Away', ['Yes', 'No'])
.then(function(selectedOption) {
if (selectedOption === 'Yes') {
datacontext.cancelChanges();
}
return selectedOption;
});
}
return true;
}
};
return vm;
});
parent viewmodel
define([viewmodelBase], function (vmbase) {
var vm1 = new vmbase();
vm1.newProperty = "blah";
var vm2 = new vmbase();
});
I wrote a post on my blog that addresses this issue. In short, I use prototypical inheritance for all of my modal dialog views in one of my projects. Here's the link to the post I wrote (feel free to skip to the code part) and a jsFiddle example that demonstrates it.
Simplified example that can work in Durandal (NOTE: each view-model returns its constructor function, not an object):
viewmodels/modal.js
define(['durandal/system'],
function(system) {
var modal = function () {
this.name = 'Modal';
}
modal.prototype = {
activate: function() {
system.log(this.name + ' activating');
},
attached: function(view) {
system.log(this.name + ' attached');
},
deactivate: function() {
system.log(this.name + ' deactivating');
},
detached: function(view, parent) {
system.log(this.name + ' detached');
}
};
return modal;
});
viewmodels/child.js
define(['durandal/system', 'viewmodels/modal'],
function(system, Modal) {
var child = function() {
this.name = 'Child Modal';
}
// inherits from Modal
child.prototype = new Modal();
child.prototype.constructor = child;
child.prototype._super = Modal.prototype;
// overrides Modal's activate() method
child.prototype.activate = function() {
this._super.activate.call(this); // we can still call it from the _super property
system.log(this.name + ' activating [overridden version]');
};
return child;
});
I prefer this implementation because it supports code reuse, conforms to OOP principles as best as javascript allows, and it gives me the ability to call the base class' methods via the _super property when I need to. You can easily convert this as needed.