Data variable gets undefined in Vue after submit - javascript

I have defined isError as false in data, however once there is an error from laravel i get the 422 error. I would like to then define isError as true but when i do it i get an error from the console saying that iserror is undefined even though it has been defined. What is the problem?
The error is as per below:
app.js:1925 Uncaught (in promise) ReferenceError: isError is not defined
Thanks
<template>
<div class="contact-section">
<div class="container">
<div class="section-content row">
<div class="contact-text col-lg-6">
<div class="text-box">
<h1 class="subtitle text-white">Contact</h1>
<h2 class="text-white"> Have You Any Project? <br> Please Drop a Message </h2>
<p class="text-white"> Get in touch and let me know how i can help. Fill out the form and i’ll be in touch as soon as possible. </p>
</div>
<ul class="contact-info">
<li>
<img src="assets/images/icons/email.png" alt="Email">
<div>
<strong>Email:</strong>
<ul>
<li>info#nafie.com</li>
</ul>
</div>
</li>
</ul>
</div>
<div class="col-lg-6">
<form class="contact-form form-styled" #submit.prevent="send">
<div class="group">
<label>Name</label>
<div class="control has-prefix-icon">
<input type="text" name="name" placeholder="e.g. John Doe" minlength="3" v-model="form.name">
</div>
</div>
<div class="group">
<label>Email</label>
<div class="control has-prefix-icon">
<input class="ltr-dir" type="email" name="email" placeholder="e.g. john.doe#gmail.com" v-model="form.email">
</div>
</div>
<div class="group">
<label>Message</label>
<div class="control has-prefix-icon">
<textarea name="message" placeholder="Write message..." v-model="form.message"></textarea>
</div>
</div>
<div class="group">
<p v-if="isError" class="error large">All fields are required</p>
<div class="control"><button class="submit-btn btn btn-dark" type="submit">Send</button></div>
</div>
</form>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
data: function() {
return {
form: {
email: '',
message: '',
name: ''
},
errors: {},
isError: false
}
},
methods: {
send: function() {
// Reset is error
this.isError = false;
axios.post("/send", this.form)
.then(function (response) {
// Reset form on success
this.form.name = '';
this.form.email = '';
this.form.message = '';
console.log(response);
})
.catch(function (error) {
// Says here undefined?
this.isError = true;
console.log(error);
console.log(error.response.data.errors);
});
}
}
}
</script>

send: function()
{
// Reset is error
this.isError = false;
let self = this;
axios.post("/send", this.form).then(function(response)
{
// Reset form on success
self.form.name = '';
self.form.email = '';
self.form.message = '';
console.log(response);
}).catch(function(error)
{
// Says here undefined?
self.isError = true;
console.log(error);
console.log(error.response.data.errors);
});
}

Related

Cannot read property 'stripeTokenHandler' of undefined vuejs component

I am building a payment form with vuejs, it included stripe js.
This is my card elements:
<!-- CARD form -->
<label class="mt-5 font-20px"> Tarjeta </label>
<div class="mt-4"> Número </div>
<div class="row mt-2">
<div class="col-md-12">
<div id="card-number-element" class="form-control rounded-pill" placeholder="**** **** **** ****"> </div>
</div>
</div>
<div class="row">
<div class= "col-md-6 mt-3">
<span> Nombre de la Tarjeta </span></br>
<input type="input" id="card-name-element" class="form-control rounded-pill" placeholder ="Juan Pérez"> </input>
</div>
<div class= "col-md-3 col-6 mt-3">
<span> Expiración </span></br>
<div id="card-expiry-element" class="form-control rounded-pill" placeholder ="MM / YY"> </div>
</div>
<div class= "col-md-3 col-6 mt-3">
<span> CCV </span></br>
<div id="card-cvc-element" class="form-control rounded-pill" placeholder ="***"> </div>
</div>
</div>
<div class="row mt-3">
<div id="card-error text-danger"></div>
<div id="card-success">
Your Stripe token is <span class="token text-success"></span>
</div>
</div>
I initialized stripe elements in mounted function:
initStripeElements(){
cardNumberElement = elements.create('cardNumber', { placeholder: '**** **** **** ****', });
cardNumberElement.mount('#card-number-element');
var cardExpiryElement = elements.create('cardExpiry', { placeholder: 'MM / YY', });
cardExpiryElement.mount('#card-expiry-element');
var cardCvcElement = elements.create('cardCvc', { placeholder: '***', });
cardCvcElement.mount('#card-cvc-element');
},
mounted() {
this.initStripeElements();
}
Everything work fine and the stripe card token can be retrieved and returned.
After that I invoke: this.stripeTokenHandler(result.token.id); to send token and data to server
submitForm(e) {
e.preventDefault();
this.submitted = true;
if (this.formInvalid()) {
return;
}
var options = {
name: document.getElementById('card-name-element').value,
};
stripe.createToken(cardNumberElement, options).then(function(result) {
var successElement = document.querySelector('.card-success');
var errorElement = document.querySelector('.card-error');
if (result.token) {
successElement.querySelector('.token').textContent = result.token.id;
this.stripeTokenHandler(result.token.id);
} else if (result.error) {
errorElement.textContent = result.error.message;
}
console.log(this)
});
if (this.cardError) {
return;
}
// this.nextStep();
},
This calling never work as it always show the error:
Finaliza.vue:415 Uncaught (in promise) TypeError: Cannot read property 'stripeTokenHandler' of undefined
Can you please help, what am I wrong here?
By somehow this variable is become undefined inside the stripe scope. So I can solve issue by saving this variable outside the stripe callback.
var context = this;
stripe.createToken(cardNumberElement, options).then(function(result) {
var successElement = document.querySelector('.card-success');
var errorElement = document.querySelector('.card-error');
if (result.token) {
successElement.querySelector('.token').textContent = result.token.id;
context.stripeTokenHandler(result.token.id);
} else if (result.error) {
errorElement.textContent = result.error.message;
}
});

