SweetAlert combine with ajax - javascript

I have ajax delete function but it keeps cannot work with my sweetalert,i dont know what wrong with my code,can't see any place wrong.Please tell me how to modify it.
function deletei(){
swal({
title: 'Are you sure?',
text: 'You won\'t be able to revert this!',
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes, delete it!'
},function ($rfno,$user) {
theuser = $user;
therfno = $rfno;
$.ajax ({
type: "POST",
url: "updateleave.php",
data: {RefNo: $rfno, userid: $user},
success: function () {
swal('Deleted!', 'Your file has been deleted!', 'success')
}
});
});
}
<input type="button" value="button" onClick="deletei(\'' .$poarr[$i]['RefNo']. '\',\''.$poarr[$i]['StaffId'].'\')" >

So i have updated my successful answer for my current condition.Hope You guys can take a reference indeed,i did not add the library in fiddle ,so you guys may just copy this code and amend yourself.Thanks everyone who provide suggestion for me!
function deletei($refnos,$users){
var refId = $refnos;
var userId = $users;
SwalDelete(refId,userId);
e.preventDefault();
}
function SwalDelete(refId,userId){
swal({
title: 'Are you sure?',
text: 'You won\'t be able to revert this!',
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes, delete it!',
preConfirm: function() {
return new Promise(function(resolve) {
$.ajax ({
type: "POST",
url: "updateleave.php",
data: {RefNo: refId, userid: userId},
success: function(data){
swal('Deleted!', 'Your file has been deleted!', 'success');
var tbl = document.getElementById("myTable");
for (var i=0; i < tbl.rows.length; i++) {
var trs = tbl.getElementsByTagName("tr")[i];
var cellVal=trs.cells[0].innerHTML;
if (cellVal=== refId) {
document.getElementById("myTable").deleteRow(i);
break; }
}
},
});
});
},
});
}
<button type="button" onClick="deletei(\'' .$poarr[$i]['RefNo']. '\',\''.$poarr[$i]['StaffId'].'\')" ></button>

showCancelButton: true, is deprecated. I will recommend using buttons. You could then create an array with what buttons you want.

function deletei(user,rfno){
var theuser = user;
var therfno = rfno;
swal({
title: 'Are you sure?',
text: 'You won\'t be able to revert this!',
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes, delete it!'
},function () {
$.ajax ({
type: "POST",
url: "updateleave.php",
data: {RefNo: therfno, userid: theuser},
success: function () {
swal('Deleted!', 'Your file has been deleted!', 'success')
}
});
});
}
<input type="button" value="button" onClick="deletei(\'' .$poarr[$i]['RefNo']. '\',\''.$poarr[$i]['StaffId'].'\')" >
Try this .
Modification :- remove $ from $rfno
Edit:-You are not passing the value of username and regNo in deletei function.

You call deletei with the two arguments $poarr[$i]['RefNo'] and $poarr[$i]['StaffId'], but you don't use them in deletei. I suspect these arguments should be the value of theuser and therfno?
function deletei($rfno, $user){
swal({
title: 'Are you sure?',
text: 'You won\'t be able to revert this!',
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes, delete it!'
}, function () {
$.ajax ({
type: "POST",
url: "updateleave.php",
data: {RefNo: $rfno, userid: $user},
success: function () {
swal('Deleted!', 'Your file has been deleted!', 'success')
}
});
});
}

Related

add sweetalert2 confirm delete in php without json data

How to use sweetalert2 with delete function in button href ?
i have button like this
<button type="button" id="btnDelete" href=" <?php echo site_url('administrator/master/delete/' . $a->idDept); ?>" class="btn btn-danger fa fa-trash but" data-toggle="tooltip" data-placement="top" title="Delete"></button>
$('.btnDelete').click(function() {
swal.fire({
title: 'Are you sure?',
text: "It will permanently deleted !",
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes, delete it!'
}).then(function() {
swal.fire(
'Deleted!',
'Your file has been deleted.',
'success'
);
});
});
sweetalert2 working but not delete the data
You will need to pass the fetch/ajax method in Swal.fire call.
$('.btnDelete').click(function(e) {
e.preventDefault();
var url = $(this).attr('href');
Swal.fire({
title: 'Are you sure?',
text: "You won't be able to revert this!",
icon: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes, delete it!',
preConfirm: () => {
return fetch(url)
.then(response => {
console.log(response);
if (!response.ok) {
throw new Error(response.statusText)
}
return response.json()
})
.catch(error => {
Swal.showValidationMessage(
`Request failed: ${error}`
)
})
}
}).then((result) => {
if (result.isConfirmed) {
Swal.fire(
'Deleted!',
'Your file has been deleted.',
'success'
)
}
});
});
Use this example codepan and modify it as you need.
https://codepen.io/ympervej/pen/wvJQyOr

