Is it possible to leverage one template and one uploader/java scipt for multiple instances of uploader? - fine-uploader

This may be TOO much to ask, but I still want to ask as it looks like too much code on web pages.
I have following template and javascript for a single instance of uploader. In my case, I have to use 8 uploader instances in a page (ofcourse in tabs!). If at all possible, I DO NOT want to repeat below code chunks to all 8 uploaders. Is is possible to leverage code (template,javascript) for all uploaders.
Please see my javascript that I am trying to re-use; but on the execution it fails for ...Uncaught Error: Method ....jsonStringCreatedByMyFunction - see my json string below..... does not exist on jQuery.fineUploader
template:
<script type="text/template" id="qq-template-manual-trigger-section1">
<div class="qq-uploader-selector qq-uploader" qq-drop-area-text="Drop files here">
<div class="qq-total-progress-bar-container-selector qq-total-progress-bar-container">
<div role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" class="qq-total-progress-bar-selector qq-progress-bar qq-total-progress-bar"></div>
</div>
<div class="qq-upload-drop-area-selector qq-upload-drop-area" qq-hide-dropzone>
<span class="qq-upload-drop-area-text-selector"></span>
</div>
<div class="buttons">
<div class="qq-upload-button-selector qq-upload-button">
<div>Select files</div>
</div>
<button type="button" id="trigger-upload-section1" class="btn btn-primary">
<i class="icon-upload icon-white"></i> Upload
</button>
</div>
<span class="qq-drop-processing-selector qq-drop-processing">
<span>Processing dropped files...</span>
<span class="qq-drop-processing-spinner-selector qq-drop-processing-spinner"></span>
</span>
<ul class="qq-upload-list-selector qq-upload-list" aria-live="polite" aria-relevant="additions removals">
<li>
<div class="qq-progress-bar-container-selector">
<div role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" class="qq-progress-bar-selector qq-progress-bar"></div>
</div>
<span class="qq-upload-spinner-selector qq-upload-spinner"></span>
<div>
<img class="qq-thumbnail-selector" qq-max-size="80" qq-server-scale>
<span class="qq-upload-file-selector qq-upload-file"></span>
<span class="qq-upload-size-selector qq-upload-size"></span>
<span class="qq-edit-filename-icon-selector qq-edit-filename-icon qq-editable" aria-label="Edit filename"></span>
<input class="qq-edit-filename-selector qq-edit-filename" tabindex="0" type="text">
</div>
<span class="qq-upload-caption-selector qq-upload-caption"></span>
<span class="qq-edit-caption-icon-selector qq-edit-caption-icon kk-editable" aria-label="Edit caption"></span>
<input class="qq-edit-caption-selector qq-edit-caption kk-editing" placeholder="Caption here ..." tabindex="0" type="text">
<button type="button" class="qq-btn qq-upload-delete-selector qq-upload-update-caption" onclick="captionUpdate(true);">Update Caption</button>
<button type="button" class="qq-btn qq-upload-cancel-selector qq-upload-cancel">Cancel</button>
<button type="button" class="qq-btn qq-upload-retry-selector qq-upload-retry">Retry</button>
<button type="button" class="qq-btn qq-upload-delete-selector qq-upload-delete" onclick="captionUpdate(false);">Delete</button
<span role="status" class="qq-upload-status-text-selector qq-upload-status-text"></span>
</li>
</ul>
</div>
</script>
Javascript:
function getFineUploaderJsonObjectStr(sectionInd) {
var requestObj = new Object();
requestObj.endpoint = 'http://s3.amazonaws.com/mybucket';
requestObj.accessKey = 'AKvcccccvccvBIA';
var objectPropertiesObj = new Object();
objectPropertiesObj.key = " function (fileId) { " +
" return $('#login_name').val()+ '/' + $('#book_id).val() + '/' " + sectionInd + " '/' + $('#fine-uploader-manual-trigger-" + sectionInd + " ').fineUploader('getName',fileId); " +
" } ";
var signatureObj = new Object();
signatureObj.endpoint = "http://localhost/app/ci/fine/endpoint";
var uploadSuccessObj = new Object();
uploadSuccessObj.endpoint = "http://localhost/app/ci/fine/endpoint?success";
var uploadSuccessObjParams = new Object();
uploadSuccessObjParams.isBrowserPreviewCapable = qq.supportedFeatures.imagePreviews;
uploadSuccessObjParams.bookid = " function() { return $('#book_id').val(); } ";
uploadSuccessObjParams.sectionid = " function() { return $('#section_id').val(); } ";
uploadSuccessObjParams.section = " function() { return 'section1'; } ";
uploadSuccessObj.params = uploadSuccessObjParams;
var sessionObj = new Object();
sessionObj.endpoint = "http://localhost/app/ci/fine/endpoint?filelist";
var sessionObjParams = new Object();
sessionObjParams.key = " function() { " +
" return $('#login_name').val()+ '/' + $('#book_id').val() + '/' " + sectionInd + " ; " +
" } ";
sessionObj.params = sessionObjParams;
var iframeSupportObj = new Object();
iframeSupportObj.localBlankPagePath = "success.html";
var corsObj = new Object();
corsObj.expected = true;
var chunkingObj = new Object();
chunkingObj.enabled = true;
var resumeObj = new Object();
resumeObj.enabled = true;
var deleteFileObj = new Object();
deleteFileObj.enabled = true;
deleteFileObj.method = "POST";
deleteFileObj.endpoint = "http://localhost/app/ci/fine/endpoint";
var deleteFileParams = new Object();
deleteFileParams.qqcaption = " function() { if (isCaptionUpdate === true) { return captionValue; } } ";
deleteFileParams.bookid = " function() { return $('#book_id').val(); } ";
deleteFileParams.sectionid = " function() { return $('#section1_id').val(); } ";
deleteFileObj.params = deleteFileParams;
var validationObj = new Object();
validationObj.itemLimit = 500;
validationObj.sizeLimit = 15000000;
var thumbnailsObj = new Object();
var thumbnailsObjPlaceholders = new Object();
thumbnailsObjPlaceholders.notAvailablePath = "http://localhost/app/ci/s3.fine-uploader/placeholders/not_available-generic.png";
thumbnailsObjPlaceholders.waitingPath = "http://localhost/app/ci/s3.fine-uploader/placeholders/waiting-generic.png";
thumbnailsObj.placeholders = thumbnailsObjPlaceholders;
var callbacksObj = new Object();
callbacksObj.onComplete = " function(id, name, response) { " +
" if (response.success) { " +
" setSectionImageCount('1', 'U', 0); " +
" } " +
" } ";
callbacksObj.onError = " function(id, name, errorReason, xhrOrXdr) { " +
" if (!isCaptionUpdate) {//isCaptionUpdate will return 206 " +
" alert(qq.format('Error on file number {} - {}. Reason: {}', id, name, errorReason)); " +
" } " +
" } ";
callbacksObj.onUpload = " function(id, fileName) { " +
" captionValue = qq(this.getItemByFileId(id)).getByClass('qq-edit-caption')[0].value; " +
" this.setParams({'qqcaption':captionValue}); " +
" } ";
callbacksObj.onDelete = " function(id) { " +
" captionValue = qq(this.getItemByFileId(id)).getByClass('qq-edit-caption')[0].value; " +
" //change sttaus to 'Updating..' if it is Caption update " +
" var statusSpan = qq(this.getItemByFileId(id)).getByClass('qq-upload-status-text')[0]; " +
" if (isCaptionUpdate === true) { " +
" statusSpan.innerText = 'Updating...'; " +
" } " +
" } ";
callbacksObj.onDeleteComplete = " function(id, xhr, isError) { " +
" if (!isError) { " +
" setSectionImageCount('1', 'D', 0); " +
" } else if (isCaptionUpdate === true) { " +
" statusSpan.innerText = ''; " +
" } " +
" } ";
callbacksObj.onSubmitted = " function (id, name) { " +
" //nothing " +
"} ";
callbacksObj.onStatusChange = " function(id, oldStatus, newStatus) { " +
" if (oldStatus === 'submitting' && newStatus === 'submitted'){ " +
" //hide 'Update Caption' btn for uploading files " +
" var updateCaptionBtn = qq(this.getItemByFileId(id)).getByClass('qq-upload-update-caption')[0]; " +
" qq(updateCaptionBtn).hide(); " +
" } " +
" } ";
callbacksObj.onSessionRequestComplete = " function(response, success, xhrOrXdr) { " +
" //alert(response.length); uploaded file count should be added to it; " +
" if (success) { " +
" if (response.length > 0) { " +
" //$('#section1ImageCount').text(response.length); " +
" setSectionImageCount('1', 'I', response.length); " +
" } " +
" var uploader = this; " +
" response.forEach(function(item) { " +
" var id = uploader.getUploads({uuid: item.uuid}).id; " +
" var fileEl = uploader.getItemByFileId(id); " +
" fileEl.querySelector('.qq-edit-caption').value = item.qqcaption; " +
" }) " +
" } " +
" } ";
var wrapperObj = new Object();
wrapperObj.template = 'qq-template-manual-trigger-'+sectionInd;
//wrapperObj.template = 'qq-template-manual-trigger';
wrapperObj.autoUpload = false;
wrapperObj.debug = true;
wrapperObj.request = requestObj;
wrapperObj.objectProperties = objectPropertiesObj;
wrapperObj.signature = signatureObj;
wrapperObj.uploadSuccess = uploadSuccessObj;
wrapperObj.session = sessionObj;
wrapperObj.iframeSupport = iframeSupportObj;
wrapperObj.cors = corsObj;
wrapperObj.chunking = chunkingObj;
wrapperObj.resume = resumeObj;
wrapperObj.deleteFile = deleteFileObj;
wrapperObj.validation = validationObj;
wrapperObj.thumbnails = thumbnailsObj;
wrapperObj.callbacks = callbacksObj;
var jsonString = JSON.stringify(wrapperObj);
console.log(jsonString);
return jsonString;
};
var section1JsonStr = getFineUploaderJsonObjectStr('section1');
var section2JsonStr = getFineUploaderJsonObjectStr('section2');
$('#fine-uploader-manual-trigger-section1').fineUploaderS3(section1JsonStr);
$('#fine-uploader-manual-trigger-section2').fineUploaderS3(section2JsonStr);
$('#trigger-upload-section1').click(function() {
$('#fine-uploader-manual-trigger-section1').fineUploaderS3('uploadStoredFiles');
});
$('#trigger-upload-section2').click(function() {
$('#fine-uploader-manual-trigger-section2').fineUploaderS3('uploadStoredFiles');
});
jsonStringCreatedByMyFunction:
{"template":"qq-template-manual-trigger-section1","autoUpload":false,"debug":true,"request":{"endpoint":"http://s3.amazonaws.com/mybucket","accessKey":"AKvvvvhjjjjAABIA"},"objectProperties":{"key":" function (fileId) { \treturn $('#login_name').val()+ '/' + $('#book_id).val() + '/' section1 '/' + $('#fine-uploader-manual-trigger-section1 ').fineUploader('getName',fileId); } "},"signature":{"endpoint":"http://localhost/app/ci/fine/endpoint"},"uploadSuccess":{"endpoint":"http://localhost/app/ci/fine/endpoint?success","params":{"isBrowserPreviewCapable":true,"bookid":" function() { return $('#book_id').val(); } ","sectionid":" function() { return $('#section_id').val(); } ","section":" function() { return 'section1'; } "}},"session":{"endpoint":"http://localhost/app/ci/fine/endpoint?filelist","params":{"key":" function() { \treturn $('#login_name').val()+ '/' + $('#book_id').val() + '/' section1 ; } "}},"iframeSupport":{"localBlankPagePath":"success.html"},"cors":{"expected":true},"chunking":{"enabled":true},"resume":{"enabled":true},"deleteFile":{"enabled":true,"method":"POST","endpoint":"http://localhost/app/ci/fine/endpoint","params":{"qqcaption":" function() { if (isCaptionUpdate === true) { return captionValue; } } ","bookid":" function() { return $('#book_id').val(); } ","sectionid":" function() { return $('#section1_id').val(); } "}},"validation":{"itemLimit":500,"sizeLimit":15000000},"thumbnails":{"placeholders":{"notAvailablePath":"http://localhost/app/ci/s3.fine-uploader/placeholders/not_available-generic.png","waitingPath":"http://localhost/app/ci/s3.fine-uploader/placeholders/waiting-generic.png"}},"callbacks":{"onComplete":" function(id, name, response) { \tif (response.success) { \t\tsetSectionImageCount('1', 'U', 0); \t} } ","onError":" function(id, name, errorReason, xhrOrXdr) { \tif (!isCaptionUpdate) {//isCaptionUpdate will return 206 \t\talert(qq.format('Error on file number {} - {}. Reason: {}', id, name, errorReason)); \t} } ","onUpload":" function(id, fileName) { \tcaptionValue = qq(this.getItemByFileId(id)).getByClass('qq-edit-caption')[0].value; \tthis.setParams({'qqcaption':captionValue}); } ","onDelete":" function(id) { \tcaptionValue = qq(this.getItemByFileId(id)).getByClass('qq-edit-caption')[0].value; \t//change sttaus to 'Updating..' if it is Caption update \tvar statusSpan = qq(this.getItemByFileId(id)).getByClass('qq-upload-status-text')[0]; \tif (isCaptionUpdate === true) { \t\tstatusSpan.innerText = 'Updating...'; \t} } ","onDeleteComplete":" function(id, xhr, isError) { \tif (!isError) { \t\tsetSectionImageCount('1', 'D', 0); \t} else if (isCaptionUpdate === true) {\t\t\tstatusSpan.innerText = ''; \t} } ","onSubmitted":" function (id, name) { //nothing } ","onStatusChange":" function(id, oldStatus, newStatus) { \tif (oldStatus === 'submitting' && newStatus === 'submitted'){ \t\t//hide 'Update Caption' btn for uploading files \t\tvar updateCaptionBtn = qq(this.getItemByFileId(id)).getByClass('qq-upload-update-caption')[0]; \t\tqq(updateCaptionBtn).hide(); \t} } ","onSessionRequestComplete":" function(response, success, xhrOrXdr) { \t//alert(response.length); uploaded file count should be added to it; \tif (success) { \t\t\t\tif (response.length > 0) { \t\t\t//$('#section1ImageCount').text(response.length); \t\t\tsetSectionImageCount('1', 'I', response.length); \t\t} \t\tvar uploader = this;\t \t\tresponse.forEach(function(item) { \t\t\tvar id = uploader.getUploads({uuid: item.uuid}).id; \t\t\tvar fileEl = uploader.getItemByFileId(id); \t\t\tfileEl.querySelector('.qq-edit-caption').value = item.qqcaption; \t\t}) \t} } "}}

