Need help in converting PDO array execution to mysqli statements. This executes for an AJAX POST call for deleting a particular id from database with SWAL function.
<?php
require_once 'connectivity.php';
$response = array();
if ($_POST['delete']) {
$pid = intval($_POST['delete']);
$query = "DELETE FROM students WHERE id=$pid";
$stmt = mysqli_query($query,$connect);
$stmt->execute(array(':pid'=>$pid));
if ($stmt) {
$response['status'] = 'success';
$response['message'] = 'Student Deleted Successfully ...';
} else {
$response['status'] = 'error';
$response['message'] = 'Unable to delete ...';
}
echo json_encode($response);
}
?>
This is the consecutive swal function which is to be executed once the delete button clicked.
<script>
$(document).ready(function(){
$(document).on('click', '#deleteid', function(e){
var productId = $(this).data('id');
SwalDelete(productId);
e.preventDefault();
});
});
function SwalDelete(productId){
swal({
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: 'delete.php',
type: 'POST',
data: {'delete' : productId}
})
.done(function(response){
swal('Deleted!', response.message, response.status);
readDetails();
})
.fail(function(){
swal('Oops...', 'Something went wrong with ajax !', 'error');
window.location.reload(true);
});
});
},
allowOutsideClick: false
});
}
function readDetails(){
window.location.reload(true);
}
Related
So I am making a checkbox for each row in my table so I can delete multiple rows at once.
I am trying to do this for each row inside my table:
<td><input id="checkItem" name="delete[]" type="checkbox" value="<?=$product->id;?>"></td>
Then delete[] is holding the array.
My issue is, I am using json (ajax) to parse my data.
It is only recognizing the last delete[] checkbox I have on my page.
If I check the last checkbox and hit delete all (my button to execute multi-selected rows), it shows the product id, this is good.
If I try any other checkbox, it returns nothing.
Here is the checkbox line that creates checkbox array for each row:
enter image description here
Here is the post function:
enter image description here
Here is my delete function:
enter image description here
Here is my json ajax code to process the requests:
$("body").on("submit", ".ajax-form", function (e) {
e.preventDefault();
form = $(this);
url = form.attr("action");
method = form.attr("method");
data = {};
form.find("[name]").each(function (key, value) {
type = $(this).attr("type");
name = $(this).attr("name");
if (type == "radio" || type == "checkbox") {
value = "";
if ($(this).prop("checked")) value = $(this).val();
} else value = $(this).val();
data[name] = value;
});
button_lang = $("[type=submit]", form).html();
var saveData = $.ajax({
type: method,
crossDomain: true,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
url: url,
data: data,
dataType: "json",
success: function(response) {
messages = "";
if(response.success === true)
{
if(response.redirect)
{
$('.ajax-form').trigger("reset");
window.location.href = response.redirect;
}
else if(response.success)
{
for (var message in response.messages) {
messages += response.messages[message] + "<br>";
}
if(response.timer) {
const Toast = Swal.mixin({
toast: true,
position: 'top-end',
showConfirmButton: false,
timer: 3000,
timerProgressBar: true,
onOpen: (toast) => {
toast.addEventListener('mouseenter', Swal.stopTimer)
toast.addEventListener('mouseleave', Swal.resumeTimer)
}
});
Toast.fire({
icon: 'success',
title: "<h6 style='text-align: left!important;'>" + messages + "</h6>"
});
$('.ajax-form').trigger("reset");
window.setTimeout(function(){window.location.href = response.sendTo;},response.timer);
} else {
const Toast = Swal.mixin({
toast: true,
position: 'top-end',
showConfirmButton: false,
timer: 3000,
timerProgressBar: true,
onOpen: (toast) => {
toast.addEventListener('mouseenter', Swal.stopTimer)
toast.addEventListener('mouseleave', Swal.resumeTimer)
}
});
Toast.fire({
icon: 'success',
title: "<h6 style='text-align: left!important;'>" + messages + "</h6>"
});
$('.ajax-form').trigger("reset");
}
}
else
{
location.reload();
}
}
else
{
for (var message in response.messages) {
messages += response.messages[message] + "<br>";
}
const Toast = Swal.mixin({
toast: true,
position: 'top-end',
showConfirmButton: false,
timer: 3000,
timerProgressBar: true,
onOpen: (toast) => {
toast.addEventListener('mouseenter', Swal.stopTimer)
toast.addEventListener('mouseleave', Swal.resumeTimer)
}
});
Toast.fire({
icon: 'error',
title: "<h6 style='text-align: left!important;'>" + messages + "</h6>"
});
}
}
});
saveData.fail(function() {
const Toast = Swal.mixin({
toast: true,
position: 'top-end',
showConfirmButton: false,
timer: 3000,
timerProgressBar: true,
onOpen: (toast) => {
toast.addEventListener('mouseenter', Swal.stopTimer)
toast.addEventListener('mouseleave', Swal.resumeTimer)
}
});
Toast.fire({
icon: 'error',
title: "<h6 style='text-align: left!important;'>A system error occured</h6>"
});
});
});
Try this. But #El_Vanja is right. Your code is highly room for improvement
form.find('input:checkbox').each(function (key, value) {
type = $(this).attr("type");
name = $(this).attr("name");
if (type == "radio" || type == "checkbox") {
value = "";
if ($(this).prop("checked")) value = $(this).val();
} else value = $(this).val();
data.push({name:value});
});
This is my button:
<button class="btn btn-danger" onclick="deleteConfirmation({{$wp->id}})" id="{{$wp->id}}" data-id="{{$wp->id}}"><i class="fa fa-trash"></i></button>
This is my jquery + ajax code:
function deleteConfirmation(id) {
swal.fire({
title: "Usunąć wypis?",
text: "Upewnij się czy chcesz usunąć ten wypis!",
type: "warning",
showCancelButton: !0,
confirmButtonText: "Tak, usuń go!",
cancelButtonText: "Nie, anuluj!",
reverseButtons: !0
}).then(function (e) {
if (e.value === true) {
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
$.ajax({
type: 'POST',
url: "{{url('/przedsiebiorca/wypisy/destroy')}}/" + id,
data: {"_token": "{{ csrf_token() }}"},
dataType: 'JSON',
success: function (results) {
if (results.success === true) {
swal.fire("Usunięto wypis!", results.message, "success");
} else {
swal.fire("Wystąpił błąd!", results.message, "error");
}
}.then(function() {
location.reload();
});
});
} else {
e.dismiss;
}
}, function (dismiss) {
return false;
})
}
This is my Laravel Controller function destroy()
public function destroy(Request $request, $id)
{
//
$delete = \App\Wypisy::where('id', $id)->delete();
return back();
// check data deleted or not
if ($delete == 1) {
$success = true;
$message = "Wypis został usunięty !";
} else {
$success = true;
$message = "Wypisu nie znaleziono";
}
// Return response
return response()->json([
'success' => $success,
'message' => $message,
]);
return back();
}
when I click the button, show me the confirmation window, and when I click, remove it, I will receive the message jquery.min.js: 2 POST http://localhost:8000/przedsiebiorca/wypisy/3 404 (Not Found) does not happen. As I copy the link above, the removal method works correctly in Laravel. What am I doing wrong ? Any tips?
Laravel 5.8, jquery 3.4.1
If you are passing the id with POST
Your ajax function:
// code ...
type: 'POST',
url: "{{url('/przedsiebiorca/wypisy/destroy')}}",
data: {"_token": "{{ csrf_token() }}", "id": id},
dataType: 'JSON',
success: function (results) {
// code ...
Your route:
Route::post('/przedsiebiorca/wypisy/destroy', 'WypisyController#destroy');
Your Controller
public function destroy(Request $request)
{
//
$id = $request->id;
$delete = \App\Wypisy::where('id', $id)->delete();
// code ...
when i change my code for this
function deleteConfirmation(id) {
swal.fire({
title: "Usunąć wypis?",
text: "Upewnij się czy chcesz usunąć ten wypis!",
type: "warning",
showCancelButton: !0,
confirmButtonText: "Tak, usuń go!",
cancelButtonText: "Nie, anuluj!",
reverseButtons: !0
}).then(function (e) {
if (e.value === true) {
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
$.ajax({
type: 'POST',
url: "{{url('/przedsiebiorca/wypisy/destroy')}}",
data: {"_token": "{{ csrf_token() }}", "id": id},
dataType: 'JSON',
success: function (results) {
if (results.success === true) {
swal.fire("Usunięto wypis!", results.message, "success");
} else {
swal.fire("Wystąpił błąd!", results.message, "error");
}
}
});
} else {
e.dismiss;
}
}, function (dismiss) {
return false;
})
}
i recive in console:
jquery.min.js:2 POST http://localhost:8000/przedsiebiorca/wypisy/destroy
500 (Internal Server Error)
send # jquery.min.js:2
ajax # jquery.min.js:2
(anonymous) # (index):395
Promise.then (async)
ue.then # sweetalert.all.js:1
deleteConfirmation # (index):390
onclick # (index):173
I want to delete records from a MySQL database table using AJAX. I have done it with PHP and work fine. But I've not been able to get it through with AJAX.
AJAX
$(document).ready(function() {
$(".confirm").click(function() {
var bid = $(this).closest("div.box2").find('input[name="dbid"]').val();
var dataString = 'id=' + bid;
$.ajax({
type: "POST",
url: "<?php echo site_url('user/delete_article')?>",
data: dataString,
cache: false,
success: function() {
$.alert('Confirmed!');
}
});
});
});
PHP
public function delete_article($id){
$data['success']='';
$data['error']='';
include_once ('query/user_query.php');
$this->db->where('bid', $id);
$data['countEarticle'] = $this->db->count_all_results('blog');
if($data['countEarticle'] >= 1){
$this->db->where('bid',$id);
$this->db->delete('blog');
}
if($data['countEarticle'] <= 0){
}
}
HTML
<div class="box-footer box-comments box2" style="display: block;">
<input type="hidden" name="dbid" value="<?php echo $draftfull['bid']?>">
<p>
<btn class="btn btn-azure btn-sm confirm"><i class="fa fa-trash-o"></i>Delete Article</btn>
</p>
</div>
I need your help. What am I doing wrong?
try this code:-
public function delete_article(){
$id=$this->input->post('bid');
$data['success']='';
$data['error']='';
include_once ('query/user_query.php');
$this->db->where('bid', $id);
$data['countEarticle'] = $this->db->count_all_results('blog');
if($data['countEarticle'] >= 1){
$this->db->where('bid',$id);
$this->db->delete('blog');
}
if($data['countEarticle'] <= 0){
}
}
try this:
<span class="fa fa-ban"></span>
//ajax
function delete(id) {
swal({
title: "Are you sure to delete?",
text: "Deleting will remove row from listing!",
type: "error",
showCancelButton: true,
confirmButtonClass: "btn-danger",
confirmButtonText: "Yes!",
cancelButtonText: "No",
closeOnConfirm: true,
closeOnCancel: true
}, function (isConfirm) {
if (isConfirm) {
$.post(
base_url + "user/delete_article",
{bid: id},
function (data) {
if (data === "1") {
location.reload();
} else if (data === "0") {
swal("", "Error to deleting data.", "warning");
} else {
swal("", data[0], "error");
}
});
}
});
}
//Controller
function delete_article($id){
if ( $this->model_name->deleteDataById($this->input->post('bid') ) {
die('1');
}
die('0');
}
If I console.log the ID out after I am meant to delete the record, the correct ID displays in console. So, it seems that it is connected up properly but doesn't actually delete a record from my database. I cannot figure this out but it's probably something obvious.
JS
<script type="text/javascript">
$(document).ready(function() {
$('.table-row').on('click', function (e) {
e.preventDefault();
var $otId = $(this).data('ot-id');
swal({
title: 'Are you sure?',
text: "You won't be able to undo this!",
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#FB404B',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes, delete it!',
closeOnCancel: false
}, function (isConfirm) {
if (isConfirm) {
$.ajax({
type: 'post',
url: 'functions/delete-ot-request.php',
data: {otId: $otId},
success: function (result) {
// window.location.href = 'delete-ot.php';
console.log($otId);
},
});
} else {
swal("Cancelled", "Maybe next time then.", "error");
}
});
});
});
</script>
PHP
if(isset($_POST['otId'])) {
$stmt = $link->prepare("DELETE FROM `ot_request` WHERE `id` = ? LIMIT 1");
$stmt->bind_param("i", $_POST['otId']);
$stmt->execute();
$stmt->close();
}
This is the html table row that holds the id:
<tr class="table-row" data-ot-id="{$id}"></tr>
Your console.log($otId); reports the id value you previously sent, not a data coming back from the server side.
Hence this output attests only that the ajax process was successful, not the server job, which is likely what turns wrong for some reason.
So you should look for errors at the server side, starting with sending back some execution trace:
if(isset($_POST['otId'])) {
try {
$stmt = $link->prepare("DELETE FROM `ot_request` WHERE `id` = ? LIMIT 1");
$stmt->bind_param("i", $_POST['otId']);
$stmt->execute();
$stmt->close();
echo 'otId "' . $_POST['otId'] . '" processed';
} catch(PDOException $e) {
echo $e->getMessage;
}
} else {
echo 'No otId found';
}
And modifying your Javascript so you output this trace:
success: function (result) {
console.log(result);
}
I have made a delete modal with Sweet Alert in Laravel and it is deleting user I choose. I would however after deletion like to redirect back to users list as my destroy() method says.
<script>
$('a#delete_user').on('click', function () {
var url = $(this).attr("data-href");
swal({
title: "Delete user?",
text: "Submit to delete",
type: "warning",
showCancelButton: true,
closeOnConfirm: false,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Delete!"
},
function () {
setTimeout(function () {
$.ajax({
type: "POST",
url: url,
data: {
_method: 'DELETE',
_token: csrf_token
},
success: function (data) {
if (data)
swal("Deleted!", "User has been deleted", "success");
else
swal("cancelled", "User has not been deleted", "error");
}
}), 2000
});
});
})
</script>
Here is the controller:
public function destroy($id)
{
User::destroy($id);
return redirect('users')->with('status', 'User Deleted!');
}
I would like to redirect to users list with message, and I have trouble doing so
In your main template file or in view file, you have to check if there is status data in session, if yes so you call sweet alert. Example code:
#if (session('status'))
<script>
$( document ).ready(
swal("{{ session('status') }}")
});
</script>
#endif
Edit js file like this:
success: function (data) {
if (data == 'success')
swal("Deleted!", "User has been deleted", "success");
window.location('Your URL');
else
swal("cancelled", "User has not been deleted", "error");
}
and the controller:
if(User::destroy($id)){
return 'success';
}else{
return 'fail';
}