Data not rendering in the table using datatables - ajax

I am implementing datatable. I can see data is coming from database in xhr using developer tools but it is not showing in the table. Please tell me what is the problem with my code.
#section Body{
<div class="row">
<div class="col-md-9">
<div class="block">
<div class="content">
<table cellpadding="0" cellspacing="0" width="100%" class="table" id="myDbTable">
<thead>
<tr>
<th data-hide>ID</th>
<th data-hide >Name</th>
<th data-hide >E-mail</th>
<th data-hide>Phone</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
</div>
</div>
</div>
}
#section Scripts{
<script>
var DataColumnsCount = 4;
//***Start Fatching Data for datatable *** start //
function fetchEmployeeTableList() {
$('#myDbTable').DataTable({
"columns": [
{"data" : "Id"},
{ "data": "Name" },
{ "data": "Email" },
{ "data": "Phone" }
]
}
);
}
$.ajax({
type: 'GET',
url: "#Url.Action("GetEmployees","Employee")",
dataType: 'json',
data: "{}",
dataSrc: 'DataSet',
success: fetchEmployeeTableList});
</script>
}
Please help me in this regard.

Related

Ajax- DataTable Not Nowrking

I'm processing the incoming data with Ajax as follows. But I can't make it compatible with dataTable. I've read the Datatable Ajax documentation. But I was never successful. How do I pull the following data into the dataTable? I want to make these codes compatible for Data Table.
You can see multiple parse operations in my code. Please do not warn about it. Net Core, I can only process the JSON file in this way. The only thing I want from you is to show this data that I have processed successfully in the datatable.
<div class="card" id="view-maincategorylist">
<div class="card-body">
<div class="table-responsive">
<table id="datatablex" class="table table-striped table-bordered" style="width:100%">
<thead>
<tr>
<th class="text-center">Fotoğraf</th>
<th class="text-center">Ana Kategori Adı</th>
<th class="text-center">Seçenekler</th>
<th class="text-center">İşlemler</th>
</tr>
</thead>
<tbody id="table-maincategories">
</tbody>
</table>
</div>
</div>
</div>
<script>
function GetMainCategoryList() {
$.ajax({
url: "/Admin/BusinessCategories/MainCategories/",
contentType: "application/json",
dataType: "json",
type: "Get",
success: function (data) {
var item = jQuery.parseJSON(data);
$("#table-maincategories").empty();
$.each(JSON.parse("[" + item + "]"), (index, value) => {
for (let element of value) {
$("#table-maincategories").append(`<tr class="text-center">
<td><img src="${element.Image}" style="height:80px;" /></td>
<td>${element.Name}</td>
<td>
<div class="form-check">
<a href="/Admin/BusinessCategories/MainShowMenu/${element.Id}" onclick="location.href=this.href;">
<input class="form-check-input" type="checkbox" id="flex_${element.Id}">
</a>
<label class="form-check-label" for="flex_${element.Id}">Menüde Göster</label>
</div>
</td>
<td>
<a onclick="ShowEditMainCategory(${element.Id})" class="btn btn-primary"><i class="bx bx-edit"></i> Düzenle</a>
<a onclick="DeleteMainCategory(${element.Id});" data-name="${element.Name}" id="del_${element.Id}" class="btn btn-danger delete-button"><i class="bx bx-trash"></i> Sil</a>
</td> </tr>`);
var checkbox = document.getElementById('flex_' + element.Id);
if (element.ShowMenu == true) {
checkbox.checked = true;
}
else {
checkbox.checked = false;
}
}
});
$('#datatable').DataTable();
ViewShowHide(1);
},
error: function () {
Swal.fire('Veriler Okunamadı!', '', 'error')
}
})
}
</script>
Problem Images:
image 1
image 2
image 3
JSON Data Output:
https://easyupload.io/1bsb75

put functional buttons for editing in serverside datatable - Laravel

