Ajax- DataTable Not Nowrking - ajax

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

Related

How to auto-populate form fields using vue and laravel

I'm developing a web application where I want to populate some field if I type computer_number I want to populate staff_old_name field that will select from staffs table.
This is what I've tried:
Template
<div>
<table class="table table-bordered table-hover">
<thead>
<tr>
<th>Computer Number</th>
<th>Old Name</th>
<th>New Name</th>
<th>Remarks</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr v-for="(staff, index) in staffs">
<td>
<span v-if="staff.editmode"><input class="form-control" v-model="staff.computer_number"/></span>
<span v-else>{{staff.computer_number}}</span>
</td>
<td>
<span v-if="staff.editmode"><input class="form-control" v-model="staff.old_name"/></span>
<span v-else>{{staff.old_name}}</span>
</td>
<td>
<span v-if="staff.editmode"><input class="form-control" v-model="staff.new_name"/></span>
<span v-else>{{staff.new_name}}</span>
</td>
<td>
<span v-if="staff.editmode"><input class="form-control" v-model="staff.remarks"/></span>
<span v-else>{{staff.remarks}}</span>
</td>
<td>
<span v-if="!staff.editmode"><button class="btn btn-info" type="button" #click="edit(staff)">Edit</button></span>
<span v-else><button class="btn btn-success" type="button" #click="save(staff)">Save</button></span>
<span><button type="button" class="btn btn-danger" #click="remove(index)"><i class="fa fa-trash"></i></button></span>
</td>
</tr>
</tbody>
</table>
<div class="box-footer">
<button class="btn btn-info" type="button" #click="cloneLast">Add Row</button>
</div>
</div>
Script
export default {
data() {
return {
staffs: [],
data_results: []
}
},
computed:{
autoComplete(){
this.data_results = [];
if(this.computer_number.length > 2){
axios.get('/api/staffs/autocomplete',{params: {computer_number: this.computer_number}}).then(response => {
console.log(response);
this.data_results = response.data;
});
}
}
},
methods: {
edit :function(obj){
this.$set(obj, 'editmode', true);
},
save : function(obj){
this.$set(obj, 'editmode', false);
},
remove: function(obj){
this.staffs.splice(obj,1);
},
cloneLast:function(obj){
//var lastObj = this.staffs[this.staffs.length-1];
//lastObj = JSON.parse(JSON.stringify(lastObj));
obj.editmode = true;
this.staffs.push(obj);
},
},
created() {
axios.get('/staff-names')
.then(response => this.staffs = response.data);
},
}
when I type the computer number I want the staff_old_name field populated base on staff name which is stored in staffs table.

Why is The Entire Body of the Web page loaded to the table instead of the data when retrieving data from the database using ajax in Larvel