Validate required field before swal?

How to validate required input field before swal?I have added required in input field but its not working?swal alerts are working fine,Anyone please help me to solve this issue.Thanks in advance.
<input type="text" class="form-control" name="marks" id="marks" required>
<button type="button" id="btn_upload<?php echo $s;?>" class="btn btn-primary" onClick="FunctionAdd(<?php echo $s;?>)" >Submit</button>
<script>
function FunctionAdd($s)
{
swal({
title: 'Are you sure?',
text: "The data will input",
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Add',
cancelButtonText: 'Cancel'
}).then((result) => {
if (result.value) {alert('submitting');
var myForm = $("#myForm"+$s)[0];
$.ajax({
url:"<?php echo base_url(); ?>creates",
type:"post",
data: new FormData(myForm),
processData:false,
contentType:false,
cache:false,
async:false,
success: function(data){
window.location = '';
},
failure:function(d){
alert("Error")
alert(d)
}
});
}
else if (result.dismiss === 'cancel') {
swal(
'Cancelled',
'You stay here :)',
'error'
)
}
})
You can try triggering HTML5 form validation first using HTMLFormElement.reportValidity
function FunctionAdd($s) {
var myForm = $("#myForm"+$s)[0];
if (myForm.reportValidity()) {
swal({
...
}).then((result) => {
...
});
}
}

Using SweetAlert2 in vue js to make a modal confirmation before deleting the item

I have an error in my sweetalert2 and I am using laravel vue in developing my app. What I want my app to happen is to create a confirmation modal for deleting a row in my database. Whenever I click "Yes", the item is removed but when I click the cancel button, the modal closes but also deletes the entire row. I am very confused as of the moment and this is my first time learning these frameworks and I want to learn more about this.
this is my code under the IndexComponent.vue
methods: {
deletePost(id) {
this.$swal({
title: 'Are you sure?',
text: "You won't be able to revert this!",
icon: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes, delete it!',
closeOnCancel: true
}).then((result) => {
//send request to server
let uri = `/api/post/delete/${id}`;
axios.delete(uri).then(response => {
this.posts.splice(this.posts.indexOf(id), 1);
});
if (result.value) {
this.$swal(
'Deleted!',
'Your post has been deleted!',
'success'
)
}
})
}
}
This is my button placed inside a td in my table:
<td><button #click="deletePost(post.id)" class="btn btn-danger">Delete</button></td>
This is what's inside my PostController.php:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Resources\PostCollection;
use App\Post;
public function delete($id) {
$post=Post::find($id);
$post->delete();
return response()->json('Successfully deleted!');
}
All operations are working (CRUD) but when I tried to implement the sweetalert2 the deletions are multiple. Can someone please help me?
You have to write your API call inside if like this
methods: {
deletePost(id) {
this.$swal({
title: 'Are you sure?',
text: "You won't be able to revert this!",
icon: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes, delete it!',
closeOnCancel: true
}).then((result) => {
//send request to server
if (result.value) {
let uri = `/api/post/delete/${id}`;
axios.delete(uri).then(response => {
this.posts.splice(this.posts.indexOf(id), 1);
});
this.$swal(
'Deleted!',
'Your post has been deleted!',
'success'
)
}
})
}
}
Your splice index is incorrect. It will return -1, then it will delete the last item.
It should be
this.posts = this.posts.filter(post => post.id !== id)
Full code
methods: {
deletePost(id) {
this.$swal({
title: 'Are you sure?',
text: "You won't be able to revert this!",
icon: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes, delete it!',
closeOnCancel: true
}).then((result) => {
//send request to server
if (result.value) {
let uri = `/api/post/delete/${id}`;
axios.delete(uri).then(response => {
this.posts = this.posts.filter(post => post.id !== id)
this.$swal(
'Deleted!',
'Your post has been deleted!',
'success'
)
});
}
})
}
}

Sweet alert not triggering my php file

I am using sweet alerts 2 for my webpage and i am trying to trigger my php file when the user presses delete on the sweet alert, if they do not do nothing. For some odd reason it is not triggering the php file, the pop does not come up either, i ran a simple sweet alert in the console just to see if i have the correct scripts in and it works fine.
I have this code so far :
<form method="post" id="deleteF" name="delete">
<button type="submit" name="delete" class="btn btn-xl btn-mrg" id="delete" >Delete</button>
</form>
$(document).on('submit', 'deleteF', function (e) {
e.preventDefault();
swal({
title: "Are you sure?",
text: "You can not recover your account if you delete!",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Delete",
cancelButtonText: "Cancel",
closeOnConfirm: false,
closeOnCancel: false
},
function (isConfirm) {
if (isConfirm) {
$.ajax({
type: 'POST',
url: 'lib/delete.php',
success: function (data) {
},
error: function (data) {
swal("NOT Deleted!", "Something happened!", "error");
}
});
} else {
swal("Cancelled", "Your account was not deleted", "error");
}
});
return false;
});
My php file only has a simple echo in it just to for testing, any help would be greatly appreciated, Note i only included the relevant parts, the sweet alert section is enclosed in script tags
<a data-id='" . $rows['id'] . "' id='delete_id' class='btn btn-danger btn-sm'<span class='glyphicon glyphicon-trash' href='javascript:void(0)'></span>delete</a>
<script>
$(document).ready(function() {
$(document).on('click', '#delete_id', function(e) {
var id = $(this).data('id');
SwalDelete(id);
e.preventDefault();
});
});
function SwalDelete(id) {
Swal.fire({
title: 'Are you sure?',
text: "It will be deleted permanently!",
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes, delete it!',
showLoaderOnConfirm: true,
preConfirm: function() {
return new Promise(function(resolve) {
$.ajax({
url: 'office_info_delete.php',
type: 'POST',
data: 'id=' + id,
dataType: 'json'
})
.done(function(response) {
Swal.fire('Deleted!', 'Your file has been deleted.', 'success')
})
.fail(function() {
Swal.fire('Oops...', 'Something went wrong with ajax !', 'error')
});
});
},
});
}
</script>

my ajax dont work at all?

I have an AJAX function (below). I am trying to pass an input from one page to another.
It redirects me to the other page but does not pass the required value.
I do not understand why it doesn't work as I expected.
I am looking for another way to do this. Any help will be appreciated.
//second page
<?php
$cuit = $_POST['cuit'];
?>
<input id="act" type="text" class="form-control" value="<?php echo $cuit ?>">
function mod(id, origen) {
swal({
title: 'Are you sure?',
text: "You won't be able to revert this!",
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes, delete it!',
cancelButtonText: 'No, cancel!',
confirmButtonClass: 'btn btn-success',
cancelButtonClass: 'btn btn-danger',
buttonsStyling: false
}).then(function() {
if (origen == "perfiles") {
$.post("api/eliminar_perfil.php", {
id: id
}, function(mensaje) {
$("#tr_" + id).remove();
});
} else if (origen == "index") {
$.ajax({
type: "post",
url: "perfiles.php",
data: {
cuit: $("#cuit").val()
},
success: function(result) {
location.href = 'http://localhost/miramonteapp/perfiles.php';
}
});
}
swal('Deleted!', 'Your file has been deleted.', 'success')
}, function(dismiss) {
// dismiss can be 'cancel', 'overlay',
// 'close', and 'timer'
if (dismiss === 'cancel') {
swal('Cancelled', 'Your imaginary file is safe :)', 'error')
}
})
}
<input id="cuit" type="text" class="form-control" onkeyup="searchCliente();">
<button id="btnBuscar" onclick="mod($('#cuit'), 'index');" type="button" class="btn btn-default" name="button">Buscar</button>
Boy, I think your solution is simpler, you don't need the ajax call if you want to redirect with a param.
so replace this
$.ajax({
type : "post",
url : "perfiles.php",
data : {cuit: $("#cuit").val()},
success : function(result) {
location.href = 'http://localhost/miramonteapp/perfiles.php';
}
});
by this
location.href = 'http://localhost/miramonteapp/perfiles.php?cuit=' +
$("#cuit").val();
and in your destination page perfiles.php
just read the param and use it, you can read params in JS using this as a guide How to get the value from the GET parameters?

Categories

Resources