The project is in Laravel. I have to pull a lot of records, so I opted for serverside... but, I can't put functional buttons to edit the records
index.blade
#extends('layouts.app')
#section('content')
<section class="section">
<div class="section-header">
<h3 class="page__heading">Siniestros</h3>
</div>
<nav aria-label="breadcrumb">
<ol class="breadcrumb">
<li class="breadcrumb-item">Dashboard</li>
<li class="breadcrumb-item">Siniestros</li>
<!-- <li class="breadcrumb-item active" aria-current="page">Index</li> -->
</ol>
</nav>
<div class="section-body">
<div class="row">
<div class="col-lg-12">
<div class="card">
<div class="card-body">
#can('crear-siniestro')
<a class="btn btn-primary btn-sm" href="{{ route('siniestros.create') }}">Nuevo</a>
#endcan
<table class="table table-sm m-1 p-1 table-bordered table-hover table-striped tablita" style="width:100%">
<thead style="background-color:hsl(213, 99%, 49%)">
<th style="color:#fff;">Siniestro</th>
<th style="color:#fff;">Fecha IP</th>
<th style="color:#fff;">Nro Corto</th>
<th style="color:#fff;">Dirección</th>
<th style="color:#fff;">Localidad</th>
<th style="color:#fff;">Patente</th>
<th style="color:#fff;">Fecha IP</th>
<th style="color:#fff;">Estado</th>
<th style="color:#fff;">Coordinador</th>
<th style="color:#fff;">Fecha ingreso</th>
<th style="color:#fff;">Fecha gestión</th>
<th style="color:#fff;">Modalidad</th>
<th style="color:#fff;">Cliente</th>
<th style="color:#fff;">Dirección</th>
<th style="color:#fff;">Localidad</th>
<th style="color:#fff;">Inspector</th>
<th style="color:#fff;">Motivo</th>
</thead>
</table>
</div>
</div>
</div>
</div>
</div>
</section>
#endsection
<!-- DataTables JS -->
<script src="{{ asset('assets/js/jquery.min.js') }}"></script>
<script type="text/javascript" src="https://cdn.datatables.net/v/bs4/jszip-2.5.0/dt-1.11.5/b-2.2.2/b-colvis-2.2.2/b-html5-2.2.2/b-print-2.2.2/r-2.2.9/datatables.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.6.0/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/js/all.min.js" integrity="sha512-6PM0qYu5KExuNcKt5bURAoT6KCThUmHRewN3zUFNaoI6Di7XJPTMoT6K0nsagZKk2OB4L7E3q1uQKHNHd4stIQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
#section('javas')
<script>
$(document).ready(function() {
$('.tablita').DataTable({
ajax: 'datatable/users',
processing: true,
serverSide: true,
pageLength: 100,
columns: [
{"data": "siniestro"},
{"data": "fechaip"},
{"data": "nrocorto"},
{"data": "direccion"},
{"data": "localidad"},
{"data": "patente"},
{"data": "fechaip"},
{"data": "estado"},
{"data": "coordinador"},
{"data": "created_at"},
{"data": "updated_at"},
{"data": "modalidad"},
{"data": "cliente"},
{"data": "direccion"},
{"data": "localidad"},
{"data": "inspector"},
{"data": "motivo"},
]
});
});
function editData(id){
$.ajax({
type:"get",
dataType:"json",
url:"/teacher/edit/"+id,
success: function(data){
$('#id').val(data.id);
console.log(data);
}
})
}
</script>
#endsection
SiniestroController
public function registros(){
$registros = Siniestro::all();
return Datatables::of($registros)->toJson();
return $registros;
}
web.php
Route::get('datatable/users', [SiniestroController::class, 'registros']);
In other views I have the button that I will leave next, to edit each record, which takes me to a blade view. I would like to be able to agree with this one if possible:
<a class="btn btn-outline-success btn-lg" href="{{ route('siniestros.edit',$siniestro->id) }}"><i class="fa-solid fa-pen-to-square fa-xl"></i></a>

Not sure how to save prices in one shot in vue