I have this table showing all the encashment records, it works fine but when I try to get the rows from the database within a specific range of dates and display it to the same table, the whole body of the webpage is being loaded to the table instead of the rows from the database.
Please see image below:
this is my function from the tableController.php
function encashmentRecord_DateRange(Request $request){
if($request->ajax())
{
$start = $request->get('startDate');
$end = $request->get('endDate');
$data = DB::table('encashment_requests')->whereBetween('date',[$start,$end])->get();
return view('incashment',compact('data'));
}
}
the script in my encashment.blade.php
$(document).ready(function(){
$('#dataTable').DataTable();
$('#start_date').datepicker({
format:'yyyy-mm-dd',
autoclose:true
}).val();
$('#end_date').datepicker({
format:'yyyy-mm-dd',
autoclose:true
}).val();
var range = document.getElementById('btnrange');
range.addEventListener('click',function(){
var start_date = $('#start_date').val();
var end_date =$('#end_date').val();
alert(end_date);
$('#dataTable').DataTable().destroy();
listDateRange(start_date,end_date);
},false);
function listDateRange(startDate,endDate){
$.ajax({
method: 'GET',
url : "{{ route('encashmentRecord.action') }}",
data: {startDate:startDate, endDate:endDate},
success:function(data)
{
alert(data);
$('#dataTable').html(data);
}
})
}
});
If you only need the data, you shouldn't be returning view() from your controller.
Try replacing it with this: return response()->json($data, 200);
I may have found the solution to my problem, though it may look lengthy. But it worked.
I made another view, encashmentRecord.blade, containing only the table, so in the controller, instead of returning the data in the incashment.blade, I returned the data to the new view, encashentRecord.blade and I use "#include('encashmentRecord')" in my incashment.blade to display the table.
encashmentRecord.blade.php
<div class="card-body">
<table id="dataTable" class="table table-striped table-bordered">
<thead>
<tr>
<th>Name</th>
<th>Account ID</th>
<th class="sort">Date</th>
<th>Desired Ammount</th>
<th>Destination</th>
<th>Status</th>
</tr>
</thead>
<tbody>
#if(isset($data))
#foreach($data as $row)
<tr>
<td>{{ $row->account_name}}</td>
<td>{{ $row->account_id}}</td>
<td>{{ $row->created_at}}</td>
<td>Php {{ $row->requested_ammount}}</td>
<td>{{ $row->destination}}</td>
<td>{{ $row->status}}</td>
</tr>
#endforeach
#else
<tr>
No Data
</tr>
#endif
</tbody>
</table>
and this is incashment.blade.php
<div class="row">
<div class="col-xl-3 ">
<input type="text" name="query" id="start_date" class="form-control input_daterange">
</div>
<div class="col-xl-3 ">
<input type="text" name="query" id="end_date" class="form-control">
</div>
<div class="col-xl-3 ">
<button class="btn" id="btnrange">Go</button>
</div>
</div>
<div class="card" style="margin-bottom: 0px">
<div class="card-header">
Encashment Record
</div>
<div id="table_data">
#include('tables.encashmentRecord')
</div>
</div>
I just change the view in my return on the controller
return view('tables.encashmentRecord',compact('data'));

ajax reply working but when it load second times

