How to manipulate axios returned data to print in desired formate - laravel

<template>
<div>
<table class="table table-responsive">
<tbody>
<tr v-for="(gameresults, index) in gameresults" :key="index">
<td style="color: #082ad4; font-size: 24px;">{{ gameresults.game_name }}</br>
<h3 style="color:#00d2f1; font-size: 18px;">{{ gameresults.cards }}</h3></td>
<h3 style="color:#00d2f1; font-size: 18px;">{{ this.formattedArray }}</h3></td>
</tr>
</tbody>
</table>
</div></template>
<script>
export default {
props: [''],
mounted() {
console.log('Component mounted.')
},
data() {
return {
gameresults:0,
};
},
methods: {
changeResult() {
let formattedArray = [];
this.gameresults.cards.forEach(str => {
const subs = str.split('');
const subsTwo = subs[2].split(',');
const formattedString = `${subs[1]} - ${subs[0]}-${subsTwo[0]}${subs[4]}-${subsTwo[1]}`;
formattedArray.push(formattedString);
});
console.log('Formatted Data', formattedArray);
}
// this.gameresults[0].cards
},
computed: {
chkgameresults() {
axios.post('/gameresults')
.then(response => {
this.gameresults = response.data ;
this.changeResult();
});
},
},
created () {
this.chkgameresults();
}
};
</script>
ref code axios fetches mysql concat data in array format having 2 keys [game_name and card ] i want card key to be manipulated . when i print card array using this.gameresults[0].card its giving me 123-9,897-0 using {{ gameresults.cards }} inside vu template , i want value to get manipulated like 123-90-897 ( only last 0 gets before the second exp and become 0-897 removing ',' separator

Assuming that your data is an array lets define a method...........
formatData(myData) {
let formattedArray = [];
myData.myValue.forEach(str => {
const subs = str.split('');
const subsTwo = subs[2].split(',');
const formattedString = `${subs[1]} - ${subs[0]}-${subsTwo[0]}${subs[4]}-${subsTwo[1]}`;
formattedArray.push(formattedString);
});
console.log('Formatted Data', formattedArray);
}

Related

Anyone can tell me whats wrong in here when im putting a array of number like :1,2 its starting to freeze the screen i hope someone can help me thanks

Hello guys im trying to learn vue and im trying to use datatable from https://datatables.net/ and having a problem with my action button that im not able to get the id when the #viewModal is been triggered i hope someone can help me to get the id of each buttons thanks and here is my code TIA:
EmployeeDataTable Component :
<template>
<div class="card">
<div class="card-header">
<div class="card-title">Employee List</div>
</div>
<div class="card-body">
<div class="table-responsive">
<table
id="employee-table"
class="table-sm table-bordered table-hover text-center display"
width="100%"
>
<thead>
<tr>
<th class="pt-3 pb-3">#</th>
<th>Name</th>
<th>Address</th>
<th>Contact #</th>
<th>Department</th>
<th>Status</th>
<th>Actions</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
</div>
</div>
</template>
<script>
//For Datatable to work
import "datatables.net";
import EmployeeEdit from "./EmployeeEdit.vue";
export default {
name: "EmployeeList",
data() {
return {
employees: [],
};
},
mounted() {
this.getEmployeeLists();
},
components: {
"employee-edit": EmployeeEdit,
},
methods: {
getEmployeeLists() {
// INITIALIZE DATATABLE
$("#employee-table")
.DataTable({
//LOADING
// processing: true,
//AJAX
serverSide: true,
//DIRECTION
order: [[1, "desc"]],
//AJAX
ajax: {
url: "/api/getEmployeeLists",
dataList: "json",
type: "POST",
data: { _token: "{{csrf_token()}}" },
},
//TABLE COLUMNS SHOULD BE THE SAME IN CONTROLLER
columns: [
{ data: "#" },
{ data: "name" },
{ data: "address" },
{ data: "contact" },
{ data: "department" },
{ data: "status" },
{
data: "actions",
//allowing modification
createdCell(cell, cellData, rowData) {
let EmployeeListDataTableActions = Vue.extend(
require("./EmployeeListDataTableAction.vue").default
);
let instance = new EmployeeListDataTableActions().$mount();
$(cell).empty().append(instance.$el);
},
},
],
//View Count in Table
lengthMenu: [
[10, 25, 50, -1],
[10, 25, 50, "All"],
],
})
.columns();
},
beforeDestroy: function () {
$(this.$el).DataTable().destroy();
},
},
};
</script>
EmployeeDataTableAction Component :
<template>
<button class="btn btn-primary btn-sm" #click="viewModal" title="View Employee Details">
<i class="fa fa-eye"></i>
</button>
</template>
<script>
export default{
name: 'EmployeeListDataTableAction',
data: function() {
return {
}
},
mounted() {
},
methods: {
viewModal() {
var id = $(this.$el).closest('tr').find('input').val();
return false;
axios
.post(`/api/getEmployeeDetails/${id}`, {
id: id,
})
.then((response) => {
$("#edit-employee-modal").modal("show");
$(".myModalLabel").text(
response.data.name +
" - " +
response.data.department_name
);
state.commit("getEmployeeDetailsArray", response.data);
state.commit("getTransactionId", response.data.id);
})
.catch((response) => {
this.$toast.top("Something went wrong!");
});
},
},
}
</script>
Employee Controller for the DataTable :
public function employeeList(Request $request){
$all = Employee::getEmployeeTotal();
//total count of data
$total_data = $all;
//total filter
$total_filtered = $total_data;
//set_time_limit(seconds)
$limit = $request->input('length');
//start
$start = $request->input('start');
//order
// $order = $columns[$request->input('order.0.column')];
//direction
$dir = $request->input('order.0.dir');
$search_value = $request->input('search.value');
if (!empty($search_value)) {
$posts = Employee::getEmployeeNameSearch($search_value,$start, $limit, $dir);
$total_data = count($posts);
$total_filtered = $total_data;
}else{
if(empty($request->input('search.value')))
{
//if no search
$posts = Employee::getEmployeeList($start, $limit, $dir);
}
}
$data = array();
if(!empty($posts))
{
$counter = $start + 1;
foreach ($posts as $post)
{
$department = GlobalModel::getSingleDataTable('departments',$post->department_id);
$status = StatusController::checkStatus($post->status);
$nested_data['#'] = '<span style="font-size: 12px ; text-align: center;">'.$counter++.'</span>';
$nested_data['name'] = '<p style="text-align: center;">'.$post->name.'</p>';
$nested_data['address'] = '<p style="text-align: center;">'.$post->address.'</p>';
$nested_data['contact'] = '<p style="text-align: center;">'.$post->contact.'</p>';
$nested_data['department'] = '<p style="text-align: center;">'.$department->name.'</p>';
$nested_data['status'] = '<p style="text-align: center;">'.$status.'</p>';
$nested_data['actions'] = '';
$data[] = $nested_data;
}
}
$json_data=array(
"draw" => intval($request->input('draw')),
"recordsTotal" => intval($total_data),
"recordsFiltered" => intval($total_filtered),
"data" => $data
);
return response()->json($json_data);
}
In the second line of your viewModal() function, you are placing a return false; statement. "The return statement ends function execution and specifies a value to be returned to the function caller." From Mozilla docs. That's why the API call is never executing.

Show component only after all images loaded

I am using Vue 3 and what i would like to achieve is to load all images inside a card (Album Card) and only then show the component on screen..
below is an how it looks now and also my code.
Does anybody have an idea how to achieve this?
currently component is shown first and then the images are loaded, which does not seem like a perfect user experience.
example
<template>
<div class="content-container">
<div v-if="isLoading" style="width: 100%">LOADING</div>
<album-card
v-for="album in this.albums"
:key="album.id"
:albumTitle="album.title"
:albumId="album.id"
:albumPhotos="album.thumbnailPhotos.map((photo) => photo)"
></album-card>
</div>
</template>
<script lang="ts">
import { defineComponent } from "vue";
import albumCard from "#/components/AlbumCard.vue";
interface Album {
userId: number;
id: number;
title: string;
thumbnailPhotos: Array<Photo>;
}
interface Photo {
albumId: number;
id: number;
title: string;
url: string;
thumbnailUrl: string;
}
export default defineComponent({
name: "Albums",
components: {
albumCard,
},
data() {
return {
albums: [] as Album[],
isLoading: false as Boolean,
};
},
methods: {
async getAlbums() {
this.isLoading = true;
let id_param = this.$route.params.id;
fetch(
`https://jsonplaceholder.typicode.com/albums/${
id_param === undefined ? "" : "?userId=" + id_param
}`
)
.then((response) => response.json())
.then((response: Album[]) => {
//api returns array, loop needed
response.forEach((album: Album) => {
this.getRandomPhotos(album.id).then((response: Photo[]) => {
album.thumbnailPhotos = response;
this.albums.push(album);
});
});
})
.then(() => {
this.isLoading = false;
});
},
getRandomPhotos(albumId: number): Promise<Photo[]> {
var promise = fetch(
`https://jsonplaceholder.typicode.com/photos?albumId=${albumId}`
)
.then((response) => response.json())
.then((response: Photo[]) => {
const shuffled = this.shuffleArray(response);
return shuffled.splice(0, 3);
});
return promise;
},
/*
Durstenfeld shuffle by stackoverflow answer:
https://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array/12646864#12646864
*/
shuffleArray(array: Photo[]): Photo[] {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
return array;
},
},
created: function () {
this.getAlbums();
},
});
</script>
What i did to solve this problem was using function on load event on (img) html tag inside album-card component. While images are loading a loading spinner is shown. After three images are loaded show the component on screen.
<template>
<router-link
class="router-link"
#click="selectAlbum(albumsId)"
:to="{ name: 'Photos', params: { albumId: albumsId } }"
>
<div class="album-card-container" v-show="this.numLoaded == 3">
<div class="photos-container">
<img
v-for="photo in this.thumbnailPhotos()"
:key="photo.id"
:src="photo.thumbnailUrl"
#load="loaded()"
/>
</div>
<span>
{{ albumTitle }}
</span>
</div>
<div v-if="this.numLoaded != 3" class="album-card-container">
<the-loader></the-loader>
</div>
</router-link>
</template>
<script lang="ts">
import { defineComponent } from "vue";
import { store } from "#/store";
export default defineComponent({
name: "album-card",
props: {
albumTitle: String,
albumsId: Number,
},
data: function () {
return {
store: store,
numLoaded: 0,
};
},
methods: {
thumbnailPhotos() {
return this.$attrs.albumPhotos;
},
selectAlbum(value: string) {
this.store.selectedAlbum = value;
},
loaded() {
this.numLoaded = this.numLoaded + 1;
},
},
});
</script>
Important note on using this approach is to use v-show instead of v-if on the div. v-show puts element in html(and sets display:none), while the v-if does not render element in html so images are never loaded.

Vue / Laravel - Axios post multiple field

I created a component that can add additional fields by pressing a button. I don't know how would I submit this in the database with axios.post and laravel controller. I was able to achieve it in the past with the use of jquery and pure laravel, but I'm confused how to implement it in vue and axios.
Component.vue
<template>
<v-app>
<table class="table">
<thead>
<tr>
<td><strong>Title</strong></td>
<td><strong>Description</strong></td>
<td><strong>File</strong></td>
<td></td>
</tr>
</thead>
<tbody>
<tr v-for="(row, index) in rows" :key="row.id">
<td><v-text-field outlined v-model="row.title" /></td>
<td><v-text-field outlined v-model="row.description" /></td>
<td>
<label class="fileContainer">
<input type="file" #change="setFilename($event, row)" :id="index">
</label>
</td>
<td><a #click="removeElement(index);" style="cursor: pointer">X</a></td>
</tr>
</tbody>
</table>
<div>
<v-btn #click="addRow()">Add row</v-btn>
<v-btn class="success" #click="save()">Save</v-btn>
<pre>{{ rows | json}}</pre>
</div>
</v-app>
</template>
<script>
export default {
data: ()=> ({
rows: []
}),
methods: {
addRow() {
var elem = document.createElement('tr');
this.rows.push({
title: "",
description: "",
file: {
name: 'Choose File'
}
});
},
removeElement(index) {
this.rows.splice(index, 1);
},
setFilename(event, row) {
var file = event.target.files[0];
row.file = file
},
save() {
// axios.post
}
}
}
</script>
Controller.php
public function store(Request $request)
{
// store function
}
save() {
let data = this.rows
axios
.post("Url", {
data
})
.then((res) => {
console.log(res);
})
.catch((err) => {
console.log(err)
});
}
ref link https://github.com/axios/axios
save() {
axios
.post("/your/uri", {
user_id: 1,
user_name:'jhone doe',
email:'test#test.com'
})
.then(response => {
console.log(response);
})
.catch(error => {
console.log(error)
});
}
You can retrieve your data from your controller $request->user_id,...,$request->email
Tip: if you post any object,you must JSON.stringify(your_json) them and in a response data from controller json_decode($your_json,true) or you need to modify your header file.
Always use '/your/uri' instead of /your/uri/ without trailing '/'
It now works. I'll be posting my code just in case someone encounter the same hurdle. Than you very much to #kamlesh-paul and #md-amirozzaman
Component.vue
<script>
export default {
data: ()=> ({
rows: [],
}),
methods: {
addRow() {
this.rows.push({
corporate_objective_id: '',
kpa: '',
kpi: '',
weight: '',
score: '',
equal: '',
file: {
name: 'Choose File'
}
});
},
removeElement(index) {
this.rows.splice(index, 1);
},
setFilename(event, row) {
var file = event.target.files[0];
row.file = file
},
save() {
const postData = {
data: this.rows
}
console.log(postData)
axios
.post('/api/employee-objective', {postData})
.then(res => { console.log(res) })
.catch(err => { console.log(err) });
}
}
}
</script>
Controller.php
public function store(Request $request) {
foreach($request->data as $data) {
$container = EmployeeObjective::updateOrCreate([
'kpa_info' => $data['kpa'],
'kpi_info' => $data['kpi'],
'kpa_weight' => $data['weight'],
'kpa_score_1' => $data['score'],
'kpa_equal' => $data['equal'],
]);
$container->save();
}
}

Vue2 component rendering on ajax response

I have created a component that reacts to this template:
<table-sort index="job.job_id"></table-sort>
However, when I get this template from a ajax response and add it to the DOM. It doesn't recognize it as a Vue component. How do I render this component?
Here is my component:
Vue.component('table-sort', {
name: 'table-sort',
template: `
<div class="table-sort" :data-index="index">
<i v-on:click="sortTable($event)" direction="ASC" class="fa fa-caret-up"></i>
<i v-on:click="sortTable($event)" direction="DESC" class="fa fa-caret-down"></i>
</div>
`,
props: {
index: {
type: String,
required: true,
},
},
methods: {
sortTable: function ($event) {
const self = $event.target;
const index = this.index;
const direction = self.getAttribute('direction');
let filters = Url.getQueryParameters();
filters.sort = index;
filters.direction = direction;
filters.page = 1;
const url = Url.getUrlWithoutQueryString();
const newUrl = Url.appendParamsToUrl(filters, url);
Url.redirect(newUrl);
},
},
});
Here is how I call the code to generate the table:
var ajaxTable = new AjaxTable({
name: 'jobs',
request: inputs,
container: '#job-table',
fields: fields,
});
Here is the code that appends the template:
public async drawTable() {
this.table = $(`<table class="table table-striped table-bordered table-hover table-condensed"><thead><tr id="header"></tr></thead><tbody></tbody></table>`);
this.count = $(`<div class="count pull-left"></div>`);
this.pagination = $(`<div class="pagination pull-right"></div>`);
this.fields.map((field: ColumnData) => {
let out = `<th>${field.title}`;
if (!!field.sort) {
out += ` <table-sort index="${field.sort}"></table-sort>`;
}
out += `</th>`;
this.table.find('#header').append(out);
});
this.container.append(this.table, this.count, this.pagination);
}

Input search filter not working (React)

Have component that works with React, Redux and AJAX:
class IncomeProfile extends Component {
constructor(props) {
super(props)
this.state = {
items: this.props.items || []
}
}
componentDidMount() {
this.props.IncomeListProfile();
}
componentWillReceiveProps(nextProps) {
this.setState({ items: nextProps.items });
}
filterList(event) {
var updatedList = this.state.items;
updatedList = updatedList.filter(function(item) {
return item.toLowerCase().search(event.target.value.toLowerCase()) !== -1;
});
this.setState({items: updatedList}); // now this.state.items has a value
}
render() {
var elems = this.props.items;
if (typeof elems == 'undefined') {
elems = [];
}
//console.log(elems);
return (
<div>
<table className='table'>
<thead className='theadstyle'>
<th>date
<input></input>
</th>
<th>
<input onChange={this.filterList} type='text' placeholder='keyword search'></input>
</th>
<th>
<input type='text' placeholder='amount search'></input>
</th>
<th>amount</th>
<th>Show archived</th>
</thead>
<div className='tbodymar'></div>
<tbody >
{elems.map((item) => (
<tr key={item.course_id}>
<td>{item.created_at}</td>
<td>{item.name}</td>
<td>{item.remark}</td>
<td>{item.income_amount}</td>
<td>more options</td>
</tr>
))}
</tbody>
</table>
</div>
)
}
}
const mapDispatchToProps = function(dispatch) {
return {
IncomeListProfile: () => dispatch(IncomeProfileList())
}
}
const mapStateToProps = function(state) {
//var mystore = state.toJS()
var mystore = state.getIn(['incomeProfileList'])['course_list'];
//console.log(mystored.hh);
var copy = Object.assign({}, mystore);
return {items: copy.course_list};
}
export default connect(mapStateToProps, mapDispatchToProps)(IncomeProfile);
When I enter something in input, I get error Cannot read property 'state' of undefined, but console.log show's my state. What wrong with filter ? Where mistake? if I had right state?
this.props.items only get populate after componentDidMount?
If so, and you want to set the items in the state too. You can use componentWillReceiveProps method to set the new props to you state.
componentWillReceiveProps(nextProps) {
this.setState({ items: nextProps.items });
}

Resources