Calling ActionResult using jquery ajax in .net core - ajax

Action in controller
Method GetById is the same as the Find method and EntityUpdate == Update
public IActionResult CategoryStatus(int id)
{
var data = cm.GetById(id);
if (data.CategoryStatus)
{
data.CategoryStatus = false;
}
else
{
data.CategoryStatus = true;
}
cm.EntityUpdate(data);
return RedirectToAction("Index");
}
I want to call this action from razor view with ajax, can anyone help , thanks.
I add some parts of razor view just in case
<a href="/Admin/Category/CategoryStatus/#item.CategoryID"
class="btn btn-outline-success btn-sm"
onclick="return functionConfirm(this)">
Aktivləşdir
</a>
<script>
function functionConfirm(event) {
swal({
title: 'Are you sure?',
text: "You will not be able to recover this item!",
type: 'warning',
showCancelButton: true,
cancelButtonText: 'No',
cancelButtonClass: 'btn btn-danger',
showConfirmButton: true,
confirmButtonText: 'Yes',
confirmButtonClass: 'btn btn-success'
}, function (isConfirm) {
if (isConfirm) {
$.ajax({//I need your help here
type: "GET",
url: '/Admin/Category/CategoryStatus',
success: function (msg) {
console.log(msg);
},
error: function (req, status, error) {
console.log(msg);
}
});
return true;
} else {
return false;
}
});
return false;
}

Change your code like below:
//add this....
<a data-id="#item.CategoryID"
class="btn btn-outline-success btn-sm"
onclick="return functionConfirm()">
Aktivləşdir
</a>
#section Scripts
{
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.min.css" integrity="sha512-gOQQLjHRpD3/SEOtalVq50iDn4opLVup2TF8c4QPI3/NmUPNZOk2FG0ihi8oCU/qYEsw4P6nuEZT2lAG0UNYaw==" crossorigin="anonymous" referrerpolicy="no-referrer" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.min.js" integrity="sha512-7VTiy9AhpazBeKQAlhaLRUk+kAMAb8oczljuyJHPsVPWox/QIXDFOnT9DUk1UC8EbnHKRdQowT7sOBe7LAjajQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script>
function functionConfirm() {
swal({
title: 'Are you sure?',
text: "You will not be able to recover this item!",
type: 'warning',
showCancelButton: true,
cancelButtonText: 'No',
cancelButtonClass: 'btn btn-danger',
showConfirmButton: true,
confirmButtonText: 'Yes',
confirmButtonClass: 'btn btn-success'
}, function (isConfirm) {
var id = $(event).data("id"); //add....
if (!isConfirm) return;
$.ajax({
type: "GET",
url: '/Admin/Category/CategoryStatus/'+id, //modify...
success: function (msg) {
window.location.href="/xxx/Index"
},
error: function (req, status, error) {
console.log(msg);
}
});
});
}
</script>
}

Related

Laravel/javascript Modal fail to appear

is there anything wrong with my id=submit_fw in the blade, the modal did not appear and I already addressed it to the text/javascript below, the button will submit the data in the show.blade and it supposed to have a confirmation message.
show blade
<div class="col-3 col-xs-3 col-sm-3 col-md-1 col-lg-1 col-xl-1 p-0 mt-0"></div>
#if($fw->fw_current_stg == "UR" && $fw->fw_user == $user)
<div class="col-12 col-xs-12 col-sm-12 col-md-5 col-lg-5 col-xl-5 p-0 mt-0 text-right">
<button type="button" class="btn btn-primary btn-block text-white" id="submit_fw">
<span class="spinner-border spinner-border-sm d-none" id="sp_submit" aria-hidden="true"></span>
<i class="fas fa-check" id="icon_submit"></i> SUBMIT REQUEST
</button>
#endif
text/javascript
$('#submit_fw').click(function()
{
$('#sp_submit').removeClass('d-none');
$('#icon_submit').addClass('d-none');
Swal.fire({
title: 'Proceed PR?',
text: 'Are you sure you want to submit this PR to Department Head?',
icon:'question',
confirmButtonText: 'YES',
confirmButtonColor: '#fa0031',
cancelButtonColor: '#fa0031',
showCancelButton:'true',
cancelButtonText:'NO',
}).then((result) => {
if (result.value) {
$.ajax({
url: "{{route('fw.submitfw')}}",
type:"post",
data:{
fw_number:$('#fw_number').val(),
},
success: function(result){
if(result == "submitted")
{
Swal.fire({
title: 'Success',
text: 'Your PR has been submitted to your Department Head',
icon: 'success',
confirmButtonText: 'Return to List',
confirmButtonColor: '#fa0031',
}).then((result) => {
if (result.value) {
let url = "{{route('fw.index')}}";
document.location.href=url;
}
});
}
}
});
}
else
{
}
});
$(this).prop('disabled',true);
});
First of all check id=submit_fw is only one time used in your blade file.
Then you simply set addEventListener to the id.
var submitButton = document.getElementById('submit_fw');
var submitUrl = "{{route('fw.submitfw')}}";
submitButton.addEventListener('click', function (e) {
e.preventDefault();
$('#sp_submit').removeClass('d-none');
$('#icon_submit').addClass('d-none');
submitButton.disabled = true;
Swal.fire({
title: 'Proceed PR?',
text: 'Are you sure you want to submit this PR to Department Head?',
icon:'question',
confirmButtonText: 'YES',
confirmButtonColor: '#fa0031',
cancelButtonColor: '#fa0031',
showCancelButton:'true',
cancelButtonText:'NO',
}).then((result) => {
if (result.value) {
$.ajax({
url: submitUrl,
type:"post",
data:{
fw_number:$('#fw_number').val(),
},
success: function(result){
if(result == "submitted") {
$('#sp_submit').addClass('d-none');
$('#icon_submit').removeClass('d-none');
submitButton.disabled = false;
Swal.fire({
title: 'Success',
text: 'Your PR has been submitted to your Department Head',
icon: 'success',
confirmButtonText: 'Return to List',
confirmButtonColor: '#fa0031',
}).then((result) => {
if (result.value) {
let url = "{{route('fw.index')}}";
document.location.href=url;
}
});
} else {
Swal.fire({
text: 'Somthing went wrong, please try agian!',
icon: "error",
confirmButtonText: "Ok, got it!",
confirmButtonColor: '#fa0031',
});
$('#sp_submit').addClass('d-none');
$('#icon_submit').removeClass('d-none');
submitButton.disabled = false;
}
},
error: function (jqXHR, textStatus, errorThrown) {
$('#sp_submit').addClass('d-none');
$('#icon_submit').removeClass('d-none');
submitButton.disabled = false;
}
});
} else {
$('#sp_submit').addClass('d-none');
$('#icon_submit').removeClass('d-none');
submitButton.disabled = false;
}
});
});

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

