i'v been searching for 2 days and i didint find an answer , so i made a function to delete a property onclick using ajax. but i have a weird probleme i must click twice on the button to work , i dont know why here is my code :
here is my button :
<a style="cursor: pointer"
id="{{ $i->id }}"
data-name="client/{{ Auth::guard('client')->user()->id }}/proprety"
class="delete tooltip left"
title="Supprimer">
<i class="icon-feather-trash-2"></i>
</a>
and here is my script :
$('table').on('click', '.delete', function() {
var id = $(this).attr("id");
var name = $(this).attr("data-name");
Swal.fire({
title: "Es-vous sûr?",
text: "Vous ne pourrez pas revenir en arrière!",
icon: "warning",
showCancelButton: true,
confirmButtonText: "Oui, supprimez-le!",
cancelButtonText: "Non, annuler!",
reverseButtons: true
}).then(function(result) {
if (result.value) {
$.ajax({
url: "/proprety/" + id,
method: "DELETE",
data: {
"_token": "{{ csrf_token() }}",
"id": id
}
});
Swal.fire(
"Supprimé!",
"Vos données ont été supprimées.",
"success"
)
window.location.href = "/" + name;
// result.dismiss can be "cancel", "overlay",
// "close", and "timer"
} else if (result.dismiss === "cancel") {
Swal.fire(
"Annulé",
"Votre données ont en sécurité :)",
"error"
)
}
});
});
UPDATE : the first button trigger sweetalert , after i confirm on sweetalert for the first time nothing happen , i need to repeat the process and trigger sweetalert again to work
UPDATE 1 : This is my controller to delete property :
/**
* Remove the specified resource from storage.
*
* #param \App\Models\Proprety $proprety
* #return \Illuminate\Http\Response
*/
public function destroy($proprety){
$proprety = Proprety::find($proprety);
Image::where('proprety',$proprety->unique)->delete();
Promotion::where('proprety',$proprety->id)->delete();
$proprety->delete();
return 1;
}
You have to click twice because of the way you wrapped the javascript.
Instead of writing this: $('table').on('click', '.delete', function() { ...
you should write this:
$(document).ready( function() {
$(document).on('click', '.delete', function(){ ...
So your new JS syntax should be
$(document).ready( function() {
$(document).on('click', '.delete', function(){
var id = $(this).attr("id");
var name = $(this).attr("data-name");
Swal.fire({
title: "Es-vous sûr?",
text: "Vous ne pourrez pas revenir en arrière!",
icon: "warning",
showCancelButton: true,
confirmButtonText: "Oui, supprimez-le!",
cancelButtonText: "Non, annuler!",
reverseButtons: true
}).then((result) {
if (result.value) {
$.ajax({
url: "/proprety/" + id,
method: "DELETE",
data: {
"_token": "{{ csrf_token() }}",
"id": id
}
});
Swal.fire(
"Supprimé!",
"Vos données ont été supprimées.",
"success"
)
window.location.href = "/" + name;
// result.dismiss can be "cancel", "overlay",
// "close", and "timer"
} else if (result.dismiss === "cancel") {
Swal.fire(
"Annulé",
"Votre données ont en sécurité :)",
"error"
)
}
});
});
});
EDIT:
here are the syntaxes for done() and fail() functions of sweetalert:
$(document).ready( function() {
$(document).on('click', '.delete', function(){
var id = $(this).attr('id');
var url = "{{ route('delete-susomething', ':id') }}";
url = url.replace(':id', id);
var el = this;
var name = $(this).attr('data-name');
Swal.fire({
title: 'Are you sure? <h6>(Page closes in 10 seconds)</h6>',
html: "Blah Blah",
icon: 'warning',
timer: 10000,
showCancelButton: true,
confirmButtonColor: 'green',
cancelButtonColor: '#d33',
confirmButtonText: 'Go ahead',
cancelButtonText: 'Cancel',
}).then((result) => {
if (result.value){
$.ajax({
url: url,
type: 'POST',
data: {'_method':'DELETE', '_token': '{{ csrf_token() }}'},
dataType: 'json'
})
.done(function(response){
swal.fire('Oh Yeah!', "Successfully Deleted.", response.status);
})
.fail(function(){
swal.fire('Damn!', 'Beats me, but something went wrong! Try again.', 'error');
});
}
})
});
});
now in your controller that deletes the item, after deleting, you need to return a response, so add return 1; at the end of the function that handles the deletion.
Related
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');
});
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>
I use sweetalert to get confirm for delete rows from user, the code for confirmation is
$('.delete').click(function(){
var formClass = $(this).attr('id');
$("form."+ formClass).submit(function( event ){
event.preventDefault();
swal({
title: "Do you want delete this item?",
text: "",
type: "warning",
showCancelButton: true,
confirmButtonColor: '#DD6B55',
confirmButtonText: 'yes!',
cancelButtonText: "No",
closeOnConfirm: false,
closeOnCancel: false
},
function(isConfirm) {
if (isConfirm) {
swal({
title: 'Deleted!',
text: 'the item is deleted!',
type: 'success'
}, function() {
form.submit();
});
} else {
swal("Cansel", "Not deleted :)", "error");
}
});
});
});
and this code for use pjax to have an ajax request in laravel
$(document).on('pjax:send', function() {
$('#loading').show();
$("#pjax-container").css({"opacity": "0.3"});
})
$(document).on('pjax:complete', function() {
$('#loading').hide();
$("#pjax-container").css({"opacity": "1"});
})
$(document).on('submit', 'form[form-pjax]', function(event) {
$.pjax.submit(event, '#pjax-container')
});
And the html form is:
<form action="{{ route('admin.comments.destroy',[$comment->id]) }}" class="inline-div comment-{{ $comment->id }}" method="post" form-pjax>
{{ method_field('DELETE') }}
{{ csrf_field() }}
<button type="submit" class="btn btn-sm btn-danger btn-opt delete" id="comment-{{ $comment->id }}"><span class="glyphicon glyphicon-trash"></span></button>
By this code i haven't an ajax request.
Instead of "form.submit();" What to write?
From what I can see, you don't need to use pjax for this at all. You can delete a record from database asynchronously, simply using an ajax request. Here is how I would go about doing this:
In the code below, when the user clicks on the delete link, an alert would be presented to him. If he confirms the delete action, then the function deleteFromDB would be called which is responsible for sending an ajax request to the server.
$('.delete').click(function(){
var formClass = $(this).attr('id');
event.preventDefault();
swal({
title: "Do you want delete this item?",
text: "",
type: "warning",
showCancelButton: true,
confirmButtonColor: '#DD6B55',
confirmButtonText: 'Yes!',
cancelButtonText: "No",
closeOnConfirm: false,
closeOnCancel: false
},
function(isConfirm) {
if (isConfirm) {
deleteFromDB(formClass);
} else {
swal("Cancel", "Not deleted", "error");
}
});
});
The mentioned function is defined as below:
function deleteFromDB(formClass) {
var url = "http://example.com/delete/this/record";
var form = $("form."+ formClass);
var formData = new FormData();
form.find("input[name]").each(function(index, input) {
formData.append(input.name, input.value);
});
$.post(url, formData).done(function(data) {
swal({
title: 'Deleted!',
text: 'the item is deleted!',
type: 'success'
});
});
}
It finds all the inputs that have a name attribute and appends each to a FormData object. Then a post ajax request is sent to the server and when the request is done, another alert showing the success of deletion shows up.
Pay attention here not to show the success alert before deleting the record (as you were doing in the above code), because then if something goes wrong during the request, i.e. the record could not be deleted for some reason, you would be able to show that error to the user.
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");
}
});
});
}
How do you get the value of the textbox field and send as data inside of ajaxOptions? I tested my view and it prints out the test variable successfully from my Django views. I am using X-editable for Jquery. Heres what textbox input looks like:
http://jsfiddle.net/xBB5x/197/
views.py
def create_post(request):
print request.POST.get("test", "");
return HttpResponse(json,content_type="application/json")
HTML
<a id="other1" data-pk="First Name" data-name="test">First Name</a>
AJAX
$(document).ready(function() {
$('#other1').editable({
type: 'text',
pk: 1,
url: '/create_post/',
ajaxOptions: {
data: {
csrfmiddlewaretoken: '{{ csrf_token }}',
test: "hi",
},
},
placement: 'top',
title: 'New Expense',
success: function(response, newValue) {
if(response.status == 'error') return response.msg; //ms
},
});
});
Instead of ajaxOptions, use params. If I remember correctly, test and its value will be included in your POST request by x-editable. Try something like this:
Html
<a id="other1" data-pk="1" data-name="test">First Name</a>
AJAX
$(document).ready(function() {
$('#other1').editable({
type: 'text',
url: '/create_post/',
params : function(params) {
params.csrfmiddlewaretoken = '{{ csrf_token }}';
return params;
},
placement: 'top',
title: 'New Expense',
success: function(response, newValue) {
if(response.status == 'error') return response.msg; //ms
},
});
});