I am updating my cart quantity using ajax. After successfully updating of the cart, when I load the cart and body of the current page the toggle menu of the my cart button does not work the first time. But when I update second time after loading the cart and body the toggle menu works.
My current code:
'remove': function(product_id, flag) {
// alert(product_id);
// alert(flag);
$.ajax({
url: 'includes/addToCart.php',
type: 'post',
data: 'product_id=' + product_id + '&flag='+flag,
dataType: 'json',
beforeSend: function() {
$('#cart > button').button('loading');
},
complete: function() {
$('#cart > button').button('reset');
},
success: function(json) {
// Need to set timeout otherwise it wont update the total
setTimeout(function () {
$('#cart > button').html('<span class="lg">My Cart</span><span><i class="fa fa-shopping-basket"></i> ('+json['total']+') items</span>');
}, 100);
setTimeout(function () {
// if(json['key'] == "blank")
$('#cart > ul').load('includes/loadcart.php');
}, 100);
setTimeout(function () {
$('body').load('cart.php');
}, 100);
},
});
In the console I am getting this error when it executes:
Synchronous XMLHttpRequest on the main thread is deprecated because of
its detrimental effects to the end user’s experience.
I have used the async: true, and async: false
same problem persists
here is my html code where the value displayed
<div class="btn-group btn-block" id="cart">
<button class="btn btn-viewcart dropdown-toggle" data-loading-text="Loading..." data-toggle="dropdown" type="button" aria-expanded="false" id="cart_total"><span class="lg">My Cart</span><span><i class="fa fa-shopping-basket"></i> (<?=$_SESSION['totalitem']?>) items</span></button>
<ul class="dropdown-menu pull-right" ><li>
<table id="cart_item" class="table table-striped">
<tbody>
<?php
if(empty($_SESSION['cart'])){
?>
<tr>
<td align="center" style="font-weight: bold; font-size: 14px;" colspan="5">Your Cart Is empty</td>
</tr>
<?php
}
else{
$subtotal = 0;
foreach($_SESSION['cart'] as $key=>$value){
$subtotal = $subtotal + ($_SESSION['cart'][$key]['price']*$_SESSION['cart'][$key]['qty']);
?>
<tr>
<td class="text-center"> <img class="img-thumbnail" title="iPhone" alt="iPhone" src="../photo/<?=$_SESSION['cart'][$key]['img']?>" width="57px" height="57px">
</td>
<td class="text-left"><?=$_SESSION['cart'][$key]['name']?>
</td>
<td class="text-right">x <?=$_SESSION['cart'][$key]['qty']?></td>
<td class="text-right">$<?=$_SESSION['cart'][$key]['price']*$_SESSION['cart'][$key]['qty']?></td>
<td class="text-center"><button class="btn btn-danger btn-xs" title="Remove" onclick="cart.remove('<?=$_SESSION['cart'][$key]['id']?>','delete');" type="button"><i class="fa fa-times"></i></button></td>
</tr>
<?php
}
}
$vat= $subtotal * (20/100);
$total = $subtotal + $vat;
?>
</tbody></table>
</li><li>
<?php
if(!empty($_SESSION['cart']))
{
?>
<div>
<table class="table table-bordered">
<tbody><tr>
<td class="text-right"><strong>Sub-Total</strong></td>
<td class="text-right">$<?=$subtotal?></td>
</tr>
<tr>
<td class="text-right"><strong>Eco Tax (-2.00)</strong></td>
<td class="text-right">$2.00</td>
</tr>
<tr>
<td class="text-right"><strong>VAT (20%)</strong></td>
<td class="text-right">$<?=$vat?></td>
</tr>
<tr>
<td class="text-right"><strong>Total</strong></td>
<td class="text-right">$<?=$total?></td>
</tr>
</tbody></table>
<p class="text-right"><strong><i class="fa fa-shopping-cart"></i> View Cart</strong> <strong><i class="fa fa-share"></i> Checkout</strong></p>
</div>
<?php
}
?>
</li></ul>
</div>

knockoutjs $parent undefined

I have a problem with KnockoutJS, where the $parent binding context is undefined.
Code
<div class="row">
<div class="col-md-4">
<div class="panel panel-info">
<div class="panel-heading">
<h2 class="panel-title">Products Data</h2>
</div>
<div class="panel-body">
<table class="table table-striped table-bordered table-condensed" data-bind="with: ProductsViewModel">
<thead>
<tr>
<th>ProductID</th>
<th>Product Name</th>
<th>Units In Stock</th>
<th>Action</th>
</tr>
</thead>
<tbody data-bind="foreach: products">
<tr>
<td data-bind="text: $data.ProductID"></td>
<td data-bind="text: $data.ProductName"></td>
<td data-bind="text: $data.UnitsInStock"></td>
<td><button class="btn btn-danger btn-xs" data-bind="click: $parent.RemoveProduct">[x] delete</button></td>
</tr>
</tbody>
</table>
<button class="btn btn-large" data-bind="click: GetProducts()">Load Data</button>
</div>
</div>
</div>
</div>
and:
/// <reference path="../Scripts/knockout-3.4.0.js" />
/// <reference path="../Scripts/jquery-1.10.2.js" />
function ProductsViewModel() {
var self = this;
self.products = ko.observableArray([]);
self.RemoveProduct = function () {
bootbox.alert({ message: 'Pressed !!', size: 'small' });
}
self.GetProducts = function () {
self.products.removeAll();
$.getJSON('/api/products', function (data) {
$.each(data, function (key, value) {
self.products(data);
});
});
}
}
$(document).ready(function () {
ko.applyBindings(ProductsViewModel);
});
All the binding work correctly in the table, except the click event binding on the button, where the $parent is undefined.
If I remove the button control all the data binds correctly in the table element.
Any ideas how to fix this ?? It's all standard Knockout code to my knowledge.
Thanks in advance.
bax2097
I've fixed this by removing the $parent altogether. All working now.
Problems
In your Html you bind your table into a with: ProductsViewModel. Which is not needed.
In your Load data button you did not pass the actual function, instead you execute it right away, so just remove ().
See this JsFiddle for demo

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