Unobtrusive validation with dynamically loaded partial view - asp.net-mvc-4

I'm loading partail view on button click
function loadview(ele) {
if (ele == 'account') {
$('#updateprofile').load('#Url.Action("UpdateProfile", "Account")');
$.validator.unobtrusive.parse($("#updateprofile"));
}
if (ele == 'password') {
$('#changepassword').load('#Url.Action("ChangePassword", "Account")');
$.validator.unobtrusive.parse($("#changepassword"));
}
}
Validation is not working on partial view loaded by ajax request. However it works with #Html.Partial("ChangePassword", Model.changepassword)
Any help;

You have to call the parse function in the callback function of load:
function loadview(ele) {
if (ele == 'account') {
$('#updateprofile').load('#Url.Action("UpdateProfile", "Account")', function () {
$.validator.unobtrusive.parse($("#updateprofile"));
});
}
if (ele == 'password') {
$('#changepassword').load('#Url.Action("ChangePassword", "Account")', function () {
$.validator.unobtrusive.parse($("#changepassword"));
});
}
}
Right now, you are calling the parse function before any content could be loaded.

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>

Yii2 - activeform ajax validation with normal form submit

Using the beforeSubmit function of yii.activeForm.js, how can I make it perform a normal form submit when validation passes?
I have tried the following:
$('.ajax-form').on('beforeSubmit', function (event) {
var form = $(this);
var url = form.attr('action');
var type = form.attr('method');
var data = form.serialize();
$.ajax({
url: url,
type: type,
data: data,
success: function (result) {
if (result.errors.length != 0) {
form.yiiActiveForm('updateMessages', result.errors, true);
}
else if (result.confirmed == true) {
$('.confirm-panel').show();
}
else {
return true;
}
},
error: function() {
alert('Error');
}
});
// prevent default form submission
return false;
});
Controller:
public function actionProcess()
{
$model = $this->findModel($id);
if (Yii::$app->request->isAjax) {
$return_array = [
'errors' => [],
'confirmed' => false,
];
Yii::$app->response->format = Response::FORMAT_JSON;
$return_array['errors'] = ActiveForm::validate($model);
if ($model->confirm == 1) {
$return_array['confirmed'] = true;
}
return $this->asJson($return_array);
}
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['success']);
}
return $this->render('process', [
'model' => $model,
]);
}
As you can see I am also trying to return additional data in my AJAX response. The problem I am having is the return true in the ajax success isn't working. I can't seem to break out of the function. I have also tried form.submit() here but this just does a submit loop via AJAX.
By the way I am not using enableAjaxValidation because I have some additional custom validation that happens in my controller. So this is why I have created my own custom handler for this.
First of all, you can't return true from within an ajax success function to continue form submission as it is javascript and the last line return true is already executed before the response is received so the form ain't going to submit by returning true inside the success function.
You need to use the event afterValidate if you want to submit your page manually after successful ajax validation rather than using beforeSubmit as it will go into an infinite loop if you try to submit the form using $("form").submit() inside the ajax success function. so change your line
$('.ajax-form').on('beforeSubmit', function (event) {
to
$('.ajax-form').on('afterValidate', function (event) {
and then change your success function to
success: function (result) {
if (result.errors.length != 0) {
form.yiiActiveForm('updateMessages', result.errors, true);
}
else if (result.confirmed == true) {
$('.confirm-panel').show();
}
else {
form.submit();
}
},
Hope it helps you out.
Input validation should be made in models no matter if it's built in or custom. Then you can easily use the default ajax validation.
For creating custom validators check http://www.yiiframework.com/doc-2.0/guide-input-validation.html#creating-validators
you need not to write any such code for this propose. Yii can handle ajax validations it-self. only thing that you need to do is enable it in active form like.
php $form = ActiveForm::begin([
'id' => 'contact-form',
'enableAjaxValidation' => true,
]); ?>
and placing this code in controller after initialize $model.
if (Yii::$app->request->isAjax) {
Yii::$app->response->format = Response::FORMAT_JSON;
return = ActiveForm::validate($model);
}

Vue js : _this.$emit is not a function

I have created a Vue component call imageUpload and pass property as v-model
<image-upload v-model="form.image"></image-upload>
and within imgeUpload component
I have this code
<input type="file" accept="images/*" class="file-input" #change="upload">
upload:(e)=>{
const files = e.target.files;
if(files && files.length > 0){
console.log(files[0])
this.$emit('input',files[0])
}
}
and I received
Uncaught TypeError: _this.$emit is not a function
Thanks
Do not define your method with a fat arrow. Use:
upload: function(e){
const files = e.target.files;
if(files && files.length > 0){
console.log(files[0])
this.$emit('input',files[0])
}
}
When you define your method with a fat arrow, you capture the lexical scope, which means this will be pointing to the containing scope (often window, or undefined), and not Vue.
This error surfaces if $emit is not on the current context/reference of this, perhaps when you're in the then or catch methods of a promise. In that case, capture a reference to this outside of the promise to then use so the call to $emit is successful.
<script type="text/javascript">
var Actions = Vue.component('action-history-component', {
template: '#action-history-component',
props: ['accrual'],
methods: {
deleteAction: function(accrualActionId) {
var self = this;
axios.post('/graphql',
{
query:
"mutation($accrualId: ID!, $accrualActionId: String!) { deleteAccrualAction(accrualId: $accrualId, accrualActionId: $accrualActionId) { accrualId accrualRate name startingDate lastModified hourlyRate isHeart isArchived minHours maxHours rows { rowId currentAccrual accrualDate hoursUsed actions { actionDate amount note dateCreated } } actions {accrualActionId accrualAction actionDate amount note dateCreated }} }",
variables: {
accrualId: this.accrual.accrualId,
accrualActionId: accrualActionId
}
}).then(function(res) {
if (res.data.errors) {
console.log(res);
alert('errors');
} else {
self.$emit('accrualUpdated', res.data.data.deleteAccrualAction);
}
}).catch(function(err) {
console.log(err);
});
}
}
});
You can write the method in short using upload(e) { instead of upload:(e)=>{ to make this point to the component.
Here is the full example
watch: {
upload(e) {
const files = e.target.files;
if(files && files.length > 0) {
console.log(files[0]);
this.$emit('input',files[0]);
}
}
}

using contains instead of stringStartsWith knockout js

I have the folliwng on my model:
self.filteredItems = ko.computed(function () {
var filter = this.filter().toLowerCase();
if (!filter) {
return this.sites();
} else {
return ko.utils.arrayFilter(this.sites(), function (item) {
return ko.utils.stringStartsWith(item.Name().toLowerCase(), filter);
});
}
}, self);
I use it for a search on my page but rather than stringStartsWith I'd like some sort of .contains instead so I get results where my searchterm is contained anywhere in the string rather than just at the beginning.
I imagine this must be a pretty common request but couldnt find anything obvious.
Any suggestion?
You can use simply the string.indexOf method to check for "string contains":
self.filteredItems = ko.computed(function () {
var filter = this.filter().toLowerCase();
if (!filter) {
return this.sites();
} else {
return ko.utils.arrayFilter(this.sites(), function (item) {
return item.Name().toLowerCase().indexOf(filter) !== -1;
});
}
}, self);

Extjs4, wait for ajax request

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