wenzhixin Bootstrap Table Editable: Show Error on server validation - x-editable

I am working on bootstrap table Editable. An extension of Wenzhixin Bootstrap Table.
Bootstrap Table Editable
I am using OnEditable to send data to the server (Using Laravel to handle the server request). I receive Error Codes in return about the outcome. But I can't seem to find a way to Show that Error on The Editable Popover OR prevent the new value to be replaced by old value. Like Error shows when We validate the Input.
I have checked the Editable->success but it only has NEW VALUE. Response parameter is always undefined.
Here is my code:
var table = $('#table');
table.bootstrapTable({
columns: [
{
field: 'roomType'
},
{
field: 'Mon',
editable: {
type: 'number',
title: 'Update Rates',
validate: function (v) {
if (!v) return 'Please Enter Rate Value';
if (parseFloat(v) < 0) return 'Rate should be greater than 0';
}
}
}
],
onEditableSave: function (field, row, oldValue, $el) {
var data = {
'_token': window.Laravel.csrfToken,
'Field': field,
'PK': row['_'+field+'_data'].pk,
'oldValue': oldValue,
'newValue': row[field]
};
$.post("Url", data)
.success(function(data, textStatus, xhr) {
if (data.success) {
}
else{
switch (data.code) {
case 400:
return data.msg;
break;
case 403:
return data.msg;
break;
case 401:
return data.msg;
break;
}
}
})
.fail(function(data, textStatus, xhr) {
return 'Something went wrong.';
});
}
});
I am expecting this kind of error to show:
Output To be Expected

I could not get the required output, to show the error on the popover. But I got a work around.
Sol: I am replacing the old value on error by $el[0].text = oldValue; and showing the error in some alert means.
Thanks
$.post(URL, data)
.success(function(data, textStatus, xhr) {
if (data.success) {
}
else{
switch (data.code) {
case 400:
$el[0].text = oldValue;
ShowError(data);
break;
case 403:
$el[0].text = oldValue;
ShowError(data);
break;
case 401:
$el[0].text = oldValue;
ShowError(data);
break;
}
}
})
.fail(function(data, textStatus, xhr) {
$el[0].text = oldValue;
ShowError('Something Went Wrong');
});

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>

x-editable price format issue

i have an issue in x-editable plugin, how to display prices in correct format in x-editable ? i would like to get the values as in price format like xx,xxx.xx ?
My code is
var editVehiclePrice = function (el, options) {
var options = $.extend(true, {
url: Utils.siteUrl() + 'dashboard/sell_vehicle/inline_vehicle_edit/',
ajaxOptions: {
dataType: 'json'
},
mode: 'inline',
}, options || {
params: function(params) {
params.veh_id = $(this).data('vehid');
return params;
},
success: function(response, newValue) {
if(response.status == 0) return response.msg;
console.log(Utils.numberFormat(newValue,2));
$(response.to_update).text(newValue);
},
validate: function(value) {
if($.trim(value) == '') {
return 'This field is required';
}
}
});
$(el).editable(options);
}
That console.log will display correct format value..but when i update it displays number in normal format.. Please help me
if we want to display any changes after editing, we should add
display: function(value, response) {
var k = Utils.numberFormat(value,2);
$(this).text(k);
},
The price will display in the number format.
Just to add to Anju's reply, Utils.numberFormat(value,2); is not defined. you can replace that with number.toFixed(2).replace(/(\d)(?=(\d{3})+.)/g, '$1,'); or wrap it into a utility function

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.

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

extract text from dojo xhrPost

I have a function in which I am doing a dojo.xhrPost(). Now the returning data is wrapped in an unwanted <div> which is framework specific and cannot be removed. How can I strip away the div element. Here is my code.
function sendForm() {
var resultNode = dojo.create("li");
dojo.xhrPost({
url: "${sectionaddurl}",
form: dojo.byId("sectionform"),
load: function(newContent) {
dojo.style(resultNode,"display","block");
resultNode.innerHTML = newContent;
},
error: function() {
resultNode.innerHTML = "Your form could not be sent.";
}
});
$("#sectionform")[0].reset();
dojo.place(resultNode, "existing_coursesection", "first");
}
In jquery we would do $("#some_ID").text(); where the id will be the div obtained via ajax.
Will dojo allow me to manipulate the request data which is like <div id="unwanted_div">containing my text</div>
any ideas?
I am not sure these are the "best" ways to go at it but they shoud work
1) Have the data be interpreted as XML instead of plain text:
dojo.require('dojox.xml.parser');
dojo.xhrPost({
//...
handleAs: 'xml',
//...
load: function(response_div){
//content should be xml now
result.innerHTML = dojox.xml.parser.textContent(response_div);
}
//...
})
2) Convert it to html and then process it
//create a thworwaway div with the respnse
var d = dojo.create('div', {innerHTML: response});
result.innerHTML = d.firstChild.innerHTML;
2.1) Use dojo.query instead of .firstChild if you need smore sofistication.
I prefer handle as JSON format :) , dojo have more utilities to access and to iterate the response.
dojo.xhrGet({
url : url,
handleAs : "json",
failOk : true, //Indicates whether a request should be allowed to fail
//(and therefore no console error message in the event of a failure)
timeout : 20000,
content: {//params},
load: function(){ // something },
preventCache: true,
error: function(error, ioargs) {
console.info("error function", ioargs);
var message = "";
console.info(ioargs.xhr.status, error);
//error process
},
handle: function(response, ioargs) {
var message = "";
console.info(ioargs.xhr.status, error);
switch (ioargs.xhr.status) {
case 200:
message = "Good request.";
break;
case 404:
message = "The page you requested was not found.";
break;
case 0:
message = "A network error occurred. Check that you are connected to the internet.";
break;
default:
message = "An unknown error occurred";
}
}
});