swal delete and cancel button both deletes the data - ajax

I'm working in php laravel.
what i want is on deleting a record from data-table(loaded using ajax), if the user wants to delete a record they can click the delete button.
Upon clicking the delete button the sweetalert(swal) is used with DELETE and CANCEL button as shown below:
function deleteFeeds(id) {
swal({
title: "Are You Sure?",
text: "",
type: "warning",
showCancelButton: true,
confirmButtonClass: "btn-danger",
confirmButtonText: "yes",
closeOnConfirm: true,
}).then(function (isConfirm) {
if(isConfirm)
{
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
url: baseUrl + 'deleteFeed/' + id,
method: "POST",
success: function (data) {
swal({
title: "deleted",
text: "deleted_successfully",
type: "success",
confirmButtonColor: "#00cc00",
confirmButtonText: "Confirm",
});
window.location.reload();
}
});
}
else{
swal("Cancelled", "Your feed is safe :)", "error");
}
});
}
But if the user selects the CANCEL button the data gets deleted which should not happen.
can anyone help me with this?

use isConfirm.value instead of isConfirm for if condition

Related

Confirmation with SweetAlert, Vue & Laravel

I'm trying delete my data after confirmation and for that I want to use sweetalert.
1
If I use simple alert like:
deletePage(index) {
if (confirm("Do you really want to delete it?")) {
let page = this.pages[index];
axios.delete(`/api/pagedelete/${page.id}`).then(response => {
this.pages.splice(index, 1);
});
}
},
Works fine
2
When I want use sweetalert like:
deletePage(index) {
let page = this.pages[index];
swal({
title: "Are you sure ?",
text: "You will not be able to recover this page !",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes, delete it !",
cancelButtonText: "No, cancel !",
closeOnConfirm: false,
closeOnCancel: false
},
function(isConfirm) {
if (isConfirm) {
axios.delete(`/api/pagedelete/${page.id}`).then(response => {
this.pages.splice(index, 1);
});
}
else {
swal("Cancelled", "Your page has not been deleted !", "error");
}
}
);
}
Doesn't work!
Error I get is:
uncaught exception: SweetAlert: Unexpected 2nd argument (function (isConfirm) {
var _this2 = this;
if (isConfirm) {
axios.delete('/api/pagedelete/' + page.id).then(function (response) {
_this2.pages.splice(index, 1);
});
} else {
swal("Cancelled", "Your page has not been deleted !", "error");
}
})
Any idea how to fix this?
The documentation shows it using promises for confirmation:
swal({
title: "Are you sure?",
text: "Once deleted, you will not be able to recover this imaginary file!",
icon: "warning",
buttons: true,
dangerMode: true,
})
.then((willDelete) => {
if (willDelete) {
swal("Poof! Your imaginary file has been deleted!", {
icon: "success",
});
} else {
swal("Your imaginary file is safe!");
}
});
Your example would then be:
deletePage(index) {
let page = this.pages[index];
swal({
title: "Are you sure ?",
text: "You will not be able to recover this page !",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes, delete it !",
cancelButtonText: "No, cancel !",
closeOnConfirm: false,
closeOnCancel: false
}).then((confirmed) => {
if (confirmed) {
axios.delete(`/api/pagedelete/${page.id}`).then(response => {
this.pages.splice(index, 1);
});
} else {
swal("Cancelled", "Your page has not been deleted !", "error");
}
});
}

jqgrid navButtonAdd response

How to get a json response from a jqgrid custom button. Here is my code
$("#jqGrid").navButtonAdd('#jqGridPager', {
id: "btnCustom",
caption: "",
title: "Test Title",
buttonicon: 'fa fa-file-excel-o',
onClickButton: function () {
window.location.href = "/Controller/Action";
//need to get a responce
},
position: "last"
});
You will need to replace the
...
window.location.href = "/Controller/Action";
...
with ajax like
$.ajax({
url : "/Controller/Action",
dataType : "json",
success : function(response, status, jqXHR) {
// response is your json data
}
});

SweetAlert2 - Dynamic queue without clicking confirm button?

