knockoutjs refresh or update - ajax

I trying create a ajax-refresh shopping-cart panel. My shopping-cart is listed but I can't refresh it in $.getJSON callback function. my view and code is;
<div class="panel panel-info">
<div class="panel-heading">
<i class="fa fa-list-ul"></i> Sipariş Listeniz
</div>
<div class="panel-body">
<div id="cart" data-bind="foreach: Currencies">
<div class="">
<span data-bind="text: Currency"></span>
<table class=" table table-striped" data-bind="foreach: Items">
<tr>
<td data-bind="text: Code"></td>
<td data-bind="text: Amount"></td>
<td data-bind="text: Price"></td>
<td data-bind="text: LineTotal"></td>
</tr>
</table>
</div>
</div>
</div>
<div class="panel-footer">
</div>
</div>
and
var cartViewModel = {
Currencies: ko.observableArray()
};
$(function () {
ShowCart();
});
function AddToCart(i, a) {
$.getJSON('#Url.Action("AddToCart", "Products")/' + i + '?Amount=' + a, null, function (d) {
if (d)
ShowCart();
});
}
function ShowCart() {
$.getJSON('#Url.Action("GetCart","Products")', null, function (c) {
cartViewModel.Currencies = ko.observableArray(c);
cartViewModel.Currencies.valueHasMutated();
ko.applyBindings(cartViewModel);
});
}
How can I refresh the binding in the $.getJSON callback?

I think your problem is that you're overwriting the observables in your view-model.
All you need to do is pass a new value into the existing observable.
Try this instead:
function ShowCart() {
$.getJSON('#Url.Action("GetCart","Products")', null, function (c) {
cartViewModel.Currencies(c);
});
}

Related

problem in datatable when use in livewire component

i use livewire defer loading for load data after rendering page.
After opening the page, the information is successfully received and displayed in the table
But the problem is that I use datatable and when the received information is displayed, datatable becomes a simple table. As if I did not use datatable at all.
This is the livewire component code
class Cryptolist extends Component
{
public bool $loadData = false;
public function init()
{
$this->loadData = true;
}
public function render()
{
try {
if ($this->loadData) {
$api = new \Binance\API('api','secret');
$prices = $api->coins();
$one = json_encode($prices, true);
$coins = json_decode($one , true);
} else {
$coins = [];
}
return view('livewire.backend.crypto.cryptolist')->with('coins' , $coins);
}catch(\Exception $e)
{
return view('wrong')->with('e' , $e);
}
}
}
And this is the component view where the table is located and displays the received information
<div wire:init="init">
#if ($loadData)
<div id="loadesh1" wire:ignore>
<table class="datatable-init nk-tb-list nk-tb-ulist" data-auto-responsive="false">
<thead>
<tr class="nk-tb-item nk-tb-head">
<th class="nk-tb-col"><span class="sub-text">name</span></th>
<th class="nk-tb-col tb-col-mb"><span class="sub-text">balance</span></th>
</tr>
</thead>
<tbody>
#foreach ($coins as $item => $value)
<tr class="nk-tb-item">
<td class="nk-tb-col">
<div class="user-card">
<div class="user-avatar d-none d-sm-flex">
#if(file_exists(public_path() . '/img/crypto/'.strtolower($value['coin'].".svg")))
<img style="border-radius: 0"
src="{{asset('/img/crypto/'.strtolower($value['coin']))}}.svg" class="img-fluid"
alt="">
#else
<img style="border-radius: 0"
src="https://demo.rayanscript.ir/-/vendor/cryptocurrency-icons/32/color/noimage.png"
class="img-fluid" alt="">
#endif
</div>
<div class="user-info">
<span class="tb-lead english" style="font-weight: bolder">{{$value['name']}}</span>
<span class="english">{{$value['coin']}}</span>
</div>
</div>
</td>
<td class="nk-tb-col tb-col-mb" data-order="{{$value['coin']}}">
<div class="btn-group" aria-label="Basic example">
<button type="button" class="btn btn-sm btn-dim btn-light"
wire:click="getBalance('{{$value['coin']}}')">
<div wire:loading wire:target="getBalance('{{$value['coin']}}')">
<span class="spinner-border spinner-border-sm" role="status"
aria-hidden="true"></span>
</div>
<span class="w-120px" id="coin-{{$value['coin']}}">get balance</span>
</button>
<button type="button" class="btn btn-sm btn-dim btn-primary">add coin</button>
</div>
</td>
</tr><!-- .nk-tb-item -->
#endforeach
</tbody>
</table>
</div>
#else
Loading data...
#endif
</div>
What do you think is the problem, what code is written incorrectly?

