I want to delete data without refreshing whole page using ajax - laravel

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

Related

Ajax/laravel delete methode work only when i click twice

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.

How can I delete using ajax in laravel?

BLADE FILE
<td><button class="deleteuser" data-id="{{ $user->id }}" data-token="{{ csrf_token() }}" >DELETE</button>
</td>
AJAX
$(document).ready( function () {
$(".deleteuser").click(function(){
var id = $(this).data("id");
var token = $(this).data("token");
$.ajax(
{
url: "user/delete/"+id,
type: 'DELETE',
dataType: "JSON",
data: {
"id": id,
"_method": 'DELETE',
"_token": token,
},
success: function ()
{
console.log("it Work");
}
});
console.log("It failed");
});
});
CONTROLLER
public function destroyuser($id){
$this->authorize('Admin');
User::find($id)->delete($id);
return response()->json([
'success' => 'Record has been deleted successfully!'
]);
return view('viewuser');
}
If I click on delete button, there is no response. Any suggestion or correction will be appreciated. Thanks in advance
I don't know if the JS is in a different file but to check if the "$( document ).ready()" is working add a console.log() call at the beginning.
$(document).ready( function () {console.log("document is ready")
$(".deleteuser").click(function(){
Refresh the page and check if "document is ready" is logged to the console.
If it isn't then the javascript is not loading
Check if the route is properly defined
You can replace your url as this and check:
var id = data.id;
var url = "{{route('your_route',":id") }}";
url = url.replace(':id', id);
pass url in your ajax url param
Or make above changes:
BLADE FILE
<td>
<button style="background-color: red;" onclick="clickOffConfirmed" title="Delete" class="btn btn-sm btn-clean btn-icon btn-icon-md delete"><i class="la la-trash" style="color: white;"></i></button>
</td>
SCRIPT
<script>
$(document).ready(function() {
$(document).on('click', '.delete', function ()
{
var obj = $(this);
var id=$(this).closest('td').find(".delete_id").val();
var result = confirm("Are you sure want to delete?");
if(result)
{
$.ajax(
{
type: "POST",
url: "{{route('delete_method')}}",
data: {
'_token': $('input[name="_token"]').val(),
'id': id
},
cache: false,
success: function (data)
{
if (data.status === 'success')
{
window.location = "{{route('redirect_route')}}";
toastr["success"]("Deleted Successfully", "Success");
}
else if (data.status === 'error')
{
location.reload();
toastr["error"]("Something went wrong", "Opps");
}
}
});
}
});
});
</script>
Controller
public function delete_method(Request $request)
{
$del = ModelName::findOrFail($request->id)->delete();
if($del)
{
return response()->json(['status' => 'success']);
}
else{
return response()->json(['status' => 'error']);
}
}
Route
Route::post('/test/delete','TestController#delete_method')->name('delete_method');
In your ajax codes, change this:
url: "user/delete/"+id,
To:
url: "{{ url('user/delete') }}/" + id
If your ajax codes are inside of your blade file also you can use this way:
url: "{{ route('YOUR_ROUTE_NAME', $user->id) }}/"
You incorrectly define delete function!
change
User::find($id)->delete($id);
To
User::find($id)->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>

Jquery validation is working but the ajax is not submitted

I'm trying to validate fields inside the form and then fire a function to submit the form using Ajax, the validation is working very well, but the ajax is not working at all
can you please help me figure the solution out
$(function() {
$.validator.addMethod("urlRegex", function(value, element) {
return this.optional(element) ||regex here .test(value);
}, "this should be url.");
$("#songvalid").validate({
rules:
{
song:
{
required: true,
urlRegex: true
}
},
messages:
{
song:
{
urlRegex:"من فضلك أدخل حروف وأرقام فقط"
}
},
submitHandler: function(form){
$("#error").fadeOut();
$("#song-btn").html('<img src="btn-ajax-loader.gif" /> انتظر لحظات ...', );
$.ajax({
url: 'song_process.php',
type: this.method,
data: $(this).serialize(),
success: function(responsd) {
if(responsd=="song"){
$("#song-btn").html(' تم الإرسال');
}
else{
$("#error").fadeIn(1000, function(){
$("#error").html('<div class="alert alert-danger"> <span class="glyphicon glyphicon-info-sign"></span> '+responsd+' !%</div>');
});
}
}
});
return false;
}
});
});
I found the answer!
I changed this:
type: this.method,
data: $(this).serialize(),
to this:
type: 'POST',
data: $("#formName").serialize(),

Opencart cart.add() with option

I'm looking for solution in opencart.
Need to rebuild cart.add function for adding product with option value.
By default:
'add': function(product_id, quantity) {
$.ajax({
url: 'index.php?route=checkout/cart/add',
type: 'post',
data: 'product_id=' + product_id + '&quantity=' + (typeof(quantity) != 'undefined' ? quantity : 1),
dataType: 'json',
beforeSend: function() {
$('#cart > button').button('loading');
},
success: function(json) {
$('.alert, .text-danger').remove();
$('#cart > button').button('reset');
if (json['redirect']) {
location = json['redirect'];
}
if (json['success']) {
$('#content').parent().before('<div class="alert alert-success"><i class="fa fa-check-circle"></i> ' + json['success'] + '<button type="button" class="close" data-dismiss="alert">×</button></div>');
$('#cart-total').html(json['total']);
$('html, body').animate({ scrollTop: 0 }, 'slow');
$('#cart > ul').load('index.php?route=common/cart/info ul li');
}
}
});
checkout/cart/add php side for option:
if (isset($this->request->post['option'])) {
$option = array_filter($this->request->post['option']);
} else {
$option = array();
}
Any solutions?
You can do this in the following way. Create a simple Javascript object.
var productData = {'product_id' : PRODUCT_IDS.CARD, 'quantity': 1,'option':{'229':"Some option value"}};
And send the request as follows. Converting the object to post params using the param function.
$.ajax({
url: 'index.php?route=checkout/cart/add',
type: 'post',
data: $.param(productData),
dataType: 'json',
beforeSend: function () {
},
complete: function () {
},
success: function (json) {
},
error: function (xhr, ajaxOptions, thrownError) {
}
});
Also there are some other ways to do this, you can see possible payload formats in the /controller/checkout/cart.php file.

Resources