I have this page for searching and updating students scores using Ajax.
I have the following JavaScript code to save scores using ajax when 'Save' button is clicked:
function saveScores() {
const id = arguments[0];
var form = document.querySelector("#scores-form");
var studRegNo = form.querySelector('input[name="studRegNo'+id+'"]').value;
var visit1 = form.querySelector('input[name="visit1'+id+'"]').value;
var visit2 = form.querySelector('input[name="visit2'+id+'"]').value;
var visit3 = form.querySelector('input[name="visit3'+id+'"]').value;
var visit4 = form.querySelector('input[name="visit4'+id+'"]').value;
var visit5 = form.querySelector('input[name="visit5'+id+'"]').value;
var visit6 = form.querySelector('input[name="visit6'+id+'"]').value;
const Toast = Swal.mixin({
toast: true,
showConfirmButton: true,
confirmButtonColor: '#10393b',
showCancelButton: true,
confirmButtonText: 'Yes',
cancelButtonText: 'No',
})
Toast.fire({
icon: 'question',
title: 'Do you want to save changes'
}).then((result) => {
if (result.dismiss !== 'cancel') {
$.ajax({
type: 'POST',
url: '../include/ajaxInsert.php',
data: {
studRegNo: studRegNo,
userId: <?php echo $userId; ?>,
visit1: visit1,
visit2: visit2,
visit3: visit3,
visit4: visit4,
visit5: visit5,
visit6: visit6,
id: id,
},
cache: false,
success: function(data) {
if(data!="empty"){
const Toast = Swal.mixin({
toast: true,
showConfirmButton: false,
timer: 2500,
timerProgressBar: true,
didOpen: (toast) => {
toast.addEventListener('mouseenter', Swal.stopTimer)
toast.addEventListener('mouseleave', Swal.resumeTimer)
}
})
Toast.fire({
icon: 'success',
title: 'Changes saved successfully.'
})
}
else{
const Toast = Swal.mixin({
toast: true,
showConfirmButton: false,
timer: 1500,
timerProgressBar: true,
})
Toast.fire({
icon: 'warning',
title: 'No changes made.'
})
}
},
error: function(xhr, status, error) {
console.error(xhr);
},
});
}
})
}
I can successfully search students using PHP/PDO and display the result
I can successfully save the scores without refreshing the page
What I want is to refresh and update the row affected(Total) or the table data after saving the scores without refreshing the page.
Is that possible? and any solution to do that is welcomed.
You'll have to sum up visit1 through 6 and set the innerHtml of the total element to the result in your success function. You didnt give the id of the total element so i assumed it was total.
function saveScores() {
const id = arguments[0];
var form = document.querySelector("#scores-form");
var studRegNo = form.querySelector('input[name="studRegNo'+id+'"]').value;
var visit1 = form.querySelector('input[name="visit1'+id+'"]').value;
var visit2 = form.querySelector('input[name="visit2'+id+'"]').value;
var visit3 = form.querySelector('input[name="visit3'+id+'"]').value;
var visit4 = form.querySelector('input[name="visit4'+id+'"]').value;
var visit5 = form.querySelector('input[name="visit5'+id+'"]').value;
var visit6 = form.querySelector('input[name="visit6'+id+'"]').value;
const Toast = Swal.mixin({
toast: true,
showConfirmButton: true,
confirmButtonColor: '#10393b',
showCancelButton: true,
confirmButtonText: 'Yes',
cancelButtonText: 'No',
})
Toast.fire({
icon: 'question',
title: 'Do you want to save changes'
}).then((result) => {
if (result.dismiss !== 'cancel') {
$.ajax({
type: 'POST',
url: '../include/ajaxInsert.php',
data: {
studRegNo: studRegNo,
userId: <?php echo $userId; ?>,
visit1: visit1,
visit2: visit2,
visit3: visit3,
visit4: visit4,
visit5: visit5,
visit6: visit6,
id: id,
},
cache: false,
success: function(data) {
if(data!="empty"){
document.getElementById("total").innerHtml = visit1 + visit2 + visit3 + visit4 + visit5 + visit6;
const Toast = Swal.mixin({
toast: true,
showConfirmButton: false,
timer: 2500,
timerProgressBar: true,
didOpen: (toast) => {
toast.addEventListener('mouseenter', Swal.stopTimer)
toast.addEventListener('mouseleave', Swal.resumeTimer)
}
})
Toast.fire({
icon: 'success',
title: 'Changes saved successfully.'
})
}
else{
const Toast = Swal.mixin({
toast: true,
showConfirmButton: false,
timer: 1500,
timerProgressBar: true,
})
Toast.fire({
icon: 'warning',
title: 'No changes made.'
})
}
},
error: function(xhr, status, error) {
console.error(xhr);
},
});
}
})
}
Related
i want to send data in the form of row array, which is sent is "name" and "value" of each row, (1 row to next row)
below I save it to formData.append('data[kelompok_jenjang]', datas[i].name);
then post on the url with formData
data = [
{
"name": "Diploma",
"indicator": 2,
"value": 0
},
{
"name": "Dokter",
"indicator": 2,
"value": 0
},
{
"name": "Magister",
"indicator": 2,
"value": 0
},
{
"name": "Profesi",
"indicator": 2,
"value": 0
},
{
"name": "Sarjana",
"indicator": 2,
"value": 0
},
{
"name": "Sarjana Terapan",
"indicator": 2,
"value": 0
}
]
handleSaveTarget = async(e) =>{
e.preventDefault();
let data = this.data;
if(data !== undefined){
swal({
title: "Are You Sure ?",
text: "Save",
icon: "warning",
buttons: true,
dangerMode: false,
}).then((Agree) =>{
if(Agree){
var formData = new FormData();
let sessiondata = JSON.parse(localStorage.getItem("sessiondata"));
this.setState({display: true});
let datas = this.state.ref_data;
let arrayLength = datas.length;
for(var i=0; i < arrayLength; i++){
formData.append('data[id_sp]', sessiondata.i_idunit);
formData.append('data[id_point]', 1);
formData.append('data[kelompok_jenjang]', datas[i].name);
formData.append('data[value]', datas[i].value);
axios.post(AppConfig.SaveTarget, formData).then(res => {
swal({
title: datas.name,
text: "Target Masa Studi Berhasil Disimpan.",
icon: "success",
dangerMode: false,
})
}).catch(err=>{
swal({
title: datas.name,
text: "Target Masa Studi Gagal Disimpan.",
icon: "error",
dangerMode: false,
})
})
}
}
})
}else{
swal({
title: "Data Not Found",
text: "Something's Wrong!",
icon: "error",
// buttons: true,
dangerMode: false,
})
}
}
is there a better way than this to pass data in array form one by one, thanks
You need to make your function async to use the await keyword in order to wait each request to finish
swal({
title: "Are You Sure ?",
text: "Save",
icon: "warning",
buttons: true,
dangerMode: false,
}).then(async (Agree) => {
if (Agree) {
// Your code
for (var i = 0; i < arrayLength; i++) {
const formData = new FormData();
formData.append("data[id_sp]", sessiondata.i_idunit);
formData.append("data[id_point]", 1);
formData.append("data[kelompok_jenjang]", datas[i].name);
formData.append("data[value]", datas[i].value);
await axios
.post(AppConfig.SaveTarget, formData)
.then((res) => {
swal({
title: datas.name,
text: "Target Masa Studi Berhasil Disimpan.",
icon: "success",
dangerMode: false,
});
})
.catch((err) => {
swal({
title: datas.name,
text: "Target Masa Studi Gagal Disimpan.",
icon: "error",
dangerMode: false,
});
});
}
}
});
If you don't like use async and await keywords, I suggest this solution instead
swal({
title: "Are You Sure ?",
text: "Save",
icon: "warning",
buttons: true,
dangerMode: false,
}).then((Agree) => {
if (Agree) {
// Your code
let i = 0;
function send() {
const formData = new FormData();
formData.append("data[id_sp]", sessiondata.i_idunit);
formData.append("data[id_point]", 1);
formData.append("data[kelompok_jenjang]", datas[i].name);
formData.append("data[value]", datas[i].value);
axios
.post(AppConfig.SaveTarget, formData)
.then((res) => {
swal({
title: datas.name,
text: "Target Masa Studi Berhasil Disimpan.",
icon: "success",
dangerMode: false,
});
})
.catch((err) => {
swal({
title: datas.name,
text: "Target Masa Studi Gagal Disimpan.",
icon: "error",
dangerMode: false,
});
})
.finally(() => {
i++;
if (i < arrayLength) {
send();
}
});
}
send();
}
});
I'am use sweeet alert with type input text to handle confirmation in my program. This is my js code,
$(document).on('click', '.tl_skripsi', function(){
var id = $(this).attr("id"); //ID mjudul
Swal.fire({
title: "Anda yakin tidak lulus?",
text: "",
input: 'text',
inputPlaceholder: "Ketik 'TIDAK LULUS'",
confirmButtonColor: "#DD6B55",
confirmButtonText: "Tidak Lulus",
closeOnConfirm: false,
cancelButtonText: "Batal",
showCancelButton: true,
}).then(result => {
var konfirmasi = swal.getInput();
if (konfirmasi === "TIDAK LULUS") {
$.ajax({
url: '<?php echo base_url(); ?>prodi/#',
type: 'POST',
data: {id: id},
error: function() {
alert('Something is wrong');
},
success: function(data) {
window.location.href="<?php echo base_url(); ?>prodi/redirect_tl_skripsi";
}
});
} else {
toastr.error(konfirmasi);
}
})
});
My problem is condition always return false even though I have type TIDAK LULUS.
Note: value konfirmasi is captured
I have a sweetalert/javascript function and I want my users to upload two images and one text to my database. I only found out how to upload images using basic HTML "file" boxes. But not how to do it with sweetalert....
This is my sweetalert/Javascript code
$(document).ready(function() {
$('#new-btn').click(function() {
swal.mixin({
input: 'text',
confirmButtonText: 'Next →',
showCancelButton: true,
progressSteps: ['1', '2', '3']
}).queue([{
input: 'file',
inputAttributes: {
name: "image",
class: "image",
},
title: 'Profilbild hochladen',
text: 'Empfohlen wird 1X1'
},
{
input: 'file',
title: 'Hintergrundbild hochladen',
text: 'Empfohlen wird 16X9'
},
{
title: 'Über mich',
text: ''
},
]).then((result) => {
if (result.value) {
var kuerzeltest = "mk304";
$.ajax({
type: "POST",
url: "../../register/profil_update.php",
data: {
"post": result.value[2],
"kuerzel": kuerzeltest
},
});
$.ajax({
type: "POST",
url: "../../register/profil_update.php",
data: {
"bild": new FormData(this),
"bild2": result.value[1],
"kuerzel": kuerzeltest
},
contentType: false,
processData: false,
});
swal(
"Super!",
"Dein Profil wurde erfolgreich aktualisiert ",
"success"
)
}
})
});
})
and this is my backend code
<?php
include_once '../../userdata.php';
//Posts in Datenbank schreiben
$kuerzel = $_POST["kuerzel"];
$bild = $_FILES['bild'];
$bild2 = $_FILES['bild2'];
$post = $_POST["post"];
$pdo = new PDO ($dsn, $dbuser, $dbpass, array('charset'=>'utf8'));
$sql = "INSERT INTO user_bilder (kuerzel, bild, bild2, post) VALUES (?, ?, ?, ?)";
$statement = $pdo->prepare($sql);
$statement->execute(array("$kuerzel", "$bild", "$bild2", "$post"));
$row = $statement->fetchObject();
header("Location: ../webpage/home.php");
?>
My server where I run this code on https://mars.iuk.hdm-stuttgart.de/~mk304/Web_Projekt/webpage/ui/sweetalert/sweetalert_eingabe.php
I really don't know where my error is,
Is possible to customize the error from the
Sequelize.ValidationError
Model:
var PaymentType = sequelize.define('payment_type' , {
id: {
type: DataTypes.INTEGER(11),
allowNull: false,
primaryKey: true,
autoIncrement: true,
field: 'id'
},
code: {
type: DataTypes.STRING,
allowNull: false,
validate:{
notEmpty: true
},
field: 'code'
},
name: {
type: DataTypes.STRING,
allowNull: false,
validate:{
notEmpty: true
},
field: 'name'
}
}, {
timestamps: true,
paranoid: false,
underscored: true,
freezeTableName: true,
tableName: 'payment_types'
});
My controller:
update(req, res) {
paymentType
.update(req.body, {
where: {
id: req.params.id
}
})
.then( updatedRecords => {
res.status(200).json(updatedRecords);
})
.catch(Sequelize.ValidationError, error => {
res.status(400).json(error);
})
.catch( error => {
res.status(500).json(error);
});
},
The errors I get, are this way:
{
"name": "SequelizeValidationError",
"message": "Validation error: Validation notEmpty failed",
"errors": [
{
"message": "Validation notEmpty failed",
"type": "Validation error",
"path": "name",
"value": {},
"__raw": {}
}
]
}
I want to pass the errors like this(only path and message):
{
"name":"The field cannot be empty",
"other_field":"custom error message"
}
I don't know if I can specify a custom message in the model or I have to create a function to build the errors messages.
If I have to build a function, how can I extract the path and customize the message?
Thanks in Advance.
You can catch Sequelize's ValidationError and loop through its ValidationErrorItem's and write a custom message depending on the error type (determined by ValidationErrorItem.validatorKey). Here is a code snippet to get started.
try {
// sequelize custom logic here
} catch(e) {
const messages = {};
if (e instanceof ValidationError) {
e.errors.forEach((error) => {
let message;
switch (error.validatorKey) {
case 'isEmail':
message = 'Please enter a valid email';
break;
case 'isDate':
message = 'Please enter a valid date';
break;
case 'len':
if (error.validatorArgs[0] === error.validatorArgs[1]) {
message = 'Use ' + error.validatorArgs[0] + ' characters';
} else {
message = 'Use between ' + error.validatorArgs[0] + ' and ' + error.validatorArgs[1] + ' characters';
}
break;
case 'min':
message = 'Use a number greater or equal to ' + error.validatorArgs[0];
break;
case 'max':
message = 'Use a number less or equal to ' + error.validatorArgs[0];
break;
case 'isInt':
message = 'Please use an integer number';
break;
case 'is_null':
message = 'Please complete this field';
break;
case 'not_unique':
message = error.value + ' is taken. Please choose another one';
error.path = error.path.replace("_UNIQUE", "");
}
messages[error.path] = message;
});
}
}
You can specify a custom message for sequelize Validation, Your code will look something like this
`var PaymentType = sequelize.define('payment_type' , {
id: {
type: DataTypes.INTEGER(11),
allowNull: false,
primaryKey: true,
autoIncrement: true,
field: 'id'
},
code: {
type: DataTypes.STRING,
allowNull: false,
validate:{
notEmpty: {
args: true,
msg: “code cannot be empty"
}
},
field: 'code'
},
name: {
type: DataTypes.STRING,
allowNull: false,
validate:{
notEmpty: {
args: true,
msg: “code cannot be empty"
}
},
field: 'name'
}
I specified the validation rule as an object, in the above case, notEmpty should be true so I refactored it to an object setting the args property to true i.e notEmpty should be true, and the second property is msg which contains our custom message
notEmpty: {
args: true,
msg: “code cannot be empty"
}
Do you try to change Model like this:
var PaymentType = sequelize.define('payment_type' , {
id: {
type: DataTypes.INTEGER(11),
allowNull: false,
primaryKey: true,
autoIncrement: true,
field: 'id'
},
code: {
type: DataTypes.STRING,
allowNull: false,
validate:{
notEmpty: {
msg: "The field cannot be empty"
}
},
field: 'code'
},
name: {
type: DataTypes.STRING,
allowNull: false,
validate:{
notEmpty: {
msg: "The field cannot be empty"
}
},
field: 'name'
}
}, {
timestamps: true,
paranoid: false,
underscored: true,
freezeTableName: true,
tableName: 'payment_types'
});
Reference this post
I have codeigniter flashdata + jQuery AJAX call to show it. the code:
<script type="application/javascript">
var res_no = '<?php echo $this->session->flashdata('res_no'); ?>';
var res_new = '<?php echo $this->session->flashdata('res_new'); ?>';
(function( $ ) {
$("#check-reservations").click(function() {
$.ajax({
type: "POST",
url: "mycontroller/function",
async: true,
data: {
res_no: res_no,
res_new: res_new
},
success: function(data) {
if(data) {
alert(data);
}
}
});
});
/*
Default Notifications
*/
$('#check-reservations').show(function() {
if (res_no) {
new PNotify({
title: 'Hmm no new Reservations..',
text: res_no,
type: 'custom',
addclass: 'notification-primary',
icon: 'fa fa-info-circle '
});
}
else if (res_new) {
new PNotify({
title: 'There\'s something new!',
text: res_new,
type: 'custom',
addclass: 'notification-success',
icon: 'fa fa-check'
});
}
});
}).apply( this, [ jQuery ]);
</script>
inside the $.ajax data, i have added both
res_no: res_no,
res_new: res_new
which are just strings with text, upon success I retrive back alert with text. I want to get back the
new PNotify({
title: 'Hmm no new Reservations..',
text: res_no,
type: 'custom',
addclass: 'notification-primary',
icon: 'fa fa-info-circle '
});
PHP:
/**
* #filtered_reservations
* #index
*/
$filtered_reservations = $this->filter_array($reservations);
if (count($filtered_reservations) > 0) {
foreach ($filtered_reservations as $index => $reservation) {
$this->db->insert('reservations', $reservation);
} // end foreach
return $this->session->set_flashdata('res_new', "Success ". count($filtered_reservations) ." Reservations were Inserted!");
print "Success ". count($filtered_reservations) ." Reservations were Inserted!";
print "Reservations: ". count($kigores_id) ." found on kigo!";
} /* end if */
/**
* #filtered_reservations
* equal to 0
*/
elseif (count($filtered_reservations) === 0) {
print "Sorry no new Reservations!";
return $this->session->set_flashdata('res_no', 'Sorry no new Reservations!');
//$this->ci_alerts->set('warning', "Sorry no new Reservations!");
}
} /* end reservations */
What should I write in the data? Only solution I found so far is the window.reload which will show me the notification like I want but with refresh..
In order for that to happen, you need to place this:
$('#check-reservations').show(function() {
if (res_no) {
new PNotify({
title: 'Hmm no new Reservations..',
text: res_no,
type: 'custom',
addclass: 'notification-primary',
icon: 'fa fa-info-circle '
});
} else if (res_new) {
new PNotify({
title: 'There\'s something new!',
text: res_new,
type: 'custom',
addclass: 'notification-success',
icon: 'fa fa-check'
});
}
});
inside your AJAX success results, like this:
$.ajax({
type: "POST",
url: "mycontroller/function",
async: true,
data: {
res_no: res_no,
res_new: res_new
},
success: function(data) {
if(data) {
$('#check-reservations').show(function() {
if (res_no) {
new PNotify({
title: 'Hmm no new Reservations..',
text: res_no,
type: 'custom',
addclass: 'notification-primary',
icon: 'fa fa-info-circle '
});
} else if (res_new) {
new PNotify({
title: 'There\'s something new!',
text: res_new,
type: 'custom',
addclass: 'notification-success',
icon: 'fa fa-check'
});
}
});
}
}
});