Cart with login in laravel 5.7

I am implement shopping cart with login & witout login i am using cart package from laravel but it will stored cart item on local storage now i want to login and add cart item in database. When i am not login then item adds in local storage but when i am login then items add in database i am confuse. how i am implement I am sharing my code that i am developed need solutions
Controller:
public function add_to_cart(Request $req)
{
$userId=Session::get('userid');
$qty=$req->qty;
$product_id=$req->product_id;
$product_info=DB::table('product_details')
->join('subcategory','subcategory.sub_id','=','product_details.sub_id')
->select('subcategory.image','subcategory.name_of_subcategory','product_details.*')
->where('product_details.product_id',$product_id)->first();
$sub_id=$product_info->sub_id;
//dd($product_info);
Cart::add(array(
'id'=>$product_info->product_id,
'name'=>$product_info->name_of_subcategory,
'price'=>$product_info->price,
'qty'=>$qty,
'options'=>array('image' =>$product_info->image,'description'=>$product_info->description_of_product)
));
if($userId)
{
$content=\Cart::Content();
}
// $content=\Cart::Content();
// dd($content);
//$data = DB::select('select * from product_details where sub_id = ?',[$sub_id]);
//return view('productdetails',['data'=>$data]);
return view('cart');
}
blade
#extends('layout.header')
#section('content')
<?php
$contents=\Cart::Content();
?>
<div class="container mt-5">
<table id="cart" class="table table-hover table-condensed">
<thead>
<tr>
<th>Product</th>
<th>Price</th>
<th>Quantity</th>
<th class="text-center">Subtotal</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach($contents as $v_contents)
<tr>
<td data-th="Product">
<div class="row">
<div class="col-sm-4 hidden-xs"><img src="{{asset('images/'.$v_contents->options->image)}}" alt="..." class="img-responsive"/ height="100" width="100"></div>
<div class="col-sm-8">
<h4 class="nomargin">{{$v_contents->name}}</h4>
<p>{{$v_contents->options->description}}</p>
</div>
</div>
</td>
<td data-th="Price">{{$v_contents->price}}</td>
<td data-th="Quantity">
<div class="plus-minus" style="width:150px; ">
<div class="input-group">
<span class="input-group-btn">
<button type="button" class="btn btn-default btn-number" id="subs" >
<span class="fa fa-minus"></span>
</button>
</span>
<input type="text" id="qty" name="qty" class="form-control input-number" value="{{$v_contents->qty}}" min="1" max="10">
<span class="input-group-btn">
<button type="button" class="btn btn-default btn-number" data-type="plus" id="adds">
<span class="fa fa-plus"></span>
</button>
</span>
</div>
<input type="hidden" name="product_id" id="product_id" value="{{ $v_contents->rowId}}">
</div>
</td>
<td data-th="Subtotal" class="text-center">{{ $v_contents->total}}</td>
<td class="actions" data-th="">
<a class="btn btn-danger btn-sm" href="{{ URL::to('/delete-to-cart/'.$v_contents->rowId)}}"><i class="fa fa-trash-o"></i></a>
</td>
</tr>
#endforeach
</tbody>
<tfoot>
<!-- <tr class="visible-xs">
<td class="text-center"><strong>Total 1.99</strong></td>
</tr> -->
<tr>
<td><i class="fa fa-angle-left"></i> Continue Shopping</td>
<td colspan="2" class="hidden-xs"></td>
<td class="hidden-xs text-center"><strong>Total {{\Cart::subtotal()}}</strong></td>
<td>Checkout <i class="fa fa-angle-right"></i></td>
</tr>
</tfoot>
</table>
</div>
<script type="text/javascript">
/*$('#adds').click(function add() {
var $qty = $("#qty");
var a = $qty.val();
a++;
$("#subs").prop("disabled", !a);
$qty.val(a);
});
$("#subs").prop("disabled", !$("#qty").val());
$('#subs').click(function subst() {
var $qty = $("#qty");
var b = $qty.val();
if (b >= 1) {
b--;
$qty.val(b);
}
else {
$("#subs").prop("disabled", true);
}
});*/
</script>
<script>
$(document).ready(function(){
$(document).on('click', '#adds', function(e) {
var qty = $('#qty').val();
var product_id=$('#product_id').val();
//alert(qty);
e.preventDefault()
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
}
});
jQuery.ajax({
url: "{{ url('/increment') }}",
method: 'get',
data: {
qty: qty,id:product_id
},
success: function(result){
jQuery('#qty').val(result.qty);
}});
});
});
</script>
<script>
$(document).ready(function(){
$(document).on('click', '#subs', function(e) {
var qty = $('#qty').val();
var product_id=$('#product_id').val();
//alert(qty);
e.preventDefault()
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
}
});
jQuery.ajax({
url: "{{ url('/decrement') }}",
method: 'get',
data: {
qty: qty,id:product_id
},
success: function(result){
jQuery('#qty').val(result.qty);
}});
});
});
</script>
#endsection

