How do I upload sweetalert photos to my database - javascript

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,

Related

Update table and refresh the table after update using AJAX

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);
},
});
}
})
}

Confirmation sweet alert with condition

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

How do i use a variable in the columns section of an ajax request for data tables

I'm trying to add dynamic values for the column section in an ajax request so that the users can have control over what fields are in the data tables.
I tried with default values and it worked but when i changed to use dynamic values from a variable, the ajax field gives me errors
this works fine;
$(function() {
$('#myTable').DataTable({
processing: true,
serverSide: true,
ajax: '{{ route('members.create') }}',
columns: [
{ data: 'name', name: 'name' },
{ data: 'email', name: 'email' },
{ data: 'address', name: 'address' },
{ data: 'contact', name: 'contact' },
{ data: 'nationality', name: 'nationality' },
{ data: 'dob', name: 'dob' },
{ data: 'hometown', name: 'hometown' },
{ data: 'action', name: 'action', orderable: false, searchable: false }
]
});
});
this is where the problem comes in;
$(function() {
$('#myTable').DataTable({
processing: true,
serverSide: true,
ajax: '{{ route('members.create') }}',
columns: [
var memberFields = <?php echo json_encode($chosen_member_fields, JSON_UNESCAPED_UNICODE); ?>;
for(var i = 0; i < memberFields.length; i++){
{ data: memberFields[i], name: memberFields[i] };
},
{ data: 'action', name: 'action', orderable: false, searchable: false }
]
});
});
Thats because column property wants an array .
And your structure to build array is incorrect .
Do this :
$(function() {
var memberFields = <?php echo json_encode($chosen_member_fields, JSON_UNESCAPED_UNICODE); ?>;
var columnArray = [];//To save for value into an Array
for(var i = 0; i < memberFields.length; i++){
columnArray.push({ data: memberFields[i], name: memberFields[i] });//push valuse to array
},
columnArray.push({ data: 'action', name: 'action', orderable: false, searchable: false });//push last value
$('#myTable').DataTable({
processing: true,
serverSide: true,
ajax: '{{ route('members.create') }}',
columns: columnArray , //just say Array name !
});
});
Didnt test but hope works

Update specific rows without reloading the JqGrid

I am current using a JqGrid for my data visualization.
Here is my JqGrid configurations.
$('#jqGrid').jqGrid({
url: '/ConfirmationOfEmployment/GetUsers',
mtype: "POST",
rowNum: currentPageSize,
datatype: "json",
colNames: ['UserId', 'First Name', 'Last Name', 'Email Address', 'Expiry Date', 'Remaining Days', 'Actions','Remind Status'],
colModel: [
{ name: 'UserId', index: 'UserId', align: 'left', hidden: true, edittype: 'text' },
{ name: 'FirstName', index: 'FirstName', align: 'left' },
{ name: 'LastName', index: 'LastName', align: 'left' },
{ name: 'Email', index: 'Email', align: 'left' },
{ name: 'userExpiryDate', index: 'ExpiryDate', align: 'center', classes: 'createdDate' },
{ name: 'remainingDays', index: 'RemainingDays', align: 'center' },
{ name: 'isReminded', index: 'isReminded', align: 'left', hidden: true, edittype: 'text' },
{ name: 'act', index: 'act' },
],
pager: $('#jqPager'),
sortname: currentSortName,
width: '700',
shrinkToFit: false,
sortorder: currentSortOrder,
search: true,
postData: {
filters: RetrieveFilters
},
gridComplete: function () {
var ids = jQuery('#jqGrid').jqGrid('getDataIDs');
var remindStatus = jQuery('#jqGrid').jqGrid('getCol', 'isReminded');
for (var i = 0; i < ids.length; i++) {
var userId = ids[i];
var isUserReminded = remindStatus[i];
var confrim = "<input style='height:25px;width:60px;margin-left:5px;' type='button' value='Confirm' onclick=\"ConfirmUser('" + userId + "','"+i+"');\" />";
var remove = "<input style='height:25px;width:60px;margin-left:5px;' type='button' value='Delete' onclick=\"DeleteUser('" + userId + "');\" />";
var remind;
if (isUserReminded == 'True') {
remind = "<input style='height:25px;width:60px;margin-left:5px;' type='button' disabled value='Remind' onclick=\"RemindUser('" + userId + "');\" />";
}
else {
remind = "<input style='height:25px;width:60px;margin-left:5px;' type='button' value='Remind' onclick=\"RemindUser('" + userId + "');\" />";
}
jQuery('#jqGrid').jqGrid('setRowData', ids[i], { act: confrim + remind + remove });
};
PageIndexHashUpdate();
}
});
In each of row, there are three buttons. Once user click on the "Confirm button" it fire the ConfirmUser javascript ajax call to the server and update the expiry date and the remaining days of the particular user.Once it's get succeeded, it will reload the grid.So its working fine.Here is the code.
ConfirmUser = function (selectedUserId, rowId) {
$.ajax({
url: "/ConfirmationOfEmployment/ConfirmUser",
async: false,
cache: false,
type: "POST",
dataType: "json",
data: { userId: selectedUserId },
error: function (jqXHR, textStatus, errorThrown) {
$.flashMessage({ "error": errorThrown, "alert": "error" });
},
success: function (data, textStatus, jqXHR) {
console.log(rowId);
console.log(data.newExpiryDate);
var rowData = $('#jqGrid').jqGrid('getRowData', rowId);
console.log(rowData);
//rowData.remainingDays = '180';
//rowData.userExpiryDate = data.newExpiryDate;
//$('#jqGrid').jqGrid('setRowData', rowId, rowData)
//$("#jqGrid").jqGrid('setCell', rowid, 'remainingDays', data.remaining);
//$("#jqGrid").jqGrid('getLocalRow', rowid).remainingDays = data.remaining;
$('#jqGrid').trigger("reloadGrid", [{ page: currentPage, current: true }]);
}
});
};
But the problem is that,once the user keep on clicking the confirm button for various user records, each and every time it will reload the grid which is much time consuming.So what I am seeking is a way to update the particular row only(instead of reloading the grid.)
I tried to use 'setCell' and 'setRowData' methods(commented out lines.) but I failed. So I would like to know how to do update particular cell or row without reloading the grid? Thank you.

jQuery AJAX return the function as data upon success

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'
});
}
});
}
}
});

Categories

Resources