Related

Regarding Vue function in dashboard

We are experiencing problems after a Vue update. However, we cannot locate the error. Could anyone help us find this problem? This has occurred in the dashboard at a certain section where we show the payments from our users, so the admins can look into this.
The code:
addCollection: function (employee) {
var self = this;
year = 0;
var selectText =
'<div class="swal2-content" style="display: block;">Periode:</div>';
selectText +=
'<select id="swal-select1" class="swal2-select form-control" style="display: inline-block; width: calc(50% - 4px); margin-right: 4px;">';
for (year in self.vmAvailableYears) {
alert(this.year);
selectText +=
'<option value="' +
self.vmAvailableYears[year] +
'" ' +
(self.vmAvailableYears[year] == self.vmCurrentYear
? "selected"
: "") +
">" +
self.vmAvailableYears[year] +
"</option>";
}
selectText += "</select>";
selectText +=
'<select id="swal-select2" class="swal2-select form-control" style="display: inline-block; width: calc(50% - 4px); margin-left: 4px;">';
for (i = 1; i < 52; i++) {
selectText +=
'<option value="' +
i +
'" ' +
(i == self.vmCurrentWeek ? "selected" : "") +
">week " +
i +
"</option>";
}
selectText += "</select>";
selectText +=
'<div class="swal2-content" style="display: block;">Type:</div>';
selectText +=
'<select id="swal-select3" class="swal2-select form-control">';
selectText +=
'<option value="rent" style="' +
(self.vmCanAlter ? "" : "display: none;") +
'" data-amount-required="true" data-comment-required="false">Huur</option>';
selectText +=
'<option value="addition" data-amount-required="true" data-comment-required="true">Extra kosten</option>';
selectText +=
'<option value="payment_cash" selected data-amount-required="true" data-comment-required="false">Betaling contant</option>';
selectText +=
'<option value="payment_card" data-amount-required="true" data-comment-required="false">Betaling PIN</option>';
selectText +=
'<option value="payment_transfer" data-amount-required="true" data-comment-required="false">Betaling overboeking</option>';
selectText +=
'<option value="vacation_unpaid" data-amount-required="false" data-comment-required="false">Vakantie (doorbetalen)</option>';
selectText +=
'<option value="vacation_paid" data-amount-required="false" data-comment-required="false">Vakantie (niet doorbetalen)</option>';
selectText +=
'<option value="remission" data-amount-required="true" data-comment-required="true">Kwijtschelding</option>';
selectText +=
'<option value="comment" data-amount-required="false" data-comment-required="true">Opmerking</option>';
selectText += "</select>";
selectText +=
'<div id="swal-label1" class="swal2-content" style="display: block;">Bedrag:</div>';
selectText +=
'<input id="swal-input1" class="swal2-input" placeholder="Bedrag">';
selectText +=
'<div class="swal2-content" style="display: block;">Opmerking (<span id="swal-comment-label">optioneel</span>):</div>';
selectText +=
'<input id="swal-input2" class="swal2-input" placeholder="Opmerking">';
self
.$swal({
title:
employee.firstname +
" " +
employee.insertion +
" " +
employee.lastname,
html: selectText,
showCancelButton: true,
confirmButtonText: "Toevoegen",
cancelButtonText: "Annuleren",
showLoaderOnConfirm: true,
allowOutsideClick: false,
onOpen: function (el) {
$(el)
.find("#swal-select3")
.on("change", function () {
var selectedOption = $("option:selected", this);
var amountRequired = selectedOption.data("amount-required");
var commentRequired = selectedOption.data("comment-required");
var amountLabel = $("#swal-label1");
var amountInput = $("#swal-input1");
var commentInput = $("#swal-input2");
if (amountRequired) {
amountLabel.show();
amountInput.show();
} else {
amountLabel.hide();
amountInput.val("");
amountInput.hide();
}
commentInput.prop("required", commentRequired);
$("#swal-comment-label").text(
commentRequired ? "verplicht" : "optioneel"
);
});
$(el)
.find("#swal-select1, #swal-select2")
.on("change", function () {
const rentOption = $('#swal-select3 option[value="rent"]');
if (
self.vmCanAlter ||
self.weekIsInFuture(
$("#swal-select1").val(),
$("#swal-select2").val()
)
) {
rentOption.show();
} else {
rentOption.hide();
if ($("#swal-select3").val() == "rent") {
$("#swal-select3").val("payment_cash");
}
}
});
},
preConfirm: function (key) {
return new Promise(function (resolve, reject) {
if (
$("#swal-input2").prop("required") &&
$("#swal-input2").val().length <= 0
) {
reject("Opmerking is een verplicht veld.");
}
var postData = {
employee_id: employee.id,
type: $("#swal-select3").val(),
amount: $("#swal-input1").val().replace(",", "."),
comment: $("#swal-input2").val(),
year: $("#swal-select1").val(),
week: $("#swal-select2").val(),
};
self.resourceCollection.store(postData).then(
(response) => {
handleRequestSuccess(response);
resolve(response.data);
},
(response) => {
let handledResponse = handleRequestError(response);
if (handledResponse) {
reject(self.formatErrors(response.data));
}
}
);
});
},
})
.then(
(response) => {
let amount = parseFloat(response.amount);
if (["rent", "addition"].indexOf(response.type) > -1) {
employee.balance -= amount;
} else {
employee.balance += amount;
}
if (response.rent_subtract > 0) {
employee.collections.filter((collection) => {
employee.balance += parseFloat(collection.amount);
if (collection.type === "rent") {
collection.amount = 0;
}
});
}
employee.collections.push({
year: response.year,
week: response.week,
type: response.type,
amount: response.amount,
comment: response.comment,
admin: response.admin,
});
},
(rejection) => {}
);
}
The error:
[Vue warn]: Error in v-on handler: "ReferenceError: Can't find variable: year"
found in
---> <NdAdminCollectionEmployee> at resources/assets/js/vue/views/admin/collection/NdAdminCollectionEmployee.vue
<Root>
The other error:
ReferenceError: Can't find variable: year —
Kind regards,
Daan IV & Collin III