Running Ajax request not working

I just migrated to a different bootstrap template now my ajax functions is not working and my php file which handles the functions is not appearing in the XHR inspect tool of chrome.
I only have this jquery script ? is this enough for running an ajax function? I
<!-- Jquery Core Js -->
<script src="../dashboard-assets/plugins/jquery/jquery.min.js"></script>
HTML CODE
<form id="upload_book_form" method="POST">
<p>Upload Books</p>
<input type="file" id="uploadbookinfo" name="uploadbookinfo" value="Import" />
</form>
SCRIPT FUNCTION
<script type="text/javascript">
$(document).ready(function() {
//upload book
$('#uploadbookinfo').change(function() {
$('#upload_book_form').submit();
});
$('#upload_book_form').on('submit', function(event) {
event.preventDefault();
$.ajax({
url: "adminfunctions.php",
method: "POST",
data: new FormData(this),
contentType: false,
processData: false,
success: function(data) {
var getdata = data.trim();
if (getdata == "SUCCESS") {
swal({
title: 'Success!',
text: 'Book Added , Try refreshing the page',
type: 'success',
confirmButtonClass: "btn btn-success",
buttonsStyling: false
}).then(function() {
$("#uploadbookinfo").val(null);
});
} else if (getdata == "ERRORFILETYPE") {
swal({
title: 'Oops...',
text: 'File type is not supported',
type: 'error',
confirmButtonClass: "btn btn-danger",
buttonsStyling: false
}).then(function() {
$("#uploadbookinfo").val(null);
});
} else {
swal({
title: 'Sorry for the inconvenience!',
text: "There's a problem. Please contact the technical support for any concerns and questions.!",
type: 'error',
confirmButtonClass: "btn btn-info",
buttonsStyling: false
}).then(function() {
$("#uploadbookinfo").val(null);
});
}
},
error: function(jqXHR, exception) {
console.log(jqXHR);
}
});
});
});
</script>

Confirm Before Deleting with Sweet Alert Laravel 5.5

I want the sweet alert box to go out without deleting.
But id not found for ajax
Route
Route::get('room/delete/{id}', 'RoomList#destroy')->name('roomdelete');
View File rooms-list.blade.php
#foreach($rooms as $room)
<tr>
<td>{!! $room->room_id !!}</td>
<td>{!! $room->hotel_id !!}</td>
<td>{!! $room->room_name !!}</td>
<td>
<i class="fa fa-close text-danger"></i> </td>
</tr>
#endforeach
SweetAlert Js Code above
<script>
$(document).on('click', '.button', function (e) {
e.preventDefault();
var id = $(this).data('id');
swal({
title: "Are you sure!",
type: "error",
confirmButtonClass: "btn-danger",
confirmButtonText: "Yes!",
showCancelButton: true,
},
function() {
$.ajax({
type: "POST",
url: "{{url('room/delete')}}",
data: {id:id},
success: function (data) {
}
});
});
});
</script>
Controller File RoomList.php
public function destroy($id) {
$rooms = Room::find($id);
$rooms->delete();
return redirect()->back()->with('deleted', 'Delete Success!');
}
Clicking on the delete button does not work
Best Regards
First thing first, you have a GET route and you are sending a POST request here so first change your ajax method to GET like this:
<script>
$(document).on('click', '.button', function (e) {
e.preventDefault();
var id = $(this).data('id');
swal({
title: "Are you sure!",
type: "error",
confirmButtonClass: "btn-danger",
confirmButtonText: "Yes!",
showCancelButton: true,
},
function() {
$.ajax({
type: "GET",
url: "{{url('room/delete/')}}+id", // since your route has /{id}
data: {id:id},
success: function (data) {
}
});
});
});
</script>
Also I'm not sure about $(document).on('click', '.button', function (e) I guess it should be like this:
$('.button').on('click', '.button', function (e)
Let me know If you still have any issue.

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