I have a table that lists out all my products and their prices and I have the prices as input
and what I would like to do is, when I click on save then I need to be able to save all those prices that I changed at
one time.
I'm not sure how to go about doing that.
Here is my code
<template>
<div>
<table class="table table-sm table-bordered">
<thead>
<tr>
<th>Name</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<tr v-for="product in products">
<td>{{product.name}}</td>
<td>
<input #change="onChange(product)" v-model="product.prices">
</td>
</tr>
</tbody>
</table>
<div>
<div class="btn btn-success" #click="updatePrices()">
Save Prices
</div>
</div>
</template>
<script>
export default {
props: ['products'],
data() {
return {
product: {
price: null
}
}
},
methods: {
updatePrices(){
console.log(this.products.price);
}
},
mounted(){
}
}
</script>
Your question is about two parts of data passing.
From Vue Component to Vue Parent.
From Vue Client to Server.
And also, you may be confused with component data and props
You can check my answer
//component
Vue.component('price-table', {
props:[
'parentProducts',
],
data: function() {
return {
products:[]
};
},
methods: {
updatePrice(){
console.log('update prices from component to parent');
console.log(this.products);
this.$emit('update-prices', this.products);
}
},
mounted:function(){
console.log('pass products from parent to component');
this.products = this.parentProducts;
}
});
//parent
var vm = new Vue({
el: '#app',
data: () => ({
products:[
{
name:'Apple',
price:'10'
},
{
name:'Banana',
price:'12'
},
{
name:'Coconut',
price:'20'
},
]
}),
methods:{
savePricesToServer(products){
console.log('save prices to server');
console.log(products);
//do ajax here
}
}
});
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/vue#2.6.12/dist/vue.js"></script>
</head>
<body>
<div id="app">
<h2>Price Table</h2>
<price-table
inline-template
:parent-products="products"
v-on:update-prices="savePricesToServer"
>
<div>
<table border='1' width="100%">
<tr>
<th>Product</th>
<th>Price</th>
</tr>
<tr v-for="(product, productIndex) in products" :key="productIndex">
<td>{{ product.name}}</td>
<td>
<input type="number" v-model="product.price">
</td>
</tr>
</table>
<button #click="updatePrice">Update Price</button>
</div>
</price-table>
</div>
</body>
</html>
It is showing how to use custom event to pass data from component back to parent https://v2.vuejs.org/v2/guide/components-custom-events.html

how to reload table when certain row is created or delete?

I am just learning Vuejs with laravel. and my Delete is Working correctly but when it redirect to index page after row is deleted that row is not removed until it is loaded..
And for When Category is added new data is not shown until browser is loaded...
This is my Categories Component `
<form role="form" method="POST" enctype="multipart/form-data" #submit.prevent="createCategory" v-if="adding">
<div class="card-header">
<h3 class="card-title">Create New Category</h3>
</div>
<div class="card-body">
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label>Category Name</label>
<input type="text" class="form-control" id="category_name" v-model="category_name" placeholder="Enter Category Name">
</div>
</div>
</div>
</div>
<div class="card-footer">
<button type="submit" class="btn btn-primary">Submit</button>
<button #click.prevent="cancel" class="btn btn-danger">Cancel</button>
</div>
</form>
<div class="card-body" v-else>
<div class="card-header" >
<h3 class="card-title"><a class="btn btn-block btn-outline-secondary btn-lg" #click.prevent="add()"> Create New Category</a></h3>
</div>
<table id="example2" class="table table-bordered table-hover" >
<head>
<tr>
<th>ID</th>
<th>Category Name</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr v-for="(category,index) in model" :category="category" v-bind:key="category.id">
<td>{{category.id}}</td>
<td>{{category.category_name}}</td>
<td>Edit | <a #click="deleteCategory(category.id,index)" class="btn-outline-
danger">Delete</a></td>
</tr>
</body>
</table>
</div>
</div>
`
<script>
export default {
props:['model'],
data(){
return {
model:[],
section_id: 0,
sections: [],
parent_id: 0,
categories: [],
adding:false,
category_name:'',
}
},
methods:{
add(){
this.adding=true;
},
cancel(){
this.adding=false;
},
createCategory(){
axios.post(`categories `,{
category_name:this.category_name,
}).catch(error => {
console.log('Error')
})
.then(res=>{
this.adding=false;
})
},
deleteCategory(id,index){
if(confirm('Are You Sure ?')){
axios.delete('categories/'+id)
.then(resp => {
this.model.splice(index, 1);
})
.catch(error => {
console.log(error);
})
}
}
},
}
</script>
<table id="example2" v-if="flag" class="table table-bordered table-hover" >
<head>
<tr>
<th>ID</th>
<th>Category Name</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr v-for="(category,index) in model" :category="category" v-bind:key="category.id">
<td>{{category.id}}</td>
<td>{{category.category_name}}</td>
<td>Edit | <a #click="deleteCategory(category.id,index)" class="btn-outline-
danger">Delete</a></td>
</tr>
</body>
</table>
in data add flag:false,
data(){
return {
model:[],
section_id: 0,
sections: [],
parent_id: 0,
categories: [],
adding:false,
category_name:'',
flag:false
}
},
in your functions make your flag false in case of success response
deleteCategory(id,index){
this.flag=false;
if(confirm('Are You Sure ?')){
axios.delete('categories/'+id)
.then(resp => {
this.model.splice(index, 1);
this.flag=true;
})
.catch(error => {
console.log(error);
this.flag=false;
})
}
}
I think that you are overcomplicate this. Just create an API that retrieve all the categories. So after each addition or deletion, then just call that API.