Fill table depending dropdown list selected value in Laravel vuejs Axios

I am trying to get data in the table code are as below
I want to autofill the table with the depending dropdownlist selected value. i’ve been finding solution since days but didn’t get any success. I’m very new at this.
If anyone could help to get me out from this issue i’ll be very grateful. Thank You.
Here Is my HTML code
<div class="col-md-12">
<div class="card">
<div class="card-header">
<h3 class="card-title">employees Table</h3>
<div class="card-body">
<div class="md-3">
<div class="row">
<div class="col-md-12">
<div class="form-group">
<select
name="company_id"
id="company_id"
:class="{'is-invalid':form.errors.has('company_id')}"
class="form-control"
v-model="form.company_id"
#change="getEmployeesbyCompany()"
>
<option value selected>Select Company</option>
<option
v-for="Company in Companies.data"
:key="Company.id"
>{{Company.Company}}</option>
</select>
<has-error :form="form" field="company_id"></has-error>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- /.card-header -->
<div class="card-body table-responsive p-0">
<div class="col-md-12"></div>
<table class="table table-hover">
<!-- <thead>
</thead>-->
<tbody>
<tr>
<th>ID</th>
<th>Badge#</th>
<th>Company</th>
<th>BadgeType</th>
<th>Nationality</th>
<th>Last Name</th>
<th>First Name</th>
<th>Telphonenumber</th>
<th>Position</th>
<th>SupervisorName</th>
<th>SupervisorNumber</th>
<th>Issuedate</th>
<th>Tazker</th>
<th>Expiredate</th>
<th>Serialnumber</th>
<th>Modify</th>
</tr>
<tr v-for="employee in employees.data" :key="employee.id">
<td>{{employee.id}}</td>
<td>{{employee.BadgeCode|UppCaseFirstLetter}}</td>
<!-- <td>{{employee.company_id}}</td> -->
<td>{{Company.Company}}</td>
<td>
<span class="tag tag-success">{{employee.BadgeType}}</span>
</td>
<td>{{Nationality.nationality}}</td>
<td>{{employee.lastname |UppCaseFirstLetter}}</td>
<td>{{employee.firstname |UppCaseFirstLetter}}</td>
<td>{{employee.telphonenumber |UppCaseFirstLetter}}</td>
<td>{{employee.position |UppCaseFirstLetter}}</td>
<td>{{employee.supervisorname |UppCaseFirstLetter}}</td>
<td>{{employee.supervisornumber|UppCaseFirstLetter}}</td>
<td>{{employee.Issuedate|mydate}}</td>
<td>{{employee.tazker|UppCaseFirstLetter}}</td>
<td>{{employee.Expiredate |mydate}}</td>
<td>{{employee.serialnumber |UppCaseFirstLetter}}</td>
</tr>
</tbody>
</table>
</div>
<!-- /.card-body -->
<div class="card-footer">
<pagination :data="employees" #pagination-change-page="getResults"></pagination>
</div>
</div>
<!-- /.card -->
</div>
My #change="getEmployeesbyCompany" method:
methods: {
getEmployeesbyCompany: function() {
axios.get("api/getEmployees", {
params: {company_id: this.form.company_id}})
.then( function(response) {this.employees = response.data;}.bind(this)
);
}
Route:
Route::get('getEmployees','API\EmployeeController#getEmployees');
My getEmployees(){} method:
public function getEmployees(Request $request)
{
$employees = Employee::where('company_id',$request->company_id)->get();
return $employees;
}
My data() in Vue Component:
data() {
return {
editMode: false,
selectedTicketInvoiceId: false,
Companies: {},
Nationalities: {},
employees: {},
form: new Form({id: "",BadgeCode: "",BadgeType: "",company_id: "",
nationality_id: "",lastname: "",firstname: "",telphonenumber: "",
position: "",supervisorname: "", supervisornumber: "",
issuedate: "",tazker: "", expiredate: "", serialnumber: "" })};
}
The issue is that your table is using employees.data in the v-for directive. This works fine on the initial page load, because employees is a Laravel paginator, so the data property is defined, and it contains the array of employees, as expected.
However, your controller function is simply returning an array of employees. You are saving that array to your Vue instance's employees property. So now employees.data is undefined, and your table is empty.
To fix the issue, you can update your controller function like this:
public function getEmployees(Request $request)
{
$employees = Employee::where('company_id',$request->company_id)->get();
return ['data' => $employees]; // or return response()->json(['data' => employees]);
}

I want to set local-storage and qty increment in every click when product ID already exist in cart by Vue.js

I made a shopping cart, where a product item gets added to the cart. When I click the product, it gets stored in a cart, but not local storage. I set it local-storage. When I click a product that already exists in the cart, I want to increment its quantity, but that's not happening. It adds another row instead, which I want to prevent.
Here is my component:
<template>
<div class="row">
<div class="col-md-8">
<div v-for="(product, id) in products" :key="id" class="col-xl-3 col-sm-6 mb-3 float-left">
<div class="card o-hidden h-100">
<div class="card-body">
<div class="card-body-icon">
<i class="fas fa-fw fa-comments"></i>
</div>
<div class="mr-5">{{product.name}}</div>
</div>
<div class="card-footer clearfix small z-1 form-group row" href="#">
<span class="float-left"><input type="text" v-model="product.qty" class="form-control form-control-sm mb-2"></span>
<strong class="float-right col-sm-6">
{{product.price}} TK
</strong>
<button class="btn btn-sm btn-info float-right col-sm-6" #click="addToCart(product)">
<i class="fas fa-plus"></i>
</button>
</div>
</div>
</div>
</div>
<div class="col-md-4">
<table class="table table-sm">
<thead>
<tr>
<th>#SL</th>
<th>Name</th>
<th>Qty</th>
<th>Price</th>
<th>L/T</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr v-for="(cart, i) in carts" :key="i">
<td>{{cart.id}}</td>
<td>{{cart.name}} </td>
<td class="text-right">{{cart.qty}}</td>
<td class="text-right">{{cart.price}}</td>
<td class="text-right">{{cart.price*cart.qty}}</td>
<td><button type="button" #click="removeProduct(i)" class="btn btn-sm btn-danger">x</button></td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="4" class="text-right font-weight-bold">Total</td>
<td class="text-right"> {{total}}/-</td>
</tr>
</tfoot>
</table>
<div>
<button class="btn btn-sm btn-info float-right">Checkout</button>
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
products:[],
carts:[],
}
},
computed:{
total(){
var total = 0
this.carts.forEach(cart => {
total += parseFloat(cart.price * cart.qty)
})
return total
},
},
mounted(){
this.showProduct()
},
methods:{
showProduct(){
axios.get('api/pos')
.then(res=>{
this.products = res.data.data
});
},
addToCart(product){
this.carts.push(product)
},
removeProduct(i){
this.carts.splice(i,1)
}
}
}
</script>
Here is the screenshot:
The problem is addToCart() just pushes another product into the cart without checking if it already exists.
To fix the problem, update that method to find the item, and increment the item's quantity if found. Otherwise, push another item into the cart:
addToCart(product) {
if (this.carts.find(p => p.id === product.id)) {
product.qty++
} else {
this.carts.push(product)
}
}

