ajax is not accessing to my button inside datatable - ajax

I want to access to my button inside datatable which is inside of my modal, but when I want to access it wont load any alert , ajax url or whatever thing even If I change id or class of "a" tag. how can I fix it? this ajax I know it wont load and error in console, but it also show it..
ajax
$(function(event) {
URL_GET_VIEW_SEARCH_PRODUCT = BASE_URL + 'sale/sales/getViewSearch';
URL_GET_DATATABLE = BASE_URL + 'sale/sales/datatable';
URL_SEARCH_PRODUCT = BASE_URL + 'sale/sales/search_product';
$('#btn-search').click(function (e) {
BootstrapDialog.show({
title: 'Search Product',
message: function(dialog) {
var $message = $('<div></div>');
var pageToLoad = dialog.getData('pageToLoad');
$message.load(pageToLoad);
return $message;
},
data: {
pageToLoad: URL_GET_VIEW_SEARCH_PRODUCT
},
onshown: function(dialog){
$('#example').DataTable({
lengthChange: false,
responsive: true,
ajax: {
url: URL_GET_DATATABLE,
type: 'POST',
},
columnDefs: [{
targets: 4,
data: null,
defaultContent: "<a href='#'><span class='glyphicon glyphicon-plus'></span></a>"
}],
});
}
});
});
$('#search').typeahead({
source: function (query,process) {
$.ajax({
url: URL_SEARCH_PRODUCT,
type: 'POST',
data: {query: query},
dataType: 'json',
async: true,
success: function (data) {
console.log(data);
process(data);
}
});
}
});
$('#example tbody').on('click', 'a', function(event) {
$.ajax({
url: '/path/to/file',
type: 'default GET (Other values: POST)',
dataType: 'default: Intelligent Guess (Other values: xml, json, script, or html)',
data: {param1: 'value1'},
})
});
});
table view
<table id="example" class="table table-bordered table-striped" cellspacing="0" width="100%">
<thead>
<tr>
<th>Code</th>
<th>Description</th>
<th>Stock</th>
<th>Price</th>
<th></th>
</tr>
</thead>
</table>

Related

Button click not working in Vue in datatable ajax render

I am a newbie in Vuejs.
I have a users table which is showing data using Server-side processing in Datatable. I am trying to add a click event which will call a vue function. But the click function is not working at all. I tried use these methods. But none of them are working.
v-on:click="functionName"
v-on:click="$emit('functionName')"
#click="functionName"
HTML part
<table class="table table-bordered data-table dataTable-load">
<thead class="thead-light">
<tr>
<th style="width: 80px;">No</th>
<th>Name</th>
<th>Email</th>
<th>Phone</th>
<th>Type</th>
<th>Created</th>
<th>Last Updated</th>
<th width="280px">Action</th>
</tr>
</thead>
<tbody></tbody>
</table>
<div>
<span v-html='data'></span>
</div>
SCRIPT part
var dt = $('.dataTable-load').DataTable({
processing: true,
serverSide: true,
ajax: {
url: "{{ url('user/getdata') }}",
type: "post",
data: {"_token": "{{ csrf_token() }}"}
},
columns: [
{name: 'id', data: 'id', },
{name: 'name', data: 'name'},
{name: 'email', data: 'email'},
{name: 'phone', data: 'phone'},
{name: 'usertype', data: 'usertype',
"render": function (data, type, row) {
if (row.usertype == 'M') {
return 'Manager';
} else {
return 'Staff';
}
}
},
{name: 'created_at', data: 'created_at'},
{name: 'updated_at', data: 'updated_at'},
{
title: 'msg',
"render": function (data, type, row) {
return '<button v-on:click="showModal" #click="showModal">the button</button>';
}
}
]
});
dt.on('order.dt search.dt', function () {
dt.column(0, {search: 'applied', order: 'applied'}).nodes().each(function (cell, i) {
cell.innerHTML = i + 1;
});
}).draw();
App.js
const app = new Vue({
el: '#app',
data: {
data: '',
},
methods: {
showModal() {
this.data = 'Now click on me <a href=\'#\' #click.prevent=\'alert("yo")\'> here </a>';
},
},
});
Please let me know how to do it correctly. Thanking you in advance.

