Sweetalert2 input validation with AJAX - 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!

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 multiple input validation

I'm trying to have multiple forms inside mutiple modals, as I've read I have to use swal.mixin with queue, all of these forms have multiple inputs inside.
I've already done that, but can't find a way to validate all of these forms, any sugestion?
Here's my code:
swal.mixin({
confirmButtonText: 'Siguiente',
buttonsStyling: false,
}).queue([
{
html:
"<form class='formulario' action='' method='post'>" +
"<div class='fila'>"+
"<img src='src/images/svg/icons/person.svg' class='imagen'/>"+
"<input id='name' class='espacio-datos' name='nombre' type='text' placeholder='Nombre' maxlength='20' required>" +
"</div>"+
"<div class='fila'>"+
"<img src='src/images/svg/icons/id.svg' class='imagen'/>"+
"<input id='ced' class='espacio-datos' name='num_ident' type='text' placeholder='Cedula' onkeypress='onlyNumbers(event)'>" +
"</div>"+
"<div class='fila'>"+
"<img src='src/images/svg/icons/phone.svg' class='imagen'/>"+
"<input id='tlf' class='espacio-datos' name='num_telef' type='text' placeholder='Telefono' onkeypress='onlyNumbers(event)'>" +
"</div>"+
"</form>",
preConfirm: function () {
var array = {
'nombre' : $("#name").val(),
'cedula' : $("#ced").val(),
'telefono' : $("#tlf").val(),
}
return array;
},
},
{
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>",
preConfirm: function () {
return [
$("#num-1").val(),
$("#num-2").val(),
$("#num-3").val(),
$("#num-4").val(),
];
},
}
On sweetalert2 the inputValidator function is not called if the modal doesn't have any input defined.
A way to workaround that in your case is to add the input in the mixin but then hide it using onBeforeOpen.
Basically the mixin becomes:
swal.mixin({
confirmButtonText: 'Siguiente',
buttonsStyling: false,
input: 'text'
})
And then you add the following code to each element in the queue array to hide the input text:
onBeforeOpen: function (dom) {
swal.getInput().style.display = 'none';
}
You can see an implementation of that using your code here: https://codepen.io/anon/pen/xQxWMN
I have two at the same time. I wanted to extract number and checkbox input. But I could not get any specific answer regarding its release. After a lot of research, I developed my own version that you might find useful.
Swal.fire({
title : "Ball Adding",
html :
'<input class="swal2-input" id="rating-number" placeholder="Qo`shiladigan ballni yozing" type="number" style=" width: 80%; ">' +
'<label for="rating-checkbox" class="swal2-checkbox" style="display: flex;">' +
'<input type="checkbox" value="1" id="rating-checkbox">' +
'<span class="swal2-label">Chempionat baliga ham qo`shilsin</span>' +
'</label>',
showCancelButton : true,
confirmButtonText : "Qo'shish",
cancelButtonText : 'Bekor qilish',
showLoaderOnConfirm: true,
preConfirm : () => {
console.log('Rating: '+ parseInt(document.getElementById('rating-number').value))
console.log('Checkbox: '+document.getElementById('rating-checkbox').checked)
return parseInt(document.getElementById('rating-number').value)
},
allowOutsideClick : () => !Swal.isLoading()
}).then((result) => {
if (result.isConfirmed) {
console.log(result.value+' rating add')
}
})
<script src="//cdn.jsdelivr.net/npm/sweetalert2#11"></script>
I wrote a function for a project in Nuxtjs to update users score. The code of this function.
ratingAdd() {
Swal.fire({
title : "Ball qo'shish",
html :
'<input class="swal2-input" id="rating-number" placeholder="Qo`shiladigan ballni yozing" type="number" style=" width: 80%; ">' +
'<label for="rating-checkbox" class="swal2-checkbox" style="display: flex;">' +
'<input type="checkbox" value="1" id="rating-checkbox">' +
'<span class="swal2-label">Chempionat baliga ham qo`shilsin</span>' +
'</label>',
showCancelButton : true,
confirmButtonText : "Qo'shish",
cancelButtonText : 'Bekor qilish',
showLoaderOnConfirm: true,
preConfirm : () => {
return this.$axios.post('user/rating-change-aaa', {
user_id : parseInt(this.user_id),
rating : parseInt(document.getElementById('rating-number').value),
checkbox: document.getElementById('rating-checkbox').checked
});
},
allowOutsideClick : () => !Swal.isLoading()
}).then((result) => {
if (result.isConfirmed) {
this.SwalMixin(result.value.data.data.message, 'success')
this.getUserInfo()
}
});
},

Default value of drop-down list with JavaScript and JSON

I have a City field in my form when user select his province/state a drop-down list of cities appear according to selected state. However for the cities list there is no default value like 'Select your city'. I want to add this value.
Below is my field.js :
function getAjaxReqest(action, selectCountry, stateId, normalImput,selectedCity) {
var request = new Ajax.Request(action,
{
method: 'GET',
onSuccess: function (data) {
$('billing:city').replace('<select id="billing:city" name="billing[city]" class="required-entry">' +
'<option value=""></option>' + convertJsonToHtml(data.responseText, this,selectedCity) +
'</select>');
},
onFailure: $('billing:city').replace(normalImput),
parameters: {city_id: stateId, country_id: selectCountry}
}
);
}
function getAjaxReqestCustomer(action, selectCountry, stateId, normalImput, selectedCity) {
var request = new Ajax.Request(action,
{
method: 'GET',
onSuccess: function (data) {
$('city').replace('<select id="city" name="city" class="required-entry">' +
'<option value=""></option>' + convertJsonToHtml(data.responseText, this, selectedCity) +
'</select>');
},
onFailure: $('city').replace(normalImput),
parameters: {city_id: stateId, country_id: selectCountry}
}
);
}
function getAjaxReqestShip(action, selectCountry, stateId, normalImput,selectedCity) {
if (normalImput != null) {
var resetShip = true;
} else {
var resetShip = false;
}
var request = new Ajax.Request(action,
{
method: 'GET',
onSuccess: function (data) {
$('shipping:city').replace('<select id="shipping:city" name="shipping[city]" class="required-entry">' +
'<option value=""></option>' + convertJsonToHtml(data.responseText, this,selectedCity) +
'</select>');
},
onFailure: function (resetShip) {
if (resetShip) {
$('shipping:city').replace(normalImput)
}
},
parameters: {city_id: stateId, country_id: selectCountry}
}
);
}
function convertJsonToHtml(data, ship, selectedCity) {
var jsonData = data.evalJSON();
if (jsonData.length == 0) {
ship.replace(normalImput);
return;
}
console.log(jsonData);
htmlData = '';
jsonData.each(function (item) {
if (item.cityname == selectedCity) {
htmlData += '<option value="' + item.cityname + '" selected>' + item.cityname + '</option>';
} else {
htmlData += '<option value="' + item.cityname + '">' + item.cityname + '</option>';
}
});
return htmlData;
}
While the following code generates the City field on frontend in the form.
<div class="input-box">
<input type="text" title="<?php echo $this->__('City') ?>" name="billing[city]"
value="<?php echo $this->escapeHtml($this->getAddress()->getCity()) ?>"
class="input-text <?php echo $this->helper('customer/address')->getAttributeValidationClass('city') ?>"
id="billing:city"/>
</div>
Any help and tips are appreciated.I am a novice in Javascript and JSON so i am having a hard time playing with it.
EDIT:
I tried this:
div class="input-box">
<input type="text" title="<?php echo $this->__('City') ?>" name="billing[city]"
value="<?php echo $this->escapeHtml($this->getAddress()->getCity()) ?>"
class="input-text <?php echo $this->helper('customer/address')- >getAttributeValidationClass('city') ?>"
id="billing:city"/>
<select name="anything"><option value="undefined" disabled="selected">Select your city</option></select>
</div>
This works but adds the text 'Select your city' below the city field NOT inside it.
use this code as default showing before selecting city (i.e)set value as "undefined" disabled selected.
' +
'Select your city' + convertJsonToHtml(data.responseText, this, selectedCity) +
''

Kendo Mobile Appended form elements from treeview not being noticed

I am trying to figure out why appended form elements are not being notice by kendo mobile --- i have tried 10 different fixes but those items just dont get noticed:
This is in the view:
<li>
<div id="currentMovements">
<ul id="curMoves" data-role="listview" ></ul>
</div>
Add Movements:
<div id="routineMovements"></div>
</li>
And this is my script:
<script>
//init move count
var move_count = 0;
function onSelect(e) {
console.log("Selected: " + this.text(e.node));
//add li to movements div
//make each field unique by li
//using move_count
$("#currentMovements ul").append('<li><input type="text" name="moves[' + move_count + ']" data-min="true" id="moves[' + move_count + ']" class="k-input small-move" value="' + this.text(e.node) + '" /><input type="text" name="id[' + move_count + ']" data-min="true" id="sets[' + move_count + ']" class="k-input small-nums" value="3" /> sets of <input type="text" name="reps[' + move_count + ']" data-min="true" id="reps[' + move_count + ']" class="k-input small-nums" value="10" /><span class="clearitem">Delete</span></li>');
//increase move count
move_count++;
///test to see if the field is being noticed
moves = $('#moves[0]').val();
console.log(moves);
}
function populateRoutineForm() {
$('#curMoves .clearitem').live('click', function() {
$(this).parent().remove();
});
var routineMovementsData = new kendo.data.HierarchicalDataSource({
data: [
{
text: "Chest", items: [
{ text: "Inclined Bench" },
{ text: "Decline Bench" },
{ text: "Dumbell Presses" }
]
},{
text: "Tricep", items: [
{ text: "Cable Pulldowns" },
{ text: "Skull Crushers" },
{ text: "Close Grip Benchpress" }
]
}
]
});
//todo can we use the MVVM stuf from above to do this now?
$("#routineMovements").kendoTreeView({
dataSource: routineMovementsData,
select: onSelect
});
}
function sendAddRoutine() {
var userID = window.localStorage.getItem("userID");
var routine_title = $('#routine_title').val();
var routine_share = $('#routine_share').val();
///test to see if the field is being noticed
moves = $('#moves[0]').val();
console.log(moves);
$.ajax({
url: endpoint + "app/api/add_routine.php",
dataType: "jsonp",
type: "GET",
data: { userID: userID, routine_title: routine_title, routine_share: routine_share },
success: function (data) {
$('#routineResult').html(data.results);
//app.navigate("#view-routineFeed");
}
});
}
$('#routineDoneButton').click(function () {
sendAddRoutine();
});
</script>
Im wondering if there some way to re-init the view without losing other fields that appear above the append div?

Resources