Vue: login validation not working in my code

I'm creating login validation in Vue.js but the error message is not displaying and it gives me the error:
Property or method "error" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property.
Any help?
Template:
<template>
<div class="container" width="900">
<div class="row justify-content-center" style="margin-top: 10px;">
<div class="col-5">
<div v-if="error" class="alert alert-danger" role="alert">
{{error}}
</div>
<div class="card" >
<div class="card-text">
<div class="form-group" #keyup.enter="logItIn">
<input class="form-control"
v-model="login.email"
label="Email"
placeholder="Email Address"
required
> <br>
<input class="form-control"
v-model="login.password"
label="Password"
type="password"
placeholder="Password"
required>
</div>
</div>
<button type="button" class="btn btn-secondary" #click='logItIn'>Login</button>
</div>
</div>
</div>
</div>
</template>
Script:
import axios from 'axios'
export default {
data() {
return {
login: {
email:"",
password:"",
error: ""
}
}
},
methods: {
async logItIn() {
try {
axios.post('https://odevin-api.herokuapp.com/login',this.login)
.then(response => {
console.log(response)
let newToken=response.data.response.token;
window.token=newToken;
let user=response.data.response.user; //response
localStorage.setItem('token',newToken);
localStorage.setItem('user',JSON.stringify(user));
window.axios.defaults.params={api_token:newToken}
// Event.$emit('login',user);
this.$router.push('/');
});
} catch(e) {
this.error = 'invalid user name or password';
}
}
}
}
you referenced {{ error }} in your template but in your data object, error is a property of login object. so vue can't find it properly.
either change the usage in your template to {{ login.error }} or define it in your data object like this:
data() {
return {
error: '',
login: {
email: '',
password: '',
},
}
}

how to set value form input vue js from json