I am using the latest version of the jQuery plugin SweetAlert2. I want to use the "Dynamic queue"-function to make a AJAX call. So on the homepage there is a nice example, but you have to click a confirm button first to execute the AJAX call. I do not want this, when the alert is shown the AJAX call should execute immediately, without clicking a button. So how to do this?
Here the example from the homepage
swal.queue
([{
title: 'Your public IP',
confirmButtonText: 'Show my public IP',
text: 'Your public IP will be received via AJAX request',
showLoaderOnConfirm: true,
preConfirm: function()
{
return new Promise(function (resolve)
{
$.get('https://api.ipify.org?format=json').done(function(data)
{
swal.insertQueueStep(data.ip);
resolve();
});
});
}
}])
You should pass the callback with the AJAX request to onOpen parameter:
Swal.queue([{
title: 'Your public IP',
confirmButtonText: 'Show my public IP',
text:
'Your public IP will be received ' +
'via AJAX request',
onOpen: () => {
fetch('https://api.ipify.org?format=json')
.then(response => response.json())
.then(data => {
Swal.insertQueueStep(data.ip)
})
}
}])
<script src="https://cdn.jsdelivr.net/npm/sweetalert2#8"></script>
My working example for auto submit form with sweetalert loading and display results.
var preMessage = $('#new-ad-form').attr('pre-message');
var formData = $('#new-ad-form').serialize();
var formUrl = $('#new-ad-form').attr('action');
Swal.queue([{
allowOutsideClick: false,
allowEscapeKey: false,
title: preMessage,
showConfirmButton: false,
showCloseButton: false,
showCancelButton: false,
onOpen: () => {
Swal.showLoading();
return fetch(formUrl, {
method: 'POST',
body: formData,
headers: {
'Accept': 'application/json, text/plain, */*',
'Content-Type': "application/x-www-form-urlencoded",
}
})
.then(response => response.json())
.then(data => {
Swal.hideLoading();
if (data.status == 'success') {
Swal.update({
allowEscapeKey: false,
allowOutsideClick: false,
showConfirmButton: false,
showCloseButton: false,
showCancelButton: false,
type: 'success',
title: false,
html: data.html
})
} else {
Swal.update({
type: 'error',
title: false,
html: data.html,
allowEscapeKey: true,
allowOutsideClick: true,
showConfirmButton: true,
})
}
})
.catch(() => {
Swal.hideLoading();
Swal.update({
type: 'error',
title: 'Save request error!',
html: false
})
})
}
}]);

In kendo grid Update button is not firing

