Deleting record using laravel and vue js - laravel

I'm stuck in making a delete method using vue js and laravel. I tried to add a value to the href attribute using laravel resource and pass an id as a second parameter but when I click on it and display the id on console it shows the same id to all data which is incorrect.
Sample blade:
<a id="deleteRecord" data-id="{{$project->id}}" #click.prevent="deleteRecord" class="btn btn-circle btn-icon-only btn-danger" href="{{ route('projects.store', $project->id) }}">
<i class="icon-trash"></i>
</a>
Vue method:
deleteRecord: function(id) {
var dataId = $('#deleteRecord').attr('href')
console.log(dataId);
}

Inside of your method deleteRecord:
this.$http.delete(url)
.success(function(response) {
console.log(response)
})
.error(function(errors) {
console.log(error)
});
Or using axios inside of your method
axios.delete(url)
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});

I get it now. I'll just post it here to help others also.
deleteRecord: function(id) {
var url = "projects" + "/" + id;
$.ajax({
url: url,
type: 'DELETE',
data: { "_token": "{{ csrf_token() }}" },
success: function(response) {
//do some success stuff here..
}
});
}

Related

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();

how send id in ajax for laravel

i want to run my ajax after click on one of the options in select tag. and send id of option to ajax url.
please help me . these are my codes.
#foreach($emails as $mail)
<option id="{{$mail->id}}">{{$mail->email}}</option>
#endforeach
</select>
my ajax
$(document).ready(function () {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('.select option').on('click',function () {
var id=$('.select option:selected').attr("id");
$.ajax({
url:'/mailactive',
type:'get',
dataType:'json',
data:{id:id}
})
})
})
try to use this:
give to your select an id, for example id_select
use #id_select > option:selected in your jQuery selector instead of .select option:selected
then tell me if you still can't get the id
In Your Laravel Blade
<select id="email">
#foreach($emails as $mail)
<option id="{{ $mail->id }}"> {{ $mail->email }} </option>
#endforeach
</select>
If your Route is POST method
$(document).ready(function () {
var id = $('#email').children(":selected").attr("id");
$.post('{{ url('your_POST_route_url') }}', {
'_token': "{{ csrf_token() }}", id:id,
}, function (data) {
console.log(data); // Print your response into your console
});
});
If your Route is GET method
$(document).ready(function () {
var id = $('#email').children(":selected").attr("id");
$.get('{{ url('your_GET_route_url') }}', {
id:id,
}, function (data) {
console.log(data); // Print your response to your console
});
});
You should have return data from your GET or POST method.

Print automatically on form close

