How do I call an Ajax Delete in ASP.NET MVC? - ajax

I'm working with an existing MVC5 web app. We have a typical index page with a delete icon except there is no Delete view. We have an Ajax Post delete in the script section on the index page. I'm brand new to Ajax so I AM a bit over my head in this, so it's probably something really elementary that I'm missing.
But here it is:
$.ajax({
type: "POST",
url: '#Url.Action("DeleteRecord")',
data: data,
success: function (data) {
if (!data) {
doPopStatus("ERROR", "Something went haywire in the submit. Try Again.", "modal-header alert-danger", "fa fa-exclamation-circle text-danger", "alert", "text-danger");
}
else if (data.success === true) {
doPopStatus("Success!", "The record has been removed.", "modal-header alert-success", "fa fa-check-circle text-success", "alert", "text-primary", '#Url.Action("Index")');
}
else { //if (data.isSuccessful === false) {
doPopStatus("Delete Failed!", data.status, "modal-header alert-danger", "fa fa-exclamation-triangle text-warning", "alert", "text-danger");
}
},
error: function (jqXHR, textStatus, errorThrown) {
goReady();
console.error(jqXHR);
let errorDetails = doParseResponseErrorDetails(jqXHR);
doPopStatus("ERROR", "Something went haywire in the post. Try Again.<p>" + jqXHR.status + ": " + jqXHR.statusText + "<br />" + '<div class="bs-callout bs-callout-danger">' + errorDetails + "</div></p>", "modal-header alert-danger", "fa fa-exclamation-circle text-danger", "alert", "text-danger");
}});
This is the code (earlier) in the Index page:
<a id="hlnkDelete" href='#Url.Action("DeleteRecord", new { id = item.ID })' data-id='#item.ID' title="delete record" class="text-red"><i class="fa fa-trash"></i></a>
Finally, the code in the controller method:
[HttpPost]
public ActionResult DeleteRecord(int id)
{
Capture capture = db.Captures.Find(id);
if (capture == null)
return Json(new { success = false, status = "Invalid ID!" }, JsonRequestBehavior.AllowGet);
try
{
db.Captures.Remove(capture);
db.SaveChanges(User.Identity.Name);
return Json(new { success = true, status = "Record Deleted" }, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
Exceptions.Handler.HandleException(ex, System.Web.HttpContext.Current.Request);
return Json(new { success = false, status = ex.Message }, JsonRequestBehavior.AllowGet);
}
}
There is no view for Delete or DeleteRecord, yet this code works in other pages on the same site.
It looks to me like it should all work, and we have similar code in other pages that works fine. The Ajax function is "DeleteRecord", the code earlier in the Index page calls "DeleteRecord" and we named the function "DeleteRecord" in the Controller.
Yet this is the error we get:
Exception: A public action method 'DeleteRecord' was not found on controller 'DemographicsDatabase.Controllers.CapturesController'.
Controller: Captures
Action: DeleteRecord
What am I doing wrong here, or not seeing?

This button wouldn't call the ajax function.
<a id="hlnkDelete" href='#Url.Action("DeleteRecord", new { id = item.ID })' data-id='#item.ID' title="delete record" class="text-red">
<i class="fa fa-trash"></i>
</a>
You have to bind the event like this;
Remove the href attribute in your html. Then add a btnDelete class which we will use later.
<a id="hlnkDelete" data-id='#item.ID' title="delete record" class="text-red btnDelete"><i class="fa fa-trash"></i></a>
Be sure to put the script below the body tag. Then, in your script, bind the event;
<script>
$(document).ready(function(){
$(document).on("click", ".btnDelete",function(){
var data = $(this).data("id");
$.ajax({
type: "POST",
url: '#Url.Action("DeleteRecord")',
data: data,
success: function (data) {
if (!data) {
doPopStatus("ERROR", "Something went haywire in the submit. Try Again.", "modal-header alert-danger", "fa fa-exclamation-circle text-danger", "alert", "text-danger");
}
else if (data.success === true) {
doPopStatus("Success!", "The record has been removed.", "modal-header alert-success", "fa fa-check-circle text-success", "alert", "text-primary", '#Url.Action("Index")');
}
else { //if (data.isSuccessful === false) {
doPopStatus("Delete Failed!", data.status, "modal-header alert-danger", "fa fa-exclamation-triangle text-warning", "alert", "text-danger");
}
},
error: function (jqXHR, textStatus, errorThrown) {
goReady();
console.error(jqXHR);
let errorDetails = doParseResponseErrorDetails(jqXHR);
doPopStatus("ERROR", "Something went haywire in the post. Try Again.<p>" + jqXHR.status + ": " + jqXHR.statusText + "<br />" + '<div class="bs-callout bs-callout-danger">' + errorDetails + "</div></p>", "modal-header alert-danger", "fa fa-exclamation-circle text-danger", "alert", "text-danger");
}
});
});
});
</script>

May I suggest you the following modification. It is as minimal as possible to keep your code across the project a bit similar.
// Put the Ajax call in a function
let deleteRecord = function(itemId){
$.ajax({
type: "POST",
url: '#Url.Action("DeleteRecord")',
data: {id: itemId},
success: function (data) {
if (!data) {
doPopStatus("ERROR", "Something went haywire in the submit. Try Again.", "modal-header alert-danger", "fa fa-exclamation-circle text-danger", "alert", "text-danger");
} else if (data.success === true) {
doPopStatus("Success!", "The record has been removed.", "modal-header alert-success", "fa fa-check-circle text-success", "alert", "text-primary", '#Url.Action("Index")');
} else {
//if (data.isSuccessful === false) {
doPopStatus("Delete Failed!", data.status, "modal-header alert-danger", "fa fa-exclamation-triangle text-warning", "alert", "text-danger");
}
},
error: function (jqXHR, textStatus, errorThrown) {
goReady();
console.error(jqXHR);
let errorDetails = doParseResponseErrorDetails(jqXHR);
doPopStatus("ERROR", "Something went haywire in the post. Try Again.<p>" + jqXHR.status + ": " + jqXHR.statusText + "<br />" + '<div class="bs-callout bs-callout-danger">' + errorDetails + "</div></p>", "modal-header alert-danger", "fa fa-exclamation-circle text-danger", "alert", "text-danger");
}
});
}
And in your view
<a id="hlnkDelete" href='javascript:deleteRecord(#item.ID)' data-id='#item.ID' title="delete record" class="text-red"><i class="fa fa-trash"></i></a>
Hope this help!

Update you anchor tag and add this function and check
<i class="fa fa-trash"></i>
function DeleteCaptureRecord(itemId)
{
$.ajax({
type: "POST",
url: '#Url.Action("DeleteRecord","Captures")',
data: {"id": parseInt(itemId)},
success: function (data) {
if (data != null && data.success) {
doPopStatus("ERROR", data.status , "modal-header alert-danger", "fa fa-exclamation-circle text-danger", "alert", "text-danger");
} else {
doPopStatus("Success!", data.status, "modal-header alert-success", "fa fa-check-circle text-success", "alert", "text-primary", '#Url.Action("Index")');
}
},
error: function (response) {
goReady();
doPopStatus("ERROR", "Something went haywire in the post. Try Again.<p>" + jqXHR.status + ": " + jqXHR.statusText + "<br />" + '<div class="bs-callout bs-callout-danger">' + errorDetails + "</div></p>", "modal-header alert-danger", "fa fa-exclamation-circle text-danger", "alert", "text-danger");
}
});
}

Related

How to delete image and file in my database and folder

when I want to delete data, the data in the rekap table is deleted but the file_rekap table and image_rekap table and those in the folder also don't want to be deleted
Controller Rekap
public function delete_rekap($id){
$data = rekap::findOrfail($id);
$images=image_rekap::where("rekap_id",$data->id)->get();
foreach($images as $image){
if (File::exists("images_rekap/".$image->image)) {
File::delete("images_rekap/".$image->image);
}
}
$files= file_rekap::where("rekap_id",$data->id)->get();
foreach($files as $file){
if (File::exists("rekap_file/".$file->file)) {
File::delete("rekap_file/".$file->file);
}
}
$data->delete();
return redirect()->route('rekap')->with('success','Data berhasil dihapus');
}
this my button
<a href="#" class="btn btn-danger delete m-1" data-id="{{ $row->id}}" data-customer="{{ $row->customer}}" >DELETE</a>
script
$('.delete').click(function(){
var rekapid = $(this).attr('data-id');
var customer = $(this).attr('data-customer');
swal({
title: "Yakin",
text: "Kamu akan menghapus data dengan nama "+customer+" ",
icon: "warning",
buttons: true,
dangerMode: true,
})
.then((willDelete) => {
if (willDelete) {
window.location = "/delete_rekap/"+rekapid+" "
swal("Data Berhasil Terhapus", {
icon: "success",
});
} else {
swal("Data tidak jadi dihapus");
}
});
});
</script>
what steps should i do to fix it
if you want to delete, try
unlink php

I want to delete data without refreshing whole page using ajax

I am new at Laravel, I am trying to delete data with ajax, when I click to delete button, the page is refreshing but data is deleting perfectly but that should not be reloaded.
Controller
public function destroy($id)
{
$delete = Digitizing::where('id', $id)->delete();
return back();
}
HTML view
<a href="{{route('digitizing.delete',$digitizing->id)}}"
class="btn btn-danger" onclick="deleteConfirmation({{$digitizing->id}})">Delete</a>
<script type="text/javascript">
function deleteConfirmation(id) {
Swal.fire({
title: "Delete?",
text: "Please ensure and then confirm!",
type: "warning",
showCancelButton: !0,
confirmButtonText: "Yes, delete it!",
cancelButtonText: "No, cancel!",
reverseButtons: !0
}).then(function (e) {
if (e.value === true) {
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
$.ajax({
type: 'POST',
url: "{{url('digitizing/delete')}}/" + id,
data: {_token: CSRF_TOKEN},
dataType: 'JSON',
success: function (results) {
if (results.success === true) {
swal("Done!", results.message, "success");
} else {
swal("Error!", results.message, "error");
}
}
});
} else {
e.dismiss;
}
}, function (dismiss) {
return false;
})
}
</script>
**Delete wants a get method because you have to give only ID to delete.**
**WEB.PHP**
Route::get('digitizing/delete/{id}','YourController#destroy');
**SCRIPT**
let id = $('#my_id').val();
$.ajax({
type: 'GET',
url: "{{url('digitizing/delete')}}/" + id,
data: {
_token: '{{csrf_token()}}',
},
success: function () {
alert('Successfully Deleted');
}
}).fail(function(){
console.log('problem with route = digitizing/delete');
});

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

hide bootstrap modal after select redirect instead

I would like to close my modalbox, so I return to the same page, after I click the "Select" button.
I am on shuffle.php. I open the modalbox and call the code in updaterecords.php. When I click Select I should return to shuffle.php. The problem is right now that I am redirected to updaterecords.php.
I try to solve that with adding this code to my AJAX call:
$('#editBox').on('hide.bs.modal', function (data) {
$('#editBox').modal('hide')
})
But I am still redirected. Is the code I added in the wrong place?
shuffle.php
<div class="modal-footer msg">
<form action="updaterecords.php" method="post">
<input type="hidden" id="fantasy-id" value="" name="id" />
<button type="submit" name="selectStore" >Select</button>
<button type="button" data-dismiss="modal">Close</button>
</form>
</div>
updaterecords.php
$(document).ready(function() {
$(".btn-open-modal").click(function() {
var id = $(this).data("id");
$.ajax({
type: 'post',
url: 'getdata.php',
data: {
post_id: id
},
success: function(data) {
console.log(data);
var jdata = JSON.parse(data);
if (jdata) {
console.log("is json");
$("#editBox").modal().show();
$('#id').val(jdata.id);
$("#editBox .modal-title").html(jdata.headline);
$("#editBox .modal-body").html("Weekday: " + jdata.weekday + "<br><br>Description: " + jdata.description); // + " " + $query $query => query
$('#editBox').on('hide.bs.modal', function (data) {
$('#editBox').modal('hide')
})
} else {
console.log("not valid json: " + data);
}
}
});
});
});
Please try to use $('.modal').modal('hide'); on updaterecords.php.
$(document).ready(function() {
$(".btn-open-modal").click(function() {
var id = $(this).data("id");
$('.modal').modal('hide');
$.ajax({
type: 'post',
url: 'getdata.php',
data: {
post_id: id
},
success: function(data) {
console.log(data);
var jdata = JSON.parse(data);
if (jdata) {
console.log("is json");
$("#editBox").modal().show();
$('#id').val(jdata.id);
$("#editBox .modal-title").html(jdata.headline);
$("#editBox .modal-body").html("Weekday: " + jdata.weekday + "<br><br>Description: " + jdata.description); // + " " + $query $query => query
$('#editBox').on('hide.bs.modal', function (data) {
$('#editBox').modal('hide')
})
} else {
console.log("not valid json: " + data);
}
}
});
});
});

Delete the record using sweetalert js in codeigniter using ajax

I want to delete the record using sweetalert js.
This is my view file:-
<a class="action-link delete" title="delete" href="#" onclick="confirmDelete()"> <i class="glyphicon glyphicon-trash"></i> </a>
This is my function:-
function confirmDelete(){
var id=1;
swal({
title: 'Are you sure?',
text: "You won't be able to delete this!",
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'OK',
closeOnConfirm: false
},function (isConfirm) {
$.ajax({
url: base_url+"admin/mycontroller/delete",
type: "POST",
data: {"id":id},
dataType:"HTML",
success: function () {
swal("Done!", "It was succesfully deleted!", "success");
},
error: function (xhr, ajaxOptions, thrownError) {
swal("Error deleting!", "Please try again", "error");
}
});
});
}
This is my controller delete function
public function delete(){
$id = $this->input->post('id');
$data[ 'status'] = '0';
$where = array( 'id' => $id );
$this->model->update( $this->tablename , $data , $where );
}
But not delete the data. Please help me out.
Edit: url as below
function confirmDelete(){
var id=1;
swal({
title: 'Are you sure?',
text: "You won't be able to delete this!",
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'OK',
closeOnConfirm: false
},function (isConfirm) {
$.ajax({
url: <?=base_url()?>"admin/mycontroller/delete",
type: "POST",
data: {"id":id},
dataType:"HTML",
success: function () {
swal("Done!", "It was succesfully deleted!", "success");
},
error: function (xhr, ajaxOptions, thrownError) {
swal("Error deleting!", "Please try again", "error");
}
});
});
}

Resources