i I want to insert my my in database.axios is perfect and enter data in db but I want a message 'data is entered' for the user ->
how it is important to insert the message.
thanks
<form>
<div class="well">
<h4> Add User</h4>
<div class="form-group">
<label class="pull-left"> First Name </label>
<input type="text" class="form-control" placeholder="First Name" v-model="User.first_name">
</div>
<div class="form-group">
<label class="pull-left"> Last Name </label>
<input type="text" class="form-control" placeholder="Last Namen" v-model="User.last_name">
</div>
<div class="form-group">
<label class="pull-left"> Email </label>
<input type="text" class="form-control" placeholder="Email " v-model="User.email">
</div>
</div>
<button type="submit" class="btn btn-large btn-block btn-primary full-width" #click="addToAPI">Submit</button>
<button class="btn btn-large btn-block btn-success full-width">Go User</button>
</form>
</div>
</template>
<script>
import axios from 'axios'
export default {
name: 'hello',
data() {
return {
msg: 'Welcome to Your Vue.js App',
User: { first_name: '', last_name: '', email: '' }
}
},
methods: {
addToAPI() {
let newUser = {
first_name: this.User.first_name,
last_name: this.User.last_name,
email: this.User.email
}
console.log(newUser)
axios.post('http://localhost:3000/(localaccess)',newUser)
.then(response => {
console.log('success:', response)
})
.catch(error => {
console.log('error:', error)
})
}
}
}
</script>
Add a data object where you will store the message, like:
<script>
import axios from 'axios'
export default {
name: 'hello',
data() {
return {
msg: 'Welcome to Your Vue.js App',
User: { first_name: '', last_name: '', email: '' },
message: ''
}
},
methods: {
addToAPI() {
let self = this;
let newUser = {
first_name: this.User.first_name,
last_name: this.User.last_name,
email: this.User.email
}
axios.post('http://localhost:3000/(localaccess)',newUser)
.then(response => {
self.message = 'Data is entered'
})
.catch(error => {
self.message = 'Error'
})
}
}
}
</script>
And now add it to some place ih your template - {{message}}.
Related
I just started learning Angular and everything is pretty new to me. I have started a course and I got stuck with one part. When I try to do two way property binding, the ngModel is not working as expected.
This is the user.component.ts file:
import { Component, OnInit } from '#angular/core';
import { User } from '../../models/User';
#Component({
selector: 'app-users',
templateUrl: './users.component.html',
styleUrls: ['./users.component.css'],
})
export class UsersComponent implements OnInit {
user: User = {
firstName: '',
lastName: '',
age: 0,
address: {
street: '',
city: '',
state: ''
}
}
users: User[];
showExtended: boolean = true;
loaded: boolean = false;
enableAdd: boolean = true;
showUserForm: boolean = false;
constructor() {
this.users = this.getUserDefaults();
}
ngOnInit(): void {
this.loaded = true;
}
private getUserDefaults() {
return [
{
firstName: 'John',
lastName: 'Doe',
age: 65,
address: {
street: '50 Main st',
city: 'Boston',
state: 'MA',
},
isActive: true,
registered: new Date('01/02/2018 08:30:00'),
hide: true
},
{
firstName: 'Kevin',
lastName: 'Johnson',
age: 34,
address: {
street: '20 School st',
city: 'Lynn',
state: 'MA',
},
isActive: false,
registered: new Date('03/11/2017 06:20:00'),
hide: true
},
{
firstName: 'Karen',
lastName: 'Williams',
age: 26,
address: {
street: '55 Mill st',
city: 'Miami',
state: 'FL',
},
isActive: true,
registered: new Date('11/02/2016 10:30:00'),
hide: true
},
];
}
addUser(user: User) {
this.users.push(user);
}
// toggleHide(user: User) {
// user.hide = !user.hide;
// }
onSubmit(e: any) {
console.log(123)
e.preventDefault()
}
fireEvent(e: any) {
console.log(e.type)
console.log(e.target.value)
}
}
This is the users.component.html file
<button (click)="showUserForm = !showUserForm" class="btn btn-dark mb-3">Add User</button>
<div class="card card-body mb-3" *ngIf="showUserForm">
<h2>Add User</h2>
<form (submit)="onSubmit($event)">
<div class="form-group">
<label>First Name</label>
<input type="text" class="form-control" name="firstName" [(ngModel)]="user.firstName">
</div>
<div class="form-group">
<label>Last Name</label>
<input type="text" class="form-control" name="lastName" [(ngModel)]="user.lastName">
</div>
<div class="form-group">
<label>Age</label>
<input type="number" class="form-control" name="age" [(ngModel)]="user.age">
</div>
<div class="form-group">
<label>Street Address</label>
<input type="text" class="form-control" name="street" [(ngModel)]="user.address.street">
</div>
<div class="form-group">
<label>City</label>
<input type="text" class="form-control" name="city" [(ngModel)]="user.address.city">
</div>
<div class="form-group">
<label>State</label>
<input type="text" class="form-control" name="state" [(ngModel)]="user.address.state">
</div>
<button (click)="addUser({ firstName: 'Mary', lastName: 'Jackson', isActive:true})" [disabled]="!enableAdd" class="btn btn-block mb-3">
Add New User
</button>
</form>
</div>
<h2>Users</h2>
<ul class="list-unstyled" *ngIf="loaded && users.length > 0">
<li class="card card-body mb-2" *ngFor="let user of users" [class.bg-light]="user.isActive">
<h3>{{ user.firstName }} {{ user.lastName }} <small *ngIf="user.age && user.address"><button (click)="user.hide = !user.hide" class="btn btn-dark btn-sm"><i [ngClass]="user.hide ? 'fa fa-plus' : 'fa fa-minus'" class="fa fa-plus"></i></button></small></h3>
<ul class="list-group" *ngIf="!user.hide && user.age && user.address">
<li class="list-group-item">Age: {{ user.age }}</li>
<li class="list-group-item">
Address: {{ user.address.street }}, {{ user.address.city }},
{{ user.address.state }}
</li>
<li class="list-group-item">Joined: {{ user.registered | date }}</li>
</ul>
</li>
</ul>
<h4 *ngIf="users.length == 0">No Users Found</h4>
<h4 *ngIf="!loaded">Loading Users...</h4>
And this is the interface
export interface User {
firstName: string,
lastName: string,
age?: number,
address?: {
street?: string,
city?: string,
state?: string
},
isActive?: boolean,
registered?: any,
hide?: boolean
}
In the html file where I have the inputs the ngModel is not working as expected. I am trying to bind these inputs with
user: User = {
firstName: '',
lastName: '',
age: 0,
address: {
street: '',
city: '',
state: ''
}
}
ngModel for firstName, lastName and age works just fine. But when I try to bind ngModel with user.address.street or user.address.city or user.address.state, I get the follwoing error:
Error: src/app/components/users/users.component.html:19:89 - error TS2532: Object is possibly 'undefined'.
19 <input type="text" class="form-control" name="street" [(ngModel)]="user.address.street">
~~~~~~
src/app/components/users/users.component.ts:5:16
5 templateUrl: './users.component.html',
~~~~~~~~~~~~~~~~~~~~~~~~
Error occurs in the template of component UsersComponent.
Does anybody know why is this happening and how to fix this problem? Thank you in advance.
I'm trying to get the sign in part working on my webapp but it's not working properly.
Whenever I press the login button the page either refreshes and the url gets updated with the credentials and stays at the same page OR the router gets pushed and goes to the 'homepage' without logging the user in.
I also followed this guide for reference: https://blog.logrocket.com/vue-firebase-authentication/
What's weird is that the sign up part is working just fine.
SignIn.vue
<div class="card-body">
<form>
<!-- email -->
<div class="input-group form-group">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fas fa-user"></i></span>
</div>
<input id="email" type="email" class="form-control" name="email" placeholder="e-mail" value required autofocus v-model="form.email" />
</div>
<!-- password -->
<div class="input-group form-group">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fas fa-key"></i></span>
</div>
<input id="password" type="password" class="form-control" name="password" placeholder="password" required v-model="form.password" />
</div>
<!-- error -->
<div v-if="error" class="alert alert-danger animated shake">{{ error }}</div>
<br />
<!-- login -->
<div class="form-group d-flex justify-content-between">
<div class="row align-items-center remember"><input type="checkbox" v-model="form.rememberMe" />Remember Me</div>
<input type="submit" #click="submit" value="Login" class="btn float-right login_btn" />
</div>
</form>
</div>
Script in SignIn.vue
<script>
import firebase from 'firebase';
export default {
data() {
return {
form: {
email: '',
password: '',
rememberMe: false
},
error: null
};
},
methods: {
submit() {
firebase
.auth()
.signInWithEmailAndPassword(this.form.email, this.form.password)
.catch(err => {
this.error = err.message;
})
.then(data => {
this.$router.push({ name: 'home' });
});
}
}
};
</script>
Store.js
import Vue from 'vue';
import Vuex from 'vuex';
import profile from './modules/profile';
import authenticate from './modules/authenticate';
Vue.use(Vuex);
export default new Vuex.Store({
modules: {
profile,
authenticate
}
});
Authenticate.js in store
const state = {
user: {
loggedIn: false,
data: null
}
};
const getters = {
user(state) {
return state.user;
}
};
const mutations = {
SET_LOGGED_IN(state, value) {
state.user.loggedIn = value;
},
SET_USER(state, data) {
state.user.data = data;
}
};
const actions = {
fetchUser({ commit }, user) {
commit('SET_LOGGED_IN', user !== null);
if (user) {
commit('SET_USER', {
displayName: user.displayName,
email: user.email
});
} else {
commit('SET_USER', null);
}
}
};
export default {
state,
mutations,
actions,
getters
};
It is probably because you assign the submit type to your button, your form is submitted before the Firebase method is triggered.
You should change the button code from
<input type="submit" #click="submit" value="Login" class="btn float-right login_btn" />
to
<input type="button" #click="submit" value="Login" class="btn float-right login_btn" />
See the W3 specification for more detail on button types.
<template>
<div>
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" v-model="firstName" placeholder="Enter your name">
</div>
<div class="form-group">
<label for="lastName">Last name</label>
<input type="text" class="form-control" v-model="lastName" placeholder="Enter your last name">
</div>
<div class="form-group">
<label for="message">Type Your message</label>
<textarea class="form-control" v-model="message" rows="3"></textarea>
</div>
<div class="form-group form-check" v-for="number in numbers" :key="number">
<input type="checkbox" :value="number.Broj" v-model="checkedNumbers">
<label class="form-check-label" >{{number.Broj}}</label>
</div>
<button type="submit" class="btn btn-primary" #click="sendMessage">Send message</button>
</div>
</template>
<script>
import http from "../http-common.js";
import userServices from "../services/userServices.js";
export default {
data()
{
return {
firstName: null,
lastName: null,
message: null,
numbers: "",
checkedNumbers: [],
};
},
methods:
{
async sendMessage()
{
await http.post("/message", {firstName: this.firstName, lastName: this.lastName, message: this.message, numbers: this.checkedNumbers});
this.$data.firstName = "",
this.$data.lastName = "",
this.$data.checkedNumbers = [],
this.$data.message = "";
},
retrieveNumbers() {
userServices.getNumbers().then(response => {
this.numbers = response.data;
console.log(response.data);
})
.catch(e => {
console.log(e);
});
}
},
created() {
this.retrieveNumbers();
}
}
</script>
How can I add success message to the user after clicking Send message button? For example "Message sent"
I have a perfectly working form I can insert data into database and through the form, writing data into text file. using axios after form validation. I am just struggling to show a success message after user clicks the button.
Thank you
You can do something after the Promise is returned, like :
await http.post("/message", {firstName: this.firstName, lastName: this.lastName, message: this.message, numbers: this.checkedNumbers}).then((response) => {
// Do something with the response
})
Then, you can pop a swal from SweetAlert documentation with the message you want to show.
I need to clear my inputs in modal after my data saved successfully, I've tried several solution I found here such as reset() or myData = ''; but none of them worked for me.
Code
Vue method
submit: function(e) {
axios.post('/api/saveVerse', this.verse)
.then(res => {
this.isLoading = false
$('#exampleModal').modal('toggle');
this.getVerses.push( res.data.verse );
})
.catch(error => {
this.errors = error.response.data.errors
this.isLoading = false
})
},
Vue Template
<form #submit.prevent="submit" class="needs-validation" novalidate>
<div class="modal-body">
<div class="form-row">
<div class="col-md-3 mb-3">
<label for="validationTooltip01">Verse Number</label>
<input type="text" class="form-control" id="validationTooltip01" v-model="verse.number" placeholder="Verse Number" required>
<div class="invalid-tooltip">
Verse Number Is Required.
</div>
</div>
<div class="col-md-9 mb-3">
<label for="validationTooltip01">Heading</label>
<input type="text" class="form-control" id="validationTooltip01" v-model="verse.heading" placeholder="Verse Heading">
<div class="valid-tooltip">
Heading Looks Good!
</div>
</div>
<div class="col-md-12 mb-3">
<label for="validationTooltip02">Verse</label>
<textarea name="body" class="form-control" id="validationTooltip02" v-model="verse.body" placeholder="Verse" cols="15" rows="5" required></textarea>
<div class="invalid-tooltip">
Verse Body Is Required.
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-success">Save</button>
</div>
</form>
Any idea?
Update
How I get my form data...
data() {
return {
//...
verse: {
number: '',
heading: '',
body: '',
book_id: '',
chapter_id: '',
}
}
},
try to bind the response like below.and verify please
submit: function(e) {
axios.post('/api/saveVerse', this.verse)
.then(res => {
this.isLoading = false
$('#exampleModal').modal('toggle');
this.getVerses.push( res.data.verse );
// resetting your v-model:
this.verse = {
number: '',
heading: '',
body: ''
};
}).bind(this)
.catch(error => {
this.errors = error.response.data.errors
this.isLoading = false
})
},
You can do something like this:
submit: function(e) {
axios.post('/api/saveVerse', this.verse)
.then(res => {
this.isLoading = false
$('#exampleModal').modal('toggle');
this.getVerses.push( res.data.verse );
// resetting your v-model:
this.verse = {
number: '',
heading: '',
body: ''
};
// Try this also...
e.preventDefault();
})
.catch(error => {
this.errors = error.response.data.errors
this.isLoading = false
})
},
import React, { Component } from 'react';
import { Link } from 'react-router'
class Modals extends Component {
constructor(props){
super(props);
this.state = {inputuuid: '',
inputmajor: '' ,
inputminor: '' ,
inputmanufacturer: ''};
this.handleUuid = this.handleUuid.bind(this);
this.handleMajor = this.handleMajor.bind(this);
this.handleMinor = this.handleMinor.bind(this);
this.handleManufacturer = this.handleManufacturer.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
alert("started");
fetch("http://api-env.bt2qjip33m.ap-south-1.elasticbeanstalk.com/api/v1/beacons" ,
{
method: 'post',
headers: {
'Content-Type': 'application/json',
'Authorization' : 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI1OGMyOTdiOWQzZWM4NjY4MDMwNDBlNjgiLCJlbWFpbCI6ImtrQGxpdGlmZXIuY29tIiwiZmlyc3ROYW1lIjoiS2lzaGxheSIsImxhc3ROYW1lIjoiS2lzaG9yZSIsImlhdCI6MTQ4OTE0NzgzM30.nHW5w3SSov8ySziblmw2VNlGI3CsZFR-v41Jeg9uBVs'
},
body: JSON.stringify({
name: "beacon name 1234",
description: "beacon description here for beacon",
uuid: "this.state.inputuuid1",
major: "this.state.inputmajor",
minor: "this.state.inputminor",
manufacturer: "this.state.inputmanufacturer",
beaconType: "type9",
location: "main gate8",
floor: "ist",
zone: "58c29c06d3ec866803040e6e"
})
}).then(function(response){
if(response.ok) {
console.log(response)
return response;
}
throw new Error('Network response was not ok.');
}).then(function(data) {
console.log(data);
})
.catch(function(error) {
console.log('There has been a problem with your fetch operation: ' + error);
});
}
handleUuid(event) {
this.setState({inputuuid: event.target.value});
}
handleMajor(event){
this.setState({inputmajor: event.target.value});
}
handleMinor(event){
this.setState({inputminor: event.target.value});
}
handleManufacturer(event){
this.setState({inputmanufacturer: event.target.value});
}
handleSubmit(event) {
alert('Submitted: ' + this.state.inputuuid + this.state.inputmajor + this.state.inputminor + this.state.inputmanufacturer);
event.preventDefault();
}
render() {
return (<div><div>
<div className="animated fadeIn">
<br /><div className="card" style={{ width: 57 + '%' }}>
<div className="card-header">
Beacon Settings
</div>
<div className="card-block">
<div className="input-group mb-1">
<span className="input-group-addon"><i className="icon-user"></i></span>
<input type="text" className="form-control" value={this.state.inputuuid} onChange={this.handleUuid} placeholder="UUID" />
</div>
<div className="input-group mb-1">
<span className="input-group-addon"><i className="fa fa-align-justify"></i></span>
<input type="text" className="form-control" value={this.state.inputmajor} onChange={this.handleMajor} placeholder="Major Number"/>
</div>
<div className="input-group mb-1">
<span className="input-group-addon"><i className="fa fa-align-justify"></i></span>
<input type="text" className="form-control" value={this.state.inputminor} onChange={this.handleMinor} placeholder="Minor Number"/>
</div>
<div className="input-group mb-1">
<span className="input-group-addon"><i className="fa fa-align-justify"></i></span>
<input type="text" className="form-control" value={this.state.inputmanufacturer} onChange={this.handleManufacturer} placeholder="Manufacturer Number"/>
</div><center>
<Link to={'/components/tabs'} style={{ width: 27 + '%' }} className="nav-link btn btn-block btn-success" onClick={this.handleSubmit} activeClassName="active">Save</Link>
<Link to={'/components/tabs'} style={{ width: 27 + '%' }} className="nav-link btn btn-block btn-success" activeClassName="active">Advance Settings</Link>
</center>
</div>
</div>
</div></div>
</div>
)
}
}
export default Modals;
i had taken the user inputs now i want to send them to the server using POST request which i can not able to send.
i am only getting the values by the user and those can be seen by the alert i had put in that but can't able to send to the server
Try using following way
fetch('https://mywebsite.com/endpoint/', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
firstParam: 'yourValue',
secondParam: 'yourOtherValue',
})
});
React require stringify post body data
You can create your inputField like this:
<input className="form-control" type="text" value={this.state.userData.firstName} required placeholder="First Name" onChange={this.handleChange.bind(this, 'firstName')} />
In your form component, you can define userData state object in this way:
this.state = {
userData: {
firstName: null,
lastName: null,
...
}
}
And for handleChange(), we can make it to accept dynamic keys for state variables:
handleChange(key, e, value){
let data = this.state.userData;
userData[key] = e.target.value;
this.setState({
userData: data
});
}
All you need to post then is this.state.userData.