please have a problem here. I want to display the value from the input form: name and position. but the data is in the form of json.
{"id":5,"name":"the name","pos":"the position"}
This is template html vue js
<template>
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">
Edit <b>{{name}}</b>
</div>
<div class="card-body">
<form #submit="edit()" method="post" onclick="return false">
<div class="form-group">
<label for="">Name</label>
<input v-model="input.nameInput" type="text" value="?" autocomplete="off" class="form-control">
</div>
<div class="form-group">
<label for="">Position</label>
<input v-model="input.posInput" value="?" type="text" autocomplete="off" class="form-control">
</div>
<button type="submit" class="btn btn-primary">Edit</button>
</form>
</div>
</div>
</div>
</div>
</div>
</template>
And this is java script of template file vue js
<script>
export default {
data(){
return{
name:'',
pos:'',
input:{
nameInput:'',
posInput:''
}
}
},
methods:{
getEmploye(){
axios.get('/employes_api/'+this.$route.params.id).then(response => {
this.name = response.data.name;
this.pos = response.data.pos;
});
},
edit(){
axios.put('/employes_api/'+this.$route.params.id, {
name: this.name,
pos: this.position,
}).then(response => {
this.$route.employe;
});
}
},
mounted(){
this.getEmploye();
}
}
</script>
Thanks for your help.
As described in your question, if the data received is
{"id":5,"name":"the name","pos":"the position"}
then you getEmploye method should be :
getEmploye(){
axios.get('/employes_api/'+this.$route.params.id).then(response => {
this.name = response.name;
this.pos = response.pos;
});
On element’s value, you may use the following to display data you have received from the api:
value=“{{name}}”
That means you are getting the value from name data.
Also, to test if that works, you may assign first a dummy data/value to name.
You don't need to make two separate variables one for the inputs and the other for the display, just keep the same variable for both, it will be automatically updated on the display and in the inputs while the user is typing, that's the beauty of Vue.
So instead of
data(){
return{
name:'',
pos:'',
input:{
nameInput:'',
posInput:''
}
}
},
Just keep
data(){
return{
name:'',
pos:''
}
},
For the template inputs use :
<input v-model="name" type="text" autocomplete="off" class="form-control">
...
<input v-model="pos" type="text" autocomplete="off" class="form-control">
The overall result should look like this :
<template>
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">
Edit <b>{{name}}</b>
</div>
<div class="card-body">
<form #submit="edit()" method="post">
<div class="form-group">
<label for="">Name</label>
<input v-model="name" type="text" autocomplete="off" class="form-control">
</div>
<div class="form-group">
<label for="">Position</label>
<input v-model="position" type="text" autocomplete="off" class="form-control">
</div>
<button type="submit" class="btn btn-primary">Edit</button>
</form>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
data(){
return{
name:'',
pos:''
}
},
methods:{
getEmploye(){
axios.get('/employes_api/'+this.$route.params.id).then(response => {
this.name = response.data.name;
this.pos = response.data.pos;
});
},
edit(){
axios.put('/employes_api/'+this.$route.params.id, {
name: this.name,
pos: this.pos,
}).then(response => {
this.$route.employe;
});
}
},
created(){
this.getEmploye();
}
}
Ps : Didn't test the code, if there is any error just let me know
Use :value=“name”, e.g <input :value="name"/>.

[Vue warn]: Error in nextTick: "TypeError: Cannot read property 'key' of undefined"