Updating the emberJS view after an ajax request

So I am trying to send a custom action to my server with ajax and update the emberJS model in the callback. My controller code looks like this:
PlatformUI.CampaignItemController = Ember.ObjectController.extend({
actions: {
deleteCampaign: function(){
var campaign = this.get('model');
campaign.deleteRecord();
campaign.save();
},
startCampaign: function(){
var campaign = this.get('model');
$.ajax({
url: '/campaigns/' + campaign.get('id') + '/campaign_start.json',
type: 'GET',
success: function(data, textStatus, xhr) {
campaign.set('status', data.started);
//campaign.save();
},
error: function(xhr, textStatus, errorThrown) {
console.log(xhr);
alert('start campaign failed');
}
});
}
}
});
My model looks like this:
PlatformUI.Campaign = DS.Model.extend({
name: DS.attr('string'),
status: DS.attr('string'),
updated_at: DS.attr('date'),
user_id: DS.attr('number'),
created_at: DS.attr('date'),
started: function(){
return this.get('status') == 'true';
}.property()
});
Edit: adding template:
<div class="page-header">
<h1> Campaigns
List
<a role="button" class="btn btn-primary" href="/campaigns/new">Create New</a>
</h1>
</div>
<div class="table-responsive">
<table class="table table-striped table-bordered table-hover">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Status</th>
<th>Last updated</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{{#each campaign in model itemController="CampaignItem"}}
<tr>
<td>{{campaign.id}}</td>
<td>{{campaign.name}}</td>
<td>{{ternary campaign.status "Started" "Stopped"}}</td>
<td>{{campaign.updated_at}}</td>
<td>
<a class="btn btn-primary" {{bind-attr href=campaign.edit_url}}>Edit</a>
<a class="btn btn-danger" {{action "deleteCampaign"}}>Delete</a>
{{#if campaign.started}}
<a class="btn btn-primary" {{bind-attr href=campaign.stop_url}}>Stop</a>
{{else}}
<a class="btn btn-primary" {{action "startCampaign"}}>Start</a>
{{/if}}
</td>
</tr>
{{/each}}
</tbody>
</table>
</div>
The problem is that it is not refreshing the view when I perform that action. I am new to emberJS so I don't really know if the model was really updated either.
You need to let started know that it is calculated off of status so it knows to recaclulate when status is changed.
You can do this by including the status in the list of dependencies.
started: function(){
return this.get('status') == 'true';
}.property('status')

Resources