I have a button that prints something and it works well.
I would like to print automatically when the form is closed.
At the moment the form sends an email to my customers with order details (it works very well) but now I would like to print automatically without requiring the user to push a button.
Please help me. I am a beginner here.
Relevant code:
<a
href="#!"
target="_blank"
id="save-and-print"
type="submit"
title="Speichern & Drucken">
<i class="fa fa-print"></i>
</a>
<script type="text/javascript" src="/js/summernote.js?v=0.72"></script>
<script>
$( function() {
$('#save-and-print').on('click', function (e) {
e.preventDefault();
var url = 'myOrders/replacement/' + '{{ $data->id }}';
}
});
$.ajax({
type: "PATCH",
url: '/myOrders/replacement/' + '{{ $data->id }}',
data: $("form").serialize(),
dataType: 'json',
success: function (data) {
window.location.reload();
location.href = '{{ route('print', [$data->id, 'option' => 'advance']) }}';
},
error: function (data) {
$('body').pgNotification({
style: 'flip',
message: 'Error',
position: 'top-right',
type: 'danger',
timeout: 4000
})
},
});
</script>
If you want the same action to take place on the submit event of your form as what happens when your id="save-and-print" button is being pressed, you could do something like this:
function printSomething(event) {
var url = 'myOrders/replacement/' + '{{ $data->id }}';
}
const form = document.getElementById('form');
form.addEventListener('submit', printSomething);

Django csrf_token works in one form but not in other

I have a page with two lists: for tasks (tareas) and sales (ventas). When you click their links each one opens it´s own modal and retrieves the info with AJAX.
One works with no problem (tareas). The other one gives me a csrf_token error.
I thought maybe it was a problenm of using two tokens in the same template, but I´m doing it in other templates with no problem.
And if I completely remove the tareas part, the ventas one still get´s the same error.
Venta form call
<form name="ventas_form" action="#" id="form_venta_{{operacion.comprobante}}" method="POST">
{% csrf_token %}
<input name="id" id="venta_id_submit" type="text" value="{{operacion.comprobante}}" hidden="true"/>
<a style="padding-left: 1rem;" href="" id="{{operacion.comprobante}}" class="show_venta" data-toggle="modal" >{{operacion.comprobante}}</a>
</form>
Tarea form call
<form name="form" action="#" id="form_tarea_{{tarea.id}}" method="POST">
{% csrf_token %}
<input name="id" id="tarea_id_submit" type="text" value="{{tarea.id}}" hidden="true"/>
<a style="padding-left: 1rem;" href="" id="{{tarea.id}}" class="show_tarea" data-toggle="modal" >{{ tarea.titulo }}</a>
</form>
Venta Ajax
<script>
$(function(){
$('.show_venta').on('click', function (e) {
e.preventDefault();
let venta_id = $(this).attr('id');
$.ajax({
url:'/catalog/ventas-detail/',
type:'POST',
data: $('#form_venta_'+venta_id).serialize(),
success:function(response){
console.log(response);
$('.show_venta').trigger("reset");
openModalVentas(response);
},
error:function(){
console.log('something went wrong here');
},
});
});
});
function openModalVentas(venta_data){
$('#fecha').text(venta_data.venta.fecha);
$('#comprobante').text(venta_data.venta.comprobante);
$('#cliente').text(venta_data.venta.cliente);
$('#vendedor').text(venta_data.venta.vendedor);
$('#lista').text(venta_data.venta.lista);
$('#prod_codigo').text(venta_data.venta.prod_codigo);
$('#prod_nombre').text(venta_data.venta.prod_nombre);
$('#uds').text(venta_data.venta.uds);
$('#vu').text(venta_data.venta.vu);
$('#subtotal').text(venta_data.venta.subtotal);
$('#bonif').text(venta_data.venta.bonif);
$('#modal_ventas').modal('show');
};
</script>
Tarea Ajax
<script>
$(function(){
$('.show_tarea').on('click', function (e) {
e.preventDefault();
let tarea_id = $(this).attr('id');
$.ajax({
url:'/catalog/tareas-detail/',
type:'POST',
data: $('#form_tarea_'+tarea_id).serialize(),
success:function(response){
console.log(response);
$('.show_tarea').trigger("reset");
openModal(response);
},
error:function(){
console.log('something went wrong here');
},
});
});
});
function openModal(tarea_data){
$('#creador').text(tarea_data.tarea.creador);
$('#destinatario').text(tarea_data.tarea.destinatario);
$('#titulo').text(tarea_data.tarea.titulo);
$('#tarea').text(tarea_data.tarea.tarea);
$('#resuelto').text(tarea_data.tarea.resuelto);
$('#fecha_creacion').text(tarea_data.tarea.fecha_creacion);
$('#fecha_limite').text(tarea_data.tarea.fecha_limite);
$('#fecha_resuelto').text(tarea_data.tarea.fecha_resuelto);
$('#empresa').text(tarea_data.tarea.empresa);
$('#persona_empresa').text(tarea_data.tarea.persona_empresa);
$('#modal_tareas').modal('show');
};
</script>
Venta view
def VentaDetailView(request):
ID = request.POST.get('id')
ventas_todas = Ventas.objects.filter(pk=ID).get()
venta = {
"fecha": ventas_todas.fecha,
"comprobante": ventas_todas.comprobante,
"cliente": ventas_todas.cliente,
"vendedor": ventas_todas.vendedor.nombre,
"lista": ventas_todas.lista,
"prod_codigo": ventas_todas.prod_codigo,
"prod_nombre": ventas_todas.prod_nombre,
"uds": ventas_todas.uds,
"vu": ventas_todas.vu,
"subtotal": ventas_todas.subtotal,
"bonif": ventas_todas.bonif,
}
return JsonResponse({'venta': venta})
Tarea view
def TareaDetailView(request):
ID = request.POST.get('id')
tarea_select = Tareas.objects.filter(pk=ID).get()
tarea = {
"creador": tarea_select.creador.username,
"destinatario": tarea_select.destinatario.username,
"titulo": tarea_select.titulo,
"tarea": tarea_select.tarea,
"resuelto": tarea_select.resuelto,
"fecha_creacion": tarea_select.fecha_creacion,
"fecha_limite": tarea_select.fecha_limite,
"fecha_resuelto": tarea_select.fecha_resuelto,
"empresa": tarea_select.empresa.Nombre,
"persona_empresa": tarea_select.persona_empresa.nombre,
}
return JsonResponse({'tarea': tarea})
No idea why the tareas part works ... but for sure I would add 'X-CSRFToken' header to both ajax calls:
$.ajax({
url:'/catalog/ventas-detail/',
type:'POST',
data: $('#form_venta_'+venta_id).serialize(),
headers: {'X-CSRFToken': getCookie('csrftoken')}
...
});
where:
function getCookie(name) {
var value = '; ' + document.cookie,
parts = value.split('; ' + name + '=');
if (parts.length == 2) return parts.pop().split(';').shift();
}
You can add CSRF token to header like that too :
$.ajaxSetup({
beforeSend: function(xhr, settings) {
xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
}
});
Then you didn't need to manually add your CSRF token to all your ajax request.

Delete\Add Row with AJAX (Secure way)

i am new to Laravel and trying to find way to delete or add row with AJAX request.
Let's say i have PostController and i want to delete one of my post.
So in the PostController there will be destroy function :
public function destroy($id)
{
Posts::find($id)->delete();
}
Now, how i can send from a view AJAX Request to Controller and use this destroy method in secure way.
This works for me,
But the question is if this secure ?
AJAX Function
function removeRow(id){
token = $('#rmv').data("token");
console.log(id);
$.ajax(
{
url: "/posts/"+id,
type: 'POST',
data: {
"id": id,
"_method": 'DELETE',
"_token": token,
},
success: function ()
{
console.log("it Work");
$('#post'+id).remove();
}
});
}
VIEW
<a id="rmv" onclick="javascript:removeRow({{$post->id}})" data-token="{{ csrf_token() }}" class="btn btn-primary" >Delete</a>
OK, This works for me.
But the question is if this secure ?
AJAX Function
function removeRow(id){
token = $('#rmv').data("token");
console.log(id);
$.ajax(
{
url: "/posts/"+id,
type: 'POST',
data: {
"id": id,
"_method": 'DELETE',
"_token": token,
},
success: function ()
{
console.log("it Work");
$('#post'+id).remove();
}
});
}
VIEW
<a id="rmv" onclick="javascript:removeRow({{$post->id}})" data-token="{{ csrf_token() }}" class="btn btn-primary" >Delete</a>

Resources