Laravel Ajax delete record with button

I do not understand why it does not work:
Route
Route::delete('/dashboard/booking/deletebooking/{id}','ResourceController#deletebooking')->name('works.deletebooking');
ResourceController
public function deletebooking($id){
$booking = Booking::where('id','=',$id)->get();
$booking->delete();
return response()->json(['success' => true],200);
}
Table
<tr id="{{$booking->id}}">
<td class="roomId">{{$booking->room_id}}</td>
<td class="roomName">{{$booking->name}}</td>
<td class="roomLocation">{{$booking->sede}}</td>
<td class="start">{{$booking->start_date}}</td>
<td class="end">{{$booking->end_date}}</td>
<td>
<input type="hidden" name="_method" value="delete" />
<button class="btn btn-danger btn-xs" id="destroy" data-id="{{$booking->id}}" data-token="{{ csrf_token() }}">
<span class="glyphicon glyphicon-trash"></span>
</button>
</td>
</tr>
Request Ajax
$(".btn").click(function(){
var id = $(this).data('id');
// var $tr = $(this).closest('tr');
$.ajax({
url: "/dashboard/booking/deletebooking/"+id,
dataType: "JSON",
type: 'POST',
data: {
'_token': $('meta[name=csrf-token]').attr("content"),
'_method': 'DELETE',
"id": id
},
success: function ()
{
console.log("it Work");
}
});
console.log("It failed");
});
I have this error:
Request URL: http://pickbooking.local/dashboard/booking/deletebooking/1
Request Method: POST
Status Code: 500 Internal Server Error
Remote Address: 192.168.10.10:80
The issue is in the method used for the ajax call post
// var $tr = $(this).closest('tr');
$.ajax(
{
url: "/dashboard/booking/deletebooking/"+id,
dataType: "JSON",
type: 'POST',
data: {
'_token': $('meta[name=csrf-token]').attr("content"),
'_method': 'DELETE',
"id": id
},
success: function ()
{
console.log("it Work");
}
});
the data will be sent in the body of the request, and in a DELETE request, there is no body. so laravel wont see the _method, or the _token. Either you send them in a GET request and let the _method do it's job (it will be in the url, not in the body), Or use the DELETE method in the ajax call
// var $tr = $(this).closest('tr');
$.ajax(
{
url: "/dashboard/booking/deletebooking/"+id,
dataType: "JSON",
type: 'DELETE',
data: {
'_token': $('meta[name=csrf-token]').attr("content"),
},
success: function ()
{
console.log("it Work");
}
});
Because I think you have an error something like
Method Illuminate\Database\Eloquent\Collection::delete does not exist.
Instead try something like this
$booking = Booking::where('id', '=', $id)->first();
$booking->delete();
so that $booking can have method delete()

laravel 419 status code (unknown status)