I have Kendo UI inline Grid. It read and populate the grid properly. but when i press edit and changes in any column and press update then update event is not firing. and it also not calling controller method.
my view
$(document).ready(function () {
dataSource = new kendo.data.DataSource({
transport:
{
read:
{
url: "/Student/StudentGrid",
contentType: "application/json; charset=utf-8",
dataType: "json",
type: "GET"
},
update:
{
url: "#Url.Action("EditStudentDetails")",
contentType: "application/json;charset=utf-8",
dataType: "json",
type: "POST"
},
parameterMap: function (options, operation) {
if (operation != "read" && options) {
if (operation != "destroy") {
return JSON.stringify({
studentViewModel: options
});
}
else if (operation == "destroy") {
return JSON.stringify({
id: options.Id
});
}
}
}
},
parse: function (test) {
if (test.success) {
if (test.type != "read") {
alert(test.message);
$("#grid").data("kendoGrid").dataSource.read();
}
return test.data;
}
else {
alert(test.message);
return [];
}
}
})
$("#grid").kendoGrid({
dataSource: dataSource,
filterable: true,
toolbar: ["create"],
sortable: true,
pageable: true,
columns: [
{
field: "Id",
width: 120,
visible: false
},
{
field: "Name",
title: "Student Name",
editor: AutocompleteName,
width: 180
},
{
field: "CourseName",
title: "Course Name",
editor: CourseDropDownEditor,
width: 200,
template: "#=CourseName#"
},
{
command: ["edit", "destroy"], title: " ", width: "250px"
}
],
editable: "inline"
});
What i did wrong in this and when i click on edit button it is changing to editable mode but when i click on update it is not working
Is any of your cell text has HTML tags like "<" or ">", remove them and click on update and check the update event fire.

grid is not loading after edit

1)I am using JQGrid I am able to edit the roa and post the data but the grid is not loading after submit.I know I am missing something but not sure what is.I looked the forum and google around but no result.Any help would be appriciated.Below is the code for your reference
$(document).ready(function() {
jQuery("#g-grid").jqGrid({
datatype: "json",
mtype: 'GET',
url: '${createLink(controller: 'response', action: 'listRequestsAsJSON')}',
colNames: ['Entry Type', 'Life Cycle Status','Start Date','End Date','Key Stakeholder Publish'
,'Remarks','RoadmapGroup','EventStatus'],
colModel: [
{name:'roadMapEntryTypeCode',index:'roadMapEntryTypeCode', editable:true,
edittype:"select",editoptions:{value:initdropdownlist('LIFECYCLE')}},
{name:'lifeCycleStatusCode',index:'lifeCycleStatusCode',editable:true,
edittype:"select",editoptions:{value:initdropdownlist('LIFECYCSTAT')}},
{name:'roadMapEventStartDate',index:'roadMapEventStartDate',editable:true,
formatter:'date',editoptions:{dataInit:datePick}},
{name:'roadMapEventEndDate',index:'roadMapEventEndDate',editable:true,
formatter:'date',editoptions:{dataInit:datePick}},
{name:'keyStakeholderPublisherCode',index:'keyStakeholderPublisherCode',editable:true,
edittype:"select",editoptions:{value:initdropdownlist('KEYSTAKEPUB')}},
{name:'roadMapEventRemarksText',index:'roadMapEventRemarksText',editable:true,
edittype:"textarea",editoptions:{rows:"2",cols:"20"}},
{name:'roadMapGroupName',index:'roadMapGroupName',editable:true
,editoptions:{size:10}},
{name:'roadMapEventStatusCode',index:'roadMapEventStatusCode',editable:true,
edittype:"select",editoptions:{value:initdropdownlist('EVENTSTAT')}}
],
pager: jQuery('#g-pager'),
ondblClickRow: function(rowid) {
jQuery(this).jqGrid('editGridRow', rowid,
{
closeAfterEdit:true,
afterSubmit: function(response,postdata){
var json=response.responseText;
var result=eval("("+json+")");
return [result.status,result.message];},
editCaption: "Edit LifeCycle Roadmap",
bSubmit: "Save",
bCancel: "Cancel",
bClose: "Close",
saveData: "Data has been changed! Save changes?",
bYes : "Yes",
bNo : "No",
bExit : "Cancel",
reloadAfterSubmit:true
});},
viewrecords: true,
gridview: true,
editurl:'${createLink(controller: 'response', action: 'updateAssetLifecycleRoadmap')}'+"?AssetId="+${assetInstance?.id}
});
});
datePick = function(elem){jQuery(elem).datepicker({dateFormat:"mm/dd/yy"});};
$("#bedata").click(function(){
var gr = jQuery("#g-grid").jqGrid('getGridParam','selrow');
if( gr != null ) jQuery("#g-grid").jqGrid('editGridRow',gr,{height:280,reloadAfterSubmit:false});
else alert("Please Select Row");
});
initdropdownlist = function(colName) {
var options = ":";
$.ajax({
async: false,
type: "GET",
url: '${createLink(controller: 'response', action: 'getDropDownList')}?' + "sel=" + colName,
contentType: "application/json; charset=utf-8″,
dataType: "json",
success: function(dropDownListMap) {
for (var i = 0; i < dropDownListMap.option.length; i++) {
options +=";"+dropDownListMap.option[i].value + ":" +dropDownListMap.option[i].label;
}
}
});
return options;
}
2)The other thing is with the edit button,there is no action fired on clicking the button,any idea?
<input type="BUTTON" id="bedata" value="Edit Selected"/>
Try:
$('#unmatchedgrid').setGridParam("ur url and params here" )
jQuery("#g-grid").trigger('reloadGrid')
from the second time you load the grid by fetching the selected parameters (if any)

Resources