My geojson polygon doesn't appear on the ajax-leaflet map

This is my first time to make a GIS app with CodeIgniter, Leaflet, and Ajax. I want to show a polygon above my map with geojson file that I've made using geojson.io but the polygon doesn't show. When I inspect the page in my browser it shows an error message like
Failed to load modules/jenis_hutan/...geojson/map.geojson:1
resource: the server responded with a status of 404()
Here is my js code to show the geojson file.
let tnSelect = $("#tn-select");
let gisCard = $("#gis-card");
let divModal = $(".div-modal");
tnSelect.change(function () {
let $val = $(this).val();
loadPage();
setCookie("tn_value", $val, 0.0833333);
window.location.reload(true);
});
$(window).on("load", function () {
let $tn_val = getCookie("tn_value");
let gisMap;
$.ajax({
method: "GET",
url: base_url + "ajax/tn_data",
dataType: "JSON",
data: {},
success: (res) => {
console.log(res);
if ($tn_val !== null) {
for (let i = 0; i < res.length; i++) {
let data = res[i];
let name = data.tn_name;
name = name.replace(
/^[\u00C0-\u1FFF\u2C00-\uD7FF\w]|\s[\u00C0-\u1FFF\u2C00-\uD7FF\w]/g,
function (letter) {
return letter.toUpperCase();
}
);
if (data.tn_id == $tn_val) {
tnSelect.append(
'<option selected id="tn_name" value="' +
data.tn_id +
'">' +
name +
"</option>"
);
gisCard.html(
'<div class="card mb-4 gis-card">' +
'<div class="card-header py-3 text-center">' +
'<h6 class="m-0 font-weight-bold text-center">' +
name +
"</h6>" +
"</div>" +
'<div class="card-body" id="gis-map"></div>' +
"</div>"
);
gisMap = L.map("gis-map").setView([data.tn_lat, data.tn_long], 12);
mapAPI.addTo(gisMap);
} else {
tnSelect.append(
'<option value="' + data.tn_id + '">' + name + "</option>"
);
}
}
} else {
for (let i = 0; i < res.length; i++) {
let data = res[i];
let name = data.tn_name;
name = name.replace(
/^[\u00C0-\u1FFF\u2C00-\uD7FF\w]|\s[\u00C0-\u1FFF\u2C00-\uD7FF\w]/g,
function (letter) {
return letter.toUpperCase();
}
);
if (i < 1) {
tnSelect.append(
'<option selected id="tn_name" value="' +
data.tn_id +
'">' +
name +
"</option>"
);
gisCard.html(
'<div class="card mb-4 gis-card">' +
'<div class="card-header py-3 text-center">' +
'<h6 class="m-0 font-weight-bold text-center">' +
name +
"</h6>" +
"</div>" +
'<div class="card-body" id="gis-map"></div>' +
"</div>"
);
gisMap = L.map("gis-map").setView([data.tn_lat, data.tn_long], 12);
mapAPI.addTo(gisMap);
} else {
tnSelect.append(
'<option value="' + data.tn_id + '">' + name + "</option>"
);
}
}
}
//**//
$.getJSON(base_url + "modules/jenis_hutan/geojson/map.geojson", function (
data
) {
geoLayer = L.geoJson(data, {
style: function (feature) {
return {
fillOpacity: 0.5,
weight: 1,
opacity: 1,
color: "#fa7268",
};
},
onEachFeature: function (feature, layer) {
var kode = feature.properties.kode;
var info_zona = "<h5 style='text-align:left'>ZONA INTI</h5>";
info_zona += "<hr>";
info_zona +=
"<div style='width:100%;text-align:left;margin-top:10px;'><h6>Luas area: 10.475 ha</h6><br><h6>Fungsi zona: Jalur pendakian</h6></div>";
layer.bindPopup(info_zona, {
maxWidth: 260,
closeButton: true,
offset: L.point(0, -20),
});
layer.on("click", function () {
layer.openPopup();
});
},
}).addTo(map);
});
},
});
});
Is there something wrong with my code? This is my college task and the deadline is this Friday so please anyone enlight me:( or at least give me link to some tutorial related to this thing:( Thank you everyone.

Sweetalert2 input validation with AJAX

I'm using sweetalert2 to set-up multiple inputs as modal (with swal mixin), and I need to verify in server-side if values sent are equal to the ones in database. As example I'm using just a constant value in the .php file. Here's my code:
{
onBeforeOpen: function (dom) {
dom.getElementsByClassName('swal2-input')[0].style = "display: none";
},
html:
"<form action='' method='post'>" +
"<div class='main-cont'>"+
"<span>" +
"Por favor ingresa el codigo de verificacion NUIP "+
"que hemos enviado a tu celular" +
"</span>"+
"<div class='row cuadros'>" +
"<input id='num-1' class='inp-num' data-pos='0' type='text' maxlength='1' name='one' onkeypress='isInputNumber(event)' autofocus='autofocus'/>" +
"<input id='num-2' class='inp-num' data-pos='1' type='text' maxlength='1' name='two' onkeypress='isInputNumber(event)'>" +
"<input id='num-3' class='inp-num' data-pos='2' type='text' maxlength='1' name='three' onkeypress='isInputNumber(event)'>" +
"<input id='num-4' class='inp-num' data-pos='3' type='text' maxlength='1' name='four' onkeypress='isInputNumber(event)'>" +
"</div>" +
"</div>"+
"</form>",
inputValidator: function() {
var nums = Object.values(document.getElementsByClassName("inp-num"));
for(var i = 0; i < nums.length; i++) {
if(!nums[i].value) {
return 'Ingresa el codigo completo';
}
}
$.ajax({
type: "POST",
url: "php/confirma_datos.php",
data: {
"one": $("#num-1").val(),
"two": $("#num-2").val(),
"three": $("#num-3").val(),
"four": $("#num-4").val(),
},
success : function(response) {
if (response == 'true') {
swal('hola');
return 'OK';
} else {
console.log('no coinciden');
}
},
});
},
preConfirm: function () {
return [
$("#num-1").val(),
$("#num-2").val(),
$("#num-3").val(),
$("#num-4").val(),
]
},
},
And in the server side I have.
<?php
$nuip_comp = "1234";
$nuip = $_POST['one'] . "" . $_POST['two'] . "" . $_POST['three']. "" . $_POST['four'] ;
if($nuip_comp == $nuip) {
echo 'true';
} else {
echo 'false';
}
I want to prevent the modal to go to the next step until the values are equal. Any idea on how to do this?
Thanks!

Jquery Datatable sorting

I'm noob with Jquery DataTables.
I have a very basic question on how to use the sorting plugins:
Have googled a lot on this, but I fail to get proper answers, on how to incorporate them in my code, do we have to just add the script to a ".js" file and add it? or Do we also have to call the function of the plugins?
Can someone point me to a working example with sorting of numeric columns formatted with commas/percentage signs.
The columns with signs or commas are sorted as string. I have seen a lot of references which say to use plugins and then specify sType or sSortableDataType but that doesn't work.
Here's my code: (Please correct me where I'm wrong)
<%# Page Language="C#" AutoEventWireup="true" CodeFile="scorecard_dynamic.aspx.cs" Inherits="Dashboard_scorecard_dynamic" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>new score card</title>
<%--<script src="../js/jquery-1.10.2.min.js"></script>--%>
<style type="text/css" title="currentStyle">
#import "../js/datatable/css/demo_page.css";
#import "../js/datatable/css/demo_table.css";
</style>
<script type="text/javascript" src="../js/datatable/js/jquery.js"></script>
<script type="text/javascript" src="../js/datatable/js/jquery.dataTables.js"></script>
<script src="../js/datatable/Plugins-master/sorting/custom-data-source/percent.js"></script>
<link href="../StyleSheet/LoadingPanel.css" rel="stylesheet" />
<script type="text/javascript" charset="utf-8">
$(document).ready(function () {
gettopchannelsplot();
//transpose();
var otable = $('#example').dataTable({
"iDisplayLength": 5,
"aLengthMenu": [[1, 2, 3, 4, 5], [1, 2, 3, 4, "All"]],
"oLanguage": {
"oPaginate": {
"sPrevious": "Previous", //can change text for pagination
"sNext": "Next"
},
//"fnDrawCallback": function (oSettings) {
// alert('DataTables has redrawn the table');
//},
"aoColumns": [
null,
{ "sType": "pct" },
null,
null,
null,
null,
null,
null
],
"aoColumnDefs": [
{ "bSortable": false, "aTargets": [ 0,5,6,7 ] }
]
}
//"sPaginationType": "full_numbers"
});
oTable.fnSort([[3, 'asc']]);
});
var StartDate = '16-oct-2013';
var EndDate = '22-oct-2013';
function transpose() {
var t = $('#example tbody').eq(0);
var r = t.find('tr');
var cols = r.length;
var rows = r.eq(0).find('td').length;
var cell, next, tem, i = 0;
var tb = $('<tbody></tbody>');
while (i < rows) {
cell = 0;
tem = $('<tr></tr>');
while (cell < cols) {
next = r.eq(cell++).find('td').eq(0);
tem.append(next);
}
tb.append(tem);
++i;
}
$('#example').append(tb);
$('#example').show();
}
function gettopchannelsplot() {
//$("#bubbling").show();
//alert('gettopchannelsplot');
var arrListMain = new Array();
var arrList = new Array();
var linkName = 'View Chatter';
var result = ExecuteSynchronously('../SocialMedia.asmx', 'GetTopchannels', { startDate: StartDate, endDate: EndDate });
//tbl_example.empty();
$('#example thead').append("<tr>"
+"<td class='normalBold' align='left'>info</td>"
+ "<td class='normalBold' align='left'>share of voice</td>"
+ "<td class='normalBold' align='left'>total chatter</td>"
+ "<td class='normalBold' align='left'>sentiments</td>"
+ "<td class='normalBold' align='left'>exposure</td>"
+ "<td class='normalBold' align='left'>most popular with</td>"
+ "<td class='normalBold' align='left'>most popular on</td>"
+ "<td class='normalBold' align='left'>link</td>"
+ "</tr>");
var value = new Array();
if (result.d != "" && result.d != null) {
arrListMain = result.d.split('#');
for (var i = 0; i < arrListMain.length; i++) {
var tmp = "<tr>"
+ "<td class='border' width='12%'><a href='../Scorecard.aspx?1'><image src='" + "../" + arrListMain[i].split('^')[7] + "'/></a></td>"
+ " <td class='border' width='12%' align='center'>" + arrListMain[i].split('^')[2] + "%</td>"
+ " <td class='border' width='12%' align='center'> " + arrListMain[i].split('^')[3] + "</td>"
//// + " <td class='border' width='12%' align='center'><label id=label" + i + " >" + Number(arrListMain[i].split('^')[3]).toLocaleString() + "</label></td>"
+ " <td class='border' width='12%' align='center'><image src='" + "../" + arrListMain[i].split('^')[10] + "'/></td>"
+ " <td class='border' width='13%' align='center'>" + arrListMain[i].split('^')[5] + "</td>"
+ " <td class='border' width='13%' align='center'><image src='" + "../" + arrListMain[i].split('^')[8] + "'/></td>"
+ " <td class='border' width='13%' align='center'><image src='" + "../" + arrListMain[i].split('^')[9] + "'/></td>"
+ " <td class='border' width='13%' align='center'><a href='../ChatterAdvanced2.aspx?filter=channel&value=" + arrListMain[i].split('^')[0] + "'>chatter</a></td>"
+ "</tr>";
//alert(tmp);
$('#example tbody').append(tmp);
}
}
$("#bubbling").hide();
}
</script>
<script type="text/javascript">
function ExecuteSynchronously(url, method, args) {
var executor = new Sys.Net.XMLHttpSyncExecutor(); // Instantiate a WebRequest.
var request = new Sys.Net.WebRequest(); // Set the request URL.
request.set_url(url + '/' + method); // Set the request verb.
request.set_httpVerb('POST'); // Set request header.
request.get_headers()['Content-Type'] = 'application/json; charset=utf-8'; // Set the executor.
request.set_executor(executor); // Serialize argumente into a JSON string.
request.set_body(Sys.Serialization.JavaScriptSerializer.serialize(args)); // Execute the request.
request.invoke();
if (executor.get_responseAvailable()) {
return (executor.get_object());
}
return (false);
}
</script>
</head>
<body>
<form id="form1" runat="server">
<AjaxToolkit:ToolkitScriptManager runat="server" ID="ASD">
<Scripts>
<asp:ScriptReference Path="~/js/XMLHttpSyncExecutor.js" ScriptMode="Release" />
<asp:ScriptReference Path="~/App_Code/SocialMedia.cs" />
</Scripts>
</AjaxToolkit:ToolkitScriptManager>
<div>
<div class="bubblingG" id="bubbling">
<span id="bubblingG_1"></span>
<span id="bubblingG_2"></span>
<span id="bubblingG_3"></span>
</div>
<table cellpadding="0" cellspacing="0" border="0" class="display" id="example">
<thead>
</thead>
<tbody>
</tbody>
</table>
</div>
</form>
</body>
</html>
Please excuse my HTML markup formatting.
You need both the "plugin" and set the proper sType according to that plugin. The plugins are really just some very simple functions, that you easily can produce yourself for your own needs and place into your code. Consider this "plugin" that sort percents with commas :
jQuery.extend( jQuery.fn.dataTableExt.oSort, {
"normalize": function(n) {
return parseFloat(n.toString().replace(',','.'));
},
"percent-asc": function(a, b) {
a=this.normalize(a);
b=this.normalize(b);
return ((a < b) ? -1 : ((a > b) ? 1 : 0));
},
"percent-desc": function(a, b) {
a=this.normalize(a);
b=this.normalize(b);
return ((a < b) ? 1 : ((a > b) ? -1 : 0));
}
});
The above is pretty failsafe. To initialize :
var dataTable = $('#example').dataTable({
aoColumns: [
null,
null,
null,
{ sType: "percent" },
null
],
//...
});
see this working fiddle demonstrating the code above -> http://jsfiddle.net/xK7Ud/

how to bind a gridview from the session in mvc3

I have a partial view.in this partial view,i have a webgrid.I want to bind gridview from the session value.My code is
#{
var properties = typeof(SLCCentral.Portal.Models.Entities.ApplicationModule).GetProperties();
var webGridColumns = properties.Select(prop => new WebGridColumn()
{
ColumnName = prop.Name,
Header = prop.Name
}).ToList();
var grid = new WebGrid(source: Model, canSort: false, canPage: true, rowsPerPage: 10);
var pager = grid.Pager();
var index = grid.PageIndex;
index = index + 1;
var cnt = grid.PageCount;
//var selectedIndex = "<span class=" + "webgrid-footer-selected" + ">" + index.ToString() + "</span>";
var pgarrow = "class=" + "webgrid-footer-arrow" + "><img";
var tblcss = "<table width=" + "100%" + " cellspacing=" + "0" + " cellpadding=" + "0" + " border=" + "0" + ">";
var adthcss = "class=" + "HD-td-width-col_AppAddModule" + "> </th>";
var epthcss = "class=" + "HD-td-width-col_AppEdit" + "> </th>";
var dthcss = "class" + "HD-td-width-col_AppDelete" + "> </th>";
// var pager = grid.Pager().ToString();
if (index == 2)
{
}
var tblHTML = grid.Table().ToHtmlString();
//var Pager = System.Text.RegularExpressions.Regex.Replace(grid.Pager().ToString(), index.ToString(), selectedIndex);
//var newPager = System.Text.RegularExpressions.Regex.Replace(pager, "(( \\d)|(\\d )|(<a([^a]*|a[^>])*a>))", "<span>$1</span>");
var gridHtml = grid.GetHtml(footerStyle: "webgrid-footer-Group",
mode: WebGridPagerModes.All, nextText: "Active-NXT", previousText: "Active-PRV", numericLinksCount: 5,
columns: grid.Columns(
grid.Column(columnName: "moduleName", header: "Modules Name", style: "HD-td-width-col_ModuleName", format: #<text><span class=" moduleName">#item.moduleName</span></text>),
grid.Column(columnName: "moduleShortCode", header: "ModuleShortCode", style: "HD-td-width-col_ModuleName", format: #<text><span class=" moduleName">#item.moduleShortCode</span></text>),
grid.Column(header: "Edit", style: "HD-td-width-col_AppEdit", format: #<text><span id="edit" style="cursor:pointer;text-decoration:underline;" onclick='doEdit("")'><img src="../../Images/edit-icon.png" alt="" width="18" height="19" title="Edit" /></span></text>),
grid.Column(header: "Delete", style: "HD-td-width-col_AppDelete", format: #<text><span id="delete" style="cursor:pointer;text-decoration:underline;" onclick='PerformDelete("")'><img src="../../Images/delete-icon.png" alt="" width="16" height="21" title="Delete" /></span></text>))).ToString();
//gridHtml = System.Text.RegularExpressions.Regex.Replace(gridHtml, index.ToString(), selectedIndex);
gridHtml = System.Text.RegularExpressions.Regex.Replace(gridHtml, "<table>", tblcss);
gridHtml = System.Text.RegularExpressions.Regex.Replace(gridHtml, ">AddModules</th>", adthcss);
gridHtml = System.Text.RegularExpressions.Regex.Replace(gridHtml, ">Edit</th>", epthcss);
gridHtml = System.Text.RegularExpressions.Regex.Replace(gridHtml, ">Delete</th>", dthcss);
}#(new HtmlString(gridHtml))
public void AddModule(string ModuleName, string ModuleShortcode)
{
try
{
if (!string.IsNullOrEmpty(ModuleName))
{
_objIApplicationManagerBAL.SetModuleCol(ModuleName, ModuleShortcode);
_objIApplicationModuleCol = _objISessionContext.IModuleContextCol;
}
}
catch (Exception ex)
{
}
finally
{
}
}
You can bind value in grid by using call script and by Partialview
Script
<script type="text/javascript">
$(document).ready(function () {
firstDDLValue = "Your Session Value"
$.get('#Url.Action("YourMethod")', { secondValue: firstDDLValue }, function (result) {
$('#div-grid-id').html(result);
});
});
</script>
Control:
public ActionResult YourMethod(Viewname model, string secondValue)
{
if (secondValue != "")
ObservableCollection<Yourviewnam> Yourviewnam= new ObservableCollection<Yourviewnam>();
Yourviewnam Yourviewnam= new Models.Yourviewnam();
result= Receipt.GetReceiptListByCustID(secondValue);
return PartialView("PratialViewname", result);
}
Create an PartialView cshtml and write the code for gridview as like in your main view..I feel it will works fine.

Resources