I am fairly new to Vue (and using Vue components in particular), and I can't figure out what i'm doing wrong here. Essentially I have a signup wizard (using vue-good-wizard) which if the user never clicks the back button works fine, but if at some point they click back I get the error message described in the title. I think it has something to do with the following template being rendered a second time:
<template>
<div class="playerSelectionBox">
<table style="width:100%">
<tr v-for="i in 10" track-by="$index">
<td>Row: {{i}}</td>
<td><player-entry-box></player-entry-box></td>
</tr>
</table>
</div>
</template>
Here is the code for the template from the player-entry-box component:
<template>
<div class="PlayerEntryBox">
<input class="numberBox" type="text" #blur="sendData" v-model="number" placeholder="#">
<input class="nameBox" type="text" #blur="sendData" v-model="playerName" placeholder="Player Name"><br>
</div>
</template>
My best guess is that something is happening when the code is rendered where the player-entry-box components inside of the v-for have something which conflicts with the others, but it works as expected the first time it is rendered. Is there something here I am doing wrong?
Any advice or insights into what I am missing would be great, thanks!
Other information:
All of the components are currently registered globally in the main.js file.
Here is the code for the wizard:
<div id="TeamWizard" v-if="isCreatingTeam" style="padding-top=100px;">
<vue-good-wizard
:steps="teamSteps"
:onNext="nextClickedTeam"
:onBack="backClickedTeam">
<div slot="teamPage1">
<label class="myLabel">Team Name:</label>
<input type="text" v-model="teamName" placeholder="Team Name"><br>
<br>
<label class="myLabel">Sport:</label>
<br>
<select-sport :initialSport="tkdSport" style="display: inline-block;" #sportWasSelected="tkdSport=$event"></select-sport>
<h1></h1>
</div>
<div slot="teamPage2">
<h4>Add Players</h4>
<h1></h1>
<player-selection-box></player-selection-box>
</div>
<div slot="teamPage3">
<h4>Step 3</h4>
<label class="myLabel">Team ID:</label>
<input type="text" v-model="teamID" placeholder="Team ID"><br>
<br>
<label class="myLabel">Team Token:</label>
<input type="text" v-model="teamToken" placeholder="Team Token"><br>
<br>
</div>
</vue-good-wizard>
</div>
Here is where I called this.$nextTick():
mounted () {
this.$nextTick(() => {
this.loggedInUser = firebase.auth().currentUser;
});
}
The following is from the main component :
<template>
<div class="hello">
<h1>{{ tkdSport }}</h1>
<div id="mainPage" v-if="!(isCreatingTeam || isCreatingPlayer)">
<div id="mySidenav" class="sidenav">
×
<img src="../assets/images/testUser.png" width="100px" height="100px">
About
Services
Clients
Contact
<div style="scroll">
<div v-for="i in 50">
<div style="margin=10px; color=red;"><p>Test {{ i }}</p></div>
</div>
</div>
</div>
<h1>{{ loggedInUser.email }}</h1>
<button #click="logout">Logout</button>
<button #click="openNav">Open Nav</button>
<br>
<br>
<br>
<br>
<br>
<button #click="showTeam">New Team Account</button>
<br>
<br>
<br>
<button #click="showPlayer">New Player Account</button>
</div>
<div v-else>
<div id="createTeam" v-if="isCreatingTeam">
<h1>TEAM</h1>
<br>
</div>
<div id="createPlayer" v-if="isCreatingPlayer">
<h1>PLAYER</h1>
</div>
<div id="PlayerWizard" v-if="isCreatingPlayer" style="padding-top=100px;">
<div>
<vue-good-wizard
:steps="playerSteps"
:onNext="nextClickedPlayer"
:onBack="backClickedPlayer">
<div slot="playerPage1">
<label class="myLabel">Team Name:</label>
<input type="text" v-model="teamName" placeholder="Team Name"><br>
<br>
<label class="myLabel">Sport:</label>
<br>
<select-sport :initialSport="tkdSport" style="display: inline-block;" #sportWasSelected="tkdSport=$event"></select-sport>
<h1></h1>
</div>
<div slot="playerPage2">
<h4>Add Players</h4>
<h1>Player Selection will go here</h1>
</div>
</vue-good-wizard>
</div>
</div>
<div id="TeamWizard" v-if="isCreatingTeam" style="padding-top=100px;">
<vue-good-wizard
:steps="teamSteps"
:onNext="nextClickedTeam"
:onBack="backClickedTeam">
<div slot="teamPage1">
<label class="myLabel">Team Name:</label>
<input type="text" v-model="teamName" placeholder="Team Name"><br>
<br>
<label class="myLabel">Sport:</label>
<br>
<select-sport :initialSport="tkdSport" style="display: inline-block;" #sportWasSelected="tkdSport=$event"></select-sport>
<h1></h1>
</div>
<div slot="teamPage2">
<h4>Add Players</h4>
<h1></h1>
<player-selection-box></player-selection-box>
</div>
<div slot="teamPage3">
<h4>Step 3</h4>
<label class="myLabel">Team ID:</label>
<input type="text" v-model="teamID" placeholder="Team ID"><br>
<br>
<label class="myLabel">Team Token:</label>
<input type="text" v-model="teamToken" placeholder="Team Token"><br>
<br>
</div>
</vue-good-wizard>
</div>
</div>
</div>
</template>
<script>
import firebase from 'firebase';
export default {
name: 'HelloWorld',
data () {
return {
msg: 'Welcome to Your Vue.js App',
loggedInUser: '',
teamName: '',
teamToken: '',
teamID: '',
playerName: '',
tkdSport: 'basketball',
isCreatingPlayer: false,
isCreatingTeam: false,
playerSteps: [
{
label: 'Name and Sport',
slot: 'playerPage1',
},
{
label: 'Link (OPTIONAL)',
slot: 'playerPage2',
}
],
teamSteps: [
{
label: 'Name and Sport',
slot: 'teamPage1',
},
{
label: 'Add Players',
slot: 'teamPage2',
},
{
label: 'Setup Linking (OPTIONAL)',
slot: 'teamPage3',
}
]
}
},
mounted () {
this.$nextTick(() => {
this.loggedInUser = firebase.auth().currentUser;
});
},
methods: {
logout: function() {
firebase.auth().signOut().then(() => {
this.$router.replace('login')
})
},
openNav: function() {
document.getElementById("mySidenav").style.width = "250px";
},
closeNav: function() {
document.getElementById("mySidenav").style.width = "0";
},
showTeam: function() {
this.isCreatingTeam = true
this.isCreatingPlayer = false
},
hideCreating: function() {
this.isCreatingTeam = false
this.isCreatingPlayer = false
},
showPlayer: function() {
this.isCreatingPlayer = true
this.isCreatingTeam = false
},
onComplete: function() {
alert('Yay. Done!');
},
nextClickedPlayer(currentPage) {
console.log('next clicked', currentPage)
if(currentPage==1){
this.hideCreating()
}
return true; //return false if you want to prevent moving to next page
},
backClickedPlayer(currentPage) {
console.log('back clicked', currentPage);
return true; //return false if you want to prevent moving to previous page
},
nextClickedTeam(currentPage) {
console.log('next clicked', currentPage)
if(currentPage==2){
this.hideCreating()
}
return true; //return false if you want to prevent moving to next page
},
backClickedTeam(currentPage) {
console.log('back clicked', currentPage);
return true; //return false if you want to prevent moving to previous page
}
}
}
</script>
The user logs in from a separate Login Component, and then gets routed to this component, I just need to have access to the user object within this component.
Here is the stack trace:
Error stack trace