I do an ajax call but I keep getting this error:
419 (unknown status)
i include in meta tag:
<meta name="csrf-token" content="{{ csrf_token() }}">
my table (without form):
<table class="table" id="dataTables">
<thead>
<tr>
<td>Full nametd>
<td class="text-center">Lớp</td>
<td class="text-center"><input type="checkbox" id="select_all"></td>
</tr>
</thead>
</table>
i use DataTables library load all data from Controller:
var table = $('#dataTables').DataTable({
"pagingType": "full_numbers",
"processing": true,
"serverSide": true,
"lengthMenu": [[5, 10, -1], [5, 10, "All"]],
"iDisplayLength": 5,
"ordering": false,
"ajax": '{!! url(Request::segment(1).'/lists?class_id='.Input::get('class_id')) !!}',
'createdRow': function (row, data, dataIndex) {
$(row).attr('id', data.id);
},
"columns": [
...
{
"data": "id", "sClass": "text-center",
"fnCreatedCell": function (nTd, sData, oData, iRow, iCol) {
$(nTd).html("<input type='checkbox' name='check[]' value='" + oData.id + "'>");
}
},
],
"language": {
"url": "{{url('public/extension/datatables/vietnamese.json')}}"
}
});
My Ajax:
$('#save').click(function () {
$.ajax({
type: 'POST',
url: "{{url('class/store')}}",
cache: false,
data: {"check": sThisVal }, //sThisVal get all input checkbox checked
success: function (r) {
$('#msg').html(r);
},
error: function (jqXHR, text, errorThrown) {
$('#msg').html(jqXHR + " " + text + " " + errorThrown);
}
});
});
My route:
Route::post('class/lists', 'ClassController#lists');
My controller method
public function store(Request $request){
var_dump($request->all());exit;
}
Result after click submit is null ???
In addition to putting the crsf-token value in the header meta you need to pass it through in your AJAX requests with something like:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
This is from: https://laravel.com/docs/5.6/csrf#csrf-x-csrf-token
I added the crsf-token in the data section on my ajax and it worked like a charm for me.
$('#save').click(function () {
$.ajax({
type: 'POST',
url: "{{url('class/store')}}",
cache: false,
data: {
"check": sThisVal,
"_token": "{{ csrf_token() }}",
}, //sThisVal get all input checkbox checked
success: function (r) {
$('#msg').html(r);
},
error: function (jqXHR, text, errorThrown) {
$('#msg').html(jqXHR + " " + text + " " + errorThrown);
}
});
});
Hope this Helps
sometimes all u need to do to fix this is to make the method post caps like the below

Jquery Datatable: Data won't load using ajax

This is my first time using Jquery datatable.
I don't know what's wrong with my code, but the data won't load into the datatable.
Here's the script:
$(document).ready(function () {
$.ajax({
type: "POST",
url: "TestDPRDetail.aspx/GetdtbScenario",
contentType: "application/json;charset=utf-8",
datatype: "json",
success: function (data) {
$('#grvScenario').dataTable({
data: data,
columns:
[
{ "data": "SCENARIO_ID" }
]
});
},
});
});
The url: TestDPRDetail.aspx/GetdtbScenario returns a datatable json serialized object
<System.Web.Script.Services.ScriptMethod()> _
<WebMethod()> _
Public Shared Function GetdtbScenario() As Object
Dim dtbScenarioTemp As New DataTable
Dim strDPR_ID As String
Dim clsScenarioBusiness As New ScenarioBusiness
Dim json As Newtonsoft.Json.JsonConvert
strDPR_ID = "DPR-201807-00001"
dtbScenarioTemp = clsScenarioBusiness.GetdtbScenario(strDPR_ID) 'getting data from sql
Return json.SerializeObject(dtbScenarioTemp)
End Function
I checked with a normal method (using array object) to load the datatable, it works fine:
var dataTemp = [{ "SCENARIO_ID": "SCN-201807-00008", "SCENARIO #": "B", "SCENARIO NAME": "Test Inquiry", "CONDITION": "Negative" }]
$('#grvScenario').dataTable({
data: dataTemp,
columns: [
{"data":"SCENARIO_ID"}
]
});
Here's the HTML:
<body>
<form id="form1" runat="server">
<div>
<table id="grvScenario">
<thead>
<tr>
<th>Scenario ID</th>
</tr>
</thead>
</table>
</div>
</form>
</body>
Is there something i missed from the ajax or datatable?
Try to initialize datatables first:
$(document).ready(function () {
$('#grvScenario').dataTable({
ajax: "TestDPRDetail.aspx/GetdtbScenario",
columns: [
{ "data": "SCENARIO_ID" }
]
})
});
After some trial and error, i've got my answer
It seems that TestDPRDetail.aspx/GetdtbScenario was returning a different json object after ajax call.
The return variable (data) needs to be parsed again in javascript. So it will look like this:
$.ajax({
type: "POST",
url: "TestDPRDetail.aspx/GetdtbScenario",
contentType: "application/json;charset=utf-8",
datatype: "json",
success: function (data) {
$('#grvScenario').dataTable({
data: JSON.parse(data.d),
columns:
[
{ "data": "SCENARIO_ID" }
]
});
},
});
Hope it will help anyone having the same issue

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.

Resources