Fetch Records in Angular datatable

Im new to Angular and My Requirement is
A component includes a form with the field name call "Brand" and a button to add the same record to database through angular service and there should be a datatable which is fetching all brand data from database to data table.
so by using fetchall method in ts file, i am assigning values to data table. im calling fetchall method to ngoninit() which helps me to show the data in table while component get initialized. to add record, i am using a method call addyear() and calling the same method to onSumbit(). my problem is when i add the record to database, i should be able to load newly added record to angular data table! since that method in ngoninit(), i have to refresh the browser to get the record in data table kindly give me a solution. for the back end, im using Spring boot with Postgres database
My Component TS file
constructor(private brandService:BrandService,private toastyService: ToastyService) { }
ngOnInit() {
this.findbrand();
}
onSubmit()
{
this.saveBrand();
this.submitted=true;
}
saveBrand()
{
this.brandService.addbrand(this.brand).subscribe
(data=>this.addToast({title:'Record Has been added Successfully', msg:'', timeout: 5000, theme:'default', position:'top-right', type:'success'}),
error=>this.addToast({title:'Record Not Added! Sorry', msg:'', timeout: 5000, theme:'default', position:'top-right', type:'error'}));
this.brand=new Brand();
}
findbrand()
{
this.brandService.findbrand().subscribe(data=>this.data=data,error=>this.addToast({title:'Record Cannot be found! Sorry', msg:'', timeout: 5000, theme:'default', position:'top-right', type:'error'}));
}
My Service.TS file
export class BrandService {
constructor(private http:HttpClient) { }
private baseUrl='http://localhost:8080/snazzy-engine/brand';
addbrand(brand:object):Observable<any>
{
return this.http.post(`${this.baseUrl}` + `/insert`, brand,{
headers: {'schemaName':'test.'}
});
}
findbrand():Observable<any>
{
return this.http.get(`${this.baseUrl}` + `/find-all`,{
headers: {'schemaName':'test.'}
});
}
getbrandid(id: number): Observable<Object> {
return this.http.get(`${this.baseUrl}/find-one/${id}`, {headers:
{'schemaName':'test.'}});
}
}
My HTML File
<div class="table-content crm-table">
<div class="project-table">
<div id="crm-contact" class="dt-responsive">
<div class="row">
<div class="col-xs-12 col-sm-12 col-sm-12 col-md-6">
<div>
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-6">
<div style="text-align: right;">
<label>Search:
<input type="search" [(ngModel)]="filterQuery" class="form-control input-sm full-data-search" placeholder="Search name">
</label>
</div>
</div>
</div>
<!-- <div class="panel-heading">User information</div>-->
<div class="table-responsive">
<table class="table table-bordered table-hover table-sm" [mfData]="data | dataFilter : filterQuery" #mf="mfDataTable" [mfRowsOnPage]="rowsOnPage" [(mfSortBy)]="sortBy"
[(mfSortOrder)]="sortOrder">
<thead class="thead-dark text-center">
<tr>
<th style="width:10%">
<mfDefaultSorter by="brandId">Brand ID</mfDefaultSorter>
</th>
<th style="width:70%">
<mfDefaultSorter by="name">Brand Name</mfDefaultSorter>
</th>
<th style="width:10%">
<mfDefaultSorter by="more">More</mfDefaultSorter>
</th>
<th style="width:10%">
<mfDefaultSorter by="checkbox">Delete</mfDefaultSorter>
</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let item of mf.data; let i = index;">
<td>{{item.brandId}}</td>
<td>{{item.brand}}</td>
<td class="action-icon">
<button type="button" class="btn btn-sm btn-primary" (click)="findybrandid(item.brandId);modalDefault.show();">
edit
</button>
</td>
<td>
<div class="checkbox text-center">
<label><input type="checkbox" value=""></label>
</div>
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="10">
<mfBootstrapPaginator class="pagination-main f-right"></mfBootstrapPaginator>
</td>
</tr>
</tfoot>
</table>
</div>
</div>
</div>
<div style="text-align:center;">
<button class="btn btn-out btn-danger ripple light"><i class="icofont icofont-check-circled"></i>Delete</button>
</div>
</div>
</div>
</div>
try this
saveBrand()
{
this.brandService.addbrand(this.brand)
.subscribe(
data => this.addToast(
{
title:'Record Has been added Successfully',
msg:'',
timeout: 5000,
theme:'default',
position:'top-right',
type:'success'
}),
error => this.addToast(
{
title:'Record Not Added! Sorry',
msg:'',
timeout: 5000,
theme:'default',
position:'top-right',
type:'error'
})
);
this.data.push(this.brand); /*change: push new data into an array*/
this.brand=new Brand();
}

Resources