AngularJS 1.6.8: Form data not submitting and so hence unable to save it to localStorage

I have a contact form. On submission, it displays a success message and it should store that data to $localStorage.
But, Form data not is not submitting as I do not see submitted form data in response under network in dev tools and hence I am unable to save it to $localStorage.
below is the code for respective files.
link to plunker
contact.html
<div ngController="contactController as vm">
<div class="heading text-center">
<h1>Contact Us</h1>
</div>
<div>
<form class="needs-validation" id="contactForm" novalidate method="post" name="vm.contactForm" ng-submit="saveform()">
<div class="form-group row">
<label for="validationTooltip01" class="col-sm-2 col-form-label">Name</label>
<div class="input-group">
<input type="text" class="form-control" id="validationTooltipName" placeholder="Name" ng-model="vm.name" required>
<div class="invalid-tooltip">
Please enter your full name.
</div>
</div>
</div>
<div class="form-group row">
<label for="validationTooltipEmail" class="col-sm-2 col-form-label">Email</label>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text" id="validationTooltipUsernamePrepend">#</span>
</div>
<input type="email" class="form-control" id="validationTooltipEmail" placeholder="Email"
aria-describedby="validationTooltipUsernamePrepend" ng-model="vm.email" required>
<div class="invalid-tooltip">
Please choose a valid email.
</div>
</div>
</div>
<div class="form-group row">
<label for="validationTooltip03" class="col-sm-2 col-form-label">Query</label>
<div class="input-group">
<input type="text" class="form-control" id="validationTooltipQuery" ng-model="vm.query" placeholder="Query" required>
<div class="invalid-tooltip">
Please write your Query.
</div>
</div>
</div>
<div class="btn-group offset-md-5">
<button class="btn btn-primary" type="submit">Submit</button>
<button class="btn btn-default" type="button" id="homebtn" ng-click="navigate ('home')">Home</button>
</div>
</form>
<span data-ng-bind="Message" ng-hide="hideMessage" class="sucessMsg"></span>
</div>
</div
contact.component.js
angular.module('myApp')
.component('contactComponent', {
restrict: 'E',
$scope:{},
templateUrl:'contact/contact.html',
controller: contactController,
controllerAs: 'vm',
factory:'userService',
$rootscope:{}
});
function contactController($scope, $state,userService) {
var vm = this;
vm.saveform = function(){
var name= vm.name;
var email= vm.email;
var query= vm.query;
console.log(name);
console.log(email);
console.log(query);
$scope.hideMessage = false;
$scope.Message = "Your query has been successfully submitted.";
$scope.user = userService;
};
$scope.navigate = function(home){
$state.go(home)
};
};
//localStorage code
function userService(saveform) {
var service = {
model: {
name: '',
email: '',
query:''
},
SaveState: function () {
sessionStorage.userService = angular.toJson(service.model);
},
RestoreState: function () {
service.model = angular.fromJson(sessionStorage.userService);
}
}
$rootScope.$on("savestate", service.SaveState);
$rootScope.$on("restorestate", service.RestoreState);
return service;
$rootScope.$on("$routeChangeStart", function (event, next, current) {
if (sessionStorage.restorestate == "true") {
$rootScope.$broadcast('restorestate'); //let everything know we need to restore state
sessionStorage.restorestate = false;
}
});
//let everthing know that we need to save state now.
window.onbeforeunload = function (event) {
$rootScope.$broadcast('savestate');
};
};
There are no errors in console.

Categories

Resources