I am trying to post my form using axios, but I am not able to get the data to my backend using expressjs
This is what I am doing:
<template>
<form class="" method="post" #submit.prevent="postNow">
<input type="text" name="" value="" v-model="name">
<button type="submit" name="button">Submit</button>
</form>
</template>
export default {
name: 'formPost',
data() {
return {
name: '',
show: false,
};
},
methods: {
postNow() {
axios.post('http://localhost:3030/api/new/post', {
headers: {
'Content-type': 'application/x-www-form-urlencoded',
},
body: this.name,
});
},
components: {
Headers,
Footers,
},
};
backend file:
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
router.post('/new/post', (req, res) => {
res.json(console.log("this is working" + ' ' + req.body.name));
});
The error I am receiving is:
this is working undefined
Axios post format:
axios.post(url[, data[, config]])
Your request should be:
axios.post('http://localhost:3030/api/new/post',
this.name, // the data to post
{ headers: {
'Content-type': 'application/x-www-form-urlencoded',
}
}).then(response => ....);
Fiddle: https://jsfiddle.net/wostex/jsrr4v1k/3/
<template>
<div id="content">
<h1>...</h1>
<div>
<label>Product Name</label> : <input type="text" id="txt1" v-model="model.productName" />
</div>
<div>
<label>Desciription</label> : <input type="text" id="txt2" v-model="model.descrption" />
</div>
<div>
<button type="button" v-on:click="saveClick">Save</button>
</div>
</div>
<hr />
<hr />
<h1>...</h1>
<table border="1" style="margin:auto">
<thead>
<tr>
<th style="width: 100px">ID</th>
<th style="width: 100px">Product Name</th>
<th style="width: 100px">Desciription</th>
<th style="width: 100px"></th>
</tr>
</thead>
<tbody>
<tr v-for="item in model.list" v-bind:key="item.id">
<td>{{ item.id }}</td>
<td>{{ item.productName }}</td>
<td>{{ item.descrption }}</td>
<td><button type="button" v-on:click="deleteClick(item.id)">Delete</button></td>
</tr>
</tbody>
</table>
</template>
<script>
import axios from "axios";
export default {
name: "Product",
data: function () {
return {
model: {
productName: "",
descrption: "",
},
list: [],
};
},
methods: {
saveClick() {
axios
.post("http://example.com", this.model)
.then((resp) => {
this.getList();
alert("success" + resp.data.id);
});
},
getList() {
axios.get("http://example.com").then((resp) => {
this.model.list = resp.data;
});
},
deleteClick(id) {
axios.delete("http://example.com" + id).then(() => {
this.getList();
alert("success");
});
}
},
mounted: function () {
this.getList();
},
};
</script>
Related
I would like to filter data in table using checkbox and outoput data will be shown based on checked/unchecked, for example when i'm checked "Show All" will ouput all data, and when i'm unchecked then output only will show some data. but when i'm trying to do this, the result nothing changed when i'm checked
here for vue html:
<div class="col-md-8">
<input type="checkbox" id="checkboxOrder" v-model="checkedValue" value="Onloading Complete" >
<label for="checkboxOrder">Show All</label>
</div>
<table class="table table-bordered">
<thead>
<tr>
<th>#</th>
<th>code</th>
<th>price</th>
<th>status</th>
<th>transporter</th>
<th>driver</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr v-for="(item, index) in showOrderDetail" :key="index">
<td >{{Number(index)+1}}</td>
<td>{{item.code}}</td>
<td>{{formatNumber(item.invoice_price)}}</td>
<td :class="statusBackground(item)">
<template v-if="item.t_tour">
<span v-if="!_.isEmpty(item.t_tour.t_tour_detail)">
{{item.t_tour.t_tour_detail[0].status}}
</span>
<span v-else>Unproccess</span>
</template>
<span v-else>Unproccess</span>
</td>
<td class="bg-warning">{{item.m_transporter ? item.m_transporter.name : 'unproccess'}}</td>
<td>{{driver(item)}}</td>
<td><span class="btn btn-primary" #click="showModal(item.t_tour)"><i class="fas fa-search"></i></span></td>
</tr>
</tbody>
</table>
and my vue.js :
import axios from "axios";
import accounting from "accounting";
import ShowTourDetail from "~/pages/transaction/order/ShowTourDetail";
export default {
props: {
rowData: {
type: Object,
required: true
},
rowIndex: {
type: Number
}
},
data() {
return {
t_order_detail: {},
checkedValue:[]
};
},
mounted() {
this.fetchData();
},
computed:{
showOrderDetail(){
if(!this.checkedValue.length)
return this.t_order_detail
return this.t_order_detail.filter(o => this.checkedValue.includes(o.t_tour.t_tour_detail[0].status))
}
},
methods: {
async fetchData() {
this.t_order_detail = {
...(
await axios.get(`/api/order-details`, {
params: { t_order_id: this.rowData.id }
})
).data
};
}
};
You can apply change method like :
<input type="checkbox" :value="mainCat.merchantId" id="mainCat.merchantId" v-model="checkedCategories" #change="check($event)">
Methos like:
methods: {
check: function(e) {
if(e.target.checked){
console.log("load all data using service");
// service call here
}else{
console.log("load required data using service");
// service call here
}
}
}
I'm a trying realtime data using socket.io but code isn't working. I'm inserting test data with connection API using postman.
How to view data in realtime without refresh in the browser?
Realtime data in file KritikList.vue
Below is my code.
Node Js Server:
io.on('connection', (client) => {
console.log('user is connected with id: ' + client.id);
client.on('SEND_MESSAGE', function(data) {
io.emit('kirim_data', 'Get you right back...')
console.log(data);
});
client.on('event', (data) => {
console.log('data masuk', data);
});
client.on('disconnect', () => {
console.log('disconnected');
});
});
Controller Node Js Server:
exports.create = (req, res) => {
// Validate request
if (!req.body.nama) {
res.status(400).send({
message: 'Nama tidak boleh kosong!',
});
return;
}
if (!req.body.alamat) {
res.status(400).send({
message: 'Alamat tidak boleh kosong!',
status: 400,
});
} else if (!req.body.nohp) {
res.status(400).send({
message: 'No. Telp tidak boleh kosong!',
status: 400,
});
} else if (!req.body.jenis_kritikan) {
res.status(400).send({
message: 'Jenis kritikan tidak boleh kosong!',
status: 400,
});
} else if (!req.body.isi_kritikan) {
res.status(400).send({
message: 'Isi kritikan tidak boleh kosong!',
status: 400,
});
} else {
// Create a kritik
const kritik = {
nama: req.body.nama,
alamat: req.body.alamat,
nohp: req.body.nohp,
jenis_kritikan: req.body.jenis_kritikan,
isi_kritikan: req.body.isi_kritikan,
is_accept: req.body.is_accept ? req.body.is_accept : false,
};
// Save kritik
Kritik.create(kritik)
.then((data) => {
res.send({ message: 'Kritik anda telah tersampaikan', status: 200 });
})
.catch((err) => {
res.status(500).send({
message: err.message || 'Error saat simpan kritik.',
});
});
}
};
Vue Js (index.html)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>Go-Mas App || Kritik dan Saran</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<link rel="shortcut icon" type="image/png" href="./page.png">
<link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap/dist/css/bootstrap.min.css" />
<script src="./socket.io/socket.io.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"> </script>
<script>
$(document).ready(function() {
var socket = io();
socket.emit('kirim_data');
socket.on('SEND_MESSAGE', function(msg) {
$("#app").append(msg + '<br /><br />');
});
});
</script>
</head>
<body>
<div id="app"></div>
</body>
</html>
Vue Js (App.vue)
<template>
<div>
<div id="app">
<nav class="navbar navbar-expand navbar-dark bg-info">
<router-link to="/" class="navbar-brand">Go-Mas App</router-link>
<div class="navbar-nav mr-auto">
<li class="nav-item">
<router-link to="/kritik" class="nav-link">Kritik</router-link>
</li>
<li class="nav-item">
<router-link to="/saran" class="nav-link">Saran</router-link>
</li>
</div>
</nav>
<div class="container mt-3">
<router-view />
</div>
</div>
</div>
</template>
<script src="/socket.io/socket.io.js"></script>
<script>
export default {
name: "app",
sockets: {
connect() {
console.log("server connected");
},
disconnect() {
console.log("server disconnected");
}
},
mounted() {
this.sockets.subscribe("SEND_MESSAGE", data => {
this.$socket.emit("data");
console.log(data);
});
this.sockets.unsubscribe("SEND_MESSAGE");
},
created() {
this.sockets.subscribe("SEND_MESSAGE", data => {
this.$socket.emit("data");
console.log(data);
});
this.sockets.unsubscribe("SEND_MESSAGE");
}
};
</script>
<style>
footer {
position: fixed;
height: 40px;
bottom: 0;
width: 100%;
}
</style>
Vue Js (KritikList.vue)
<template>
<div>
<div class="row">
<div class="col-md-6">
<h5 style="color:red">Cari data</h5>
<div class="input-group mb-3">
<input
type="text"
class="form-control"
placeholder="Search by jenis kritikan"
v-model="jenis_kritikan"
/>
<div class="input-group-append">
<button
class="btn btn-outline-secondary"
type="button"
#click="searchRowData"
>
Search
</button>
</div>
</div>
</div>
</div>
<br />
<div class="row">
<div class="col-md-4">
<h5 style="color:red">Kritik List</h5>
<ul class="list-group">
<li
class="list-group-item"
:class="{ active: index == currentIndex }"
v-for="(kritik, index) in kritiks"
:key="index"
#click="setActiveKritik(kritik, index)"
>
{{ kritik.nama }}
</li>
</ul>
</div>
<div class="col-md-8">
<div v-if="currentKritik">
<h5 style="color:red">Kritik Detail</h5>
<table width="100%">
<tr>
<td style="font-size:15px" width="20%"><strong>Nama </strong></td>
<td>:</td>
<td>{{ currentKritik.nama }}</td>
</tr>
<tr>
<td style="font-size:15px"><strong>Alamat </strong></td>
<td>:</td>
<td>{{ currentKritik.alamat }}</td>
</tr>
<tr>
<td style="font-size:15px"><strong>No. Telp </strong></td>
<td>:</td>
<td>{{ currentKritik.nohp }}</td>
</tr>
<tr>
<td style="font-size:15px"><strong>Jenis Kritikan </strong></td>
<td>:</td>
<td>{{ currentKritik.jenis_kritikan }}</td>
</tr>
<tr>
<td style="font-size:15px"><strong>Isi Kritikan </strong></td>
<td>:</td>
<td>{{ currentKritik.isi_kritikan }}</td>
</tr>
<tr>
<td style="font-size:15px"><strong>Status </strong></td>
<td>:</td>
<td>
<b
v-if="currentKritik.is_accept == 0"
class="badge badge-danger mr-2"
>Proses</b
>
<b v-else class="badge badge-primary mr-2">Selesai</b>
</td>
</tr>
</table>
<br />
<td v-if="currentKritik.is_accept"></td>
<td v-else>
<h5 style="color:red">Action</h5>
<p class="mt-1"></p>
<img
width="50px"
#click="updateStatus(true)"
src="../../assets/okcek.png"
alt="Proses Selesai"
/>
<label style="font-size:14px">Proses Selesai</label>
</td>
</div>
<div v-else>
<br />
<p>Klik untuk melihat detail...</p>
</div>
</div>
</div>
</div>
</template>
<script src="/socket.io/socket.io.js"></script>
<script>
import KritikDataService from "../../services/KritikDataService";
export default {
name: "data-connected",
sockets: {
connect() {
console.log("server connected");
},
disconnect() {
console.log("server disconnected");
}
},
data() {
return {
kritiks: [],
currentKritik: null,
currentIndex: -1,
jenis_kritikan: ""
};
},
mounted() {
this.sockets.subscribe("SEND_MESSAGE", data => {
this.$socket.emit("data");
console.log(data);
});
this.sockets.unsubscribe("SEND_MESSAGE");
},
created() {
this.sockets.subscribe("SEND_MESSAGE", data => {
this.$socket.emit("data");
console.log(data);
});
this.sockets.unsubscribe("SEND_MESSAGE");
},
methods: {
async retreiveKritik() {
KritikDataService.getAll()
.then(response => {
this.kritiks = response.data;
// console.log(response.data);
})
.catch(e => {
console.log(e);
});
},
refreshList() {
this.retreiveKritik();
this.currentKritik = null;
this.currentIndex = -1;
},
setActiveKritik(kritik, index) {
this.currentKritik = kritik;
this.currentIndex = index;
},
searchRowData() {
KritikDataService.findByJenisKritikan(this.jenis_kritikan)
.then(response => {
this.kritiks = response.data;
// console.log(response.data);
})
.catch(e => {
console.log(e);
});
}
},
mounted() {
this.retreiveKritik();
}
};
</script>
<style>
.list {
text-align: left;
width: 100%;
margin: 2px 12px 6px 20px;
}
</style>
trying to fetch data returnd my url in axios function. but the data is not showing up.
console.log return data with this format
this is my code
<tbody>
<tr v-for="val in values">
<td style="width: 25%" class="text-center">{{ val.id }}</td>
<td style="width: 25%" class="text-center">{{ val.value }}</td>
<td style="width: 25%" class="text-center">{{ val.price }}</td>
<td style="width: 25%" class="text-center">
<button class="btn btn-sm btn-primary">
<i class="fa fa-edit"></i>
</button>
<button class="btn btn-sm btn-danger">
<i class="fa fa-trash"></i>
</button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
name: 'attribute-values',
props: ['attributeid'],
data() {
return {
values: [],
value: '',
price: '',
currentId: '',
addValue: true,
key: 0,
}
},
mounted(){
this.loadValues();
},
methods: {
loadValues() {
let attributeId = this.attributeid;
axios.post('/admin/attributes/get-values', {
id: attributeId
}).then (response => {
console.log('hello');
let result = response.data;
this.values=result;
console.log(this.values);
return this.values;
}).catch(error => {
console.log(error);
});
},
}
}
</script>
the value array is returned correctly but still cant fetch it in my table.
any idea. thank you in advance.
It's likely caused by the use of this within an arrow function in your response handler. Per the Vue docs:
Don’t use arrow functions on an options property or callback
Try changing:
then (response => {
to:
then (function(response) {
I had similar problem therefore i will share partially my code, hopefully it will help.
> <ul>
> <li v-for="meeting in meet" :key="meeting.meeting">{{ meeting.meeting }}</li>
> </ul>
> </div>
>
>
here meetingName is from Json and this.meeting is fromfunction
> data: () => {
> return {
> meet: this.meeting,
> date: this.date,
> meetingName: this.meeting,
};
},
methods: {
> async Today() {
> await axios
> .get("http://localhost:3001/today")
> .then((response) => (this.meet = response.data))
> .catch((err) => (this.meet = "No DB connection"));
> return this.meet;
> },
I have a HTML table in which in one component I have table head and other stuff and in other component I have tbody so in every row of tbody I am adding a delete row button which I want to delete but the data is in theadcomponent there is no parent-child relation here so how can I do this.
My code
Vue.component("form-row", {
template: "#row-template",
props: {
itemname: String,
quantity: Number,
sellingprice: Number,
amount: Number
},
methods: {
delete() {
alert("tedt")
}
},
computed: {
quantitySynced: {
get() {
return this.quantity;
},
set(v) {
this.$emit("update:quantity", +v);
}
},
sellingpriceSynced: {
get() {
return this.sellingprice;
},
set(v) {
this.$emit("update:sellingprice", +v);
}
},
amountSynced() {
this.$emit("update:amount", parseFloat(this.quantity) * parseFloat(this.sellingprice));
return this.amount
}
}
});
new Vue({
el: "#app",
data() {
return {
tableDatas: []
};
},
methods: {
btnOnClick(v) {
this.tableDatas.push({
itemname: "item",
quantity: 1,
sellingprice: 55,
amount: 55
});
}
},
computed: {
calculate() {
return (
this.tableDatas.reduce((total, {
amount
}) => total + amount, 0) || 0
);
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<button type="button" #click="btnOnClick">Add</button>
<table class="table table-striped table-hover table-bordered mainTable" id="Table">
<thead>
<tr>
<th class="itemName">Item Name</th>
<th>Quantity</th>
<th>Selling Price</th>
<th>Amount</th>
</tr>
</thead>
<tbody>
<form-row v-for="(row, key) in tableDatas" :key="key" v-bind.sync="row"></form-row>
</tbody>
</table>
<div>
<label>Total Row's Amount</label>
<input type="text" disabled :value="calculate">
</div>
</div>
<script type="text/x-template" id="row-template">
<tr>
<td>
<input class="form-control" readonly :value="itemname" />
</td>
<td>
<input class="form-control text-right" type="number" min="0" step="1" v-model="quantitySynced" />
</td>
<td>
<input class="form-control text-right" type="number" min="0" step=".5" v-model="sellingpriceSynced" />
</td>
<td>
<input readonly class="form-control text-right" type="number" min="0" step="1" :value="amountSynced" />
</td>
<td>
<button>Delete</button>
</td>
</tr>
</script>
Here I have two components In one component delete button is the I know how to delete the row in same component by using this:
delete(index) {
console.log("Removing", index);
this.tableDatas.splice(index, 1);
}
Vue Mixins will work for your problem.
Mixins are a flexible way to distribute reusable functionalities for Vue components. A mixin object can contain any component options. When a component uses a mixin, all options in the mixin will be “mixed” into the component’s own options.
Here is an example;
// define a mixin object
var myMixin = {
created: function () {
this.hello()
},
methods: {
hello: function () {
console.log('hello from mixin!')
}
}
}
// define a component that uses this mixin
var Component = Vue.extend({
mixins: [myMixin]
})
var component = new Component() // => "hello from mixin!"
Use the Shared events to catch between parent to component
var sharedEvents = new Vue();---declare on top of the vue instance
//parent
new Vue({
el: "#app",
---code--
methods:
getData(){
//emit the data in parent like this
sharedEvents.$emit('forceInjectGridData', {id: "billing-grid", data: data});
}
});
And catch the data in component like below wherever you want:
methods:{
forceInjectGridData(v) {
if (this.id === v.id) {
this.gridData = v.data;
//do your coding here
}
},
} ,
mounted(){
sharedEvents.$on('forceInjectGridData', this.forceInjectGridData);
}
I have a form which is have hidden input. There is a small list of my data. Just has title and id. This list created by vue component. I want to click this list items then change to hidden input value. Here is my structure.
HTML
<div id="v-account-select">
<form method="post">
{!! csrf_field() !!}
<input type="hidden" name="id" v-model="account_id">
</form>
<account-select :datalist="{{ json_encode($list) }}"></account-select>
</div>
APP.JS
Vue.component("account-select", {
datalist: {
type: Array,
required: true,
},
methods: {
item_id_bind(id) {
this.$emit("#account_id", id);
},
},
template:
'<table class="table table-responsive table-striped table-bordered">' +
"<tbody>" +
'<tr v-for="item in datalist"><td>' +
'<button type="button" class="btn-link" v-on:click="item_id_bind(item.id)">{{item.title}}</button>' +
"</td></tr>" +
"</tbody>" +
"</table>",
});
This is my codes.
Add an event handler.
<account-select #account-change="onAccountChange" :datalist="{{ json_encode($list) }}"></account-select>
In your parent Vue add
methods:{
onAccountChange(id){
this.account_id = id
}
}
And update your component to
methods: {
item_id_bind(id) {
this.$emit("account_change", id)
}
},
Here is a working example.
console.clear()
Vue.component('account-select', {
props: {
datalist: {
type: Array,
required: true
}
},
methods: {
item_id_bind(id) {
this.$emit("account-change", id)
}
},
template:`
<table class="table table-responsive table-striped table-bordered">
<tbody>
<tr v-for="item in datalist" :key="item.id">
<td>
<button type="button"
class="btn-link"
v-on:click="item_id_bind(item.id)">
{{item.title}}
</button>
</td>
</tr>
</tbody>
</table>
`
});
new Vue({
el: "#app",
data: {
datalist: [{
id: 1,
title: "item1"
}, {
id: 2,
title: "item2"
}],
account_id: null
},
methods: {
onAccountChange(id) {
this.account_id = id
}
}
})
<script src="https://unpkg.com/vue#2.2.6/dist/vue.js"></script>
<div id="app">
<div id="v-account-select">
<form method="post">
Current Account id: {{account_id}}
<input type="hidden" name="id" v-model="account_id">
</form>
<account-select #account-change="onAccountChange" :datalist="datalist"></account-select>
</div>
</div>