I am trying to get the response data from my REST API and to display it in my vue.js application as follows:
var database = new Vue({
el: '#database',
data: {
databaseConfiguration: {
type: '',
url: '',
port: '',
username: '',
password: ''
},
errors: []
},
created: function () {
axios.get('/config/database')
.then(function (response) {
this.databaseConfiguration = response.data;
console.log(response.data);
})
.catch(function (error) {
this.errors.push(error);
console.log(error);
})
}
}
)
If I debug it, I see that the response is correctly fetched from the REST API. But unfortunately the data is not displayed on the html page.
The html code looks as follows:
<div id="database" class="panel panel-default panel-primary">
<div class="panel-heading">
<h3 class="panel-title">Database Configuration</h3>
</div>
<div class="panel-body">
<form class="form-horizontal">
<div class="form-group">
<label for="inputType" class="col-sm-2 control-label">Type</label>
<div class="col-sm-10">
<input type="text" v-model="databaseConfiguration.type" class="form-control" id="inputType"
placeholder="Database type">
</div>
</div>
<div class="form-group">
<label for="inputUrl" class="col-sm-2 control-label">Url</label>
<div class="col-sm-10">
<input type="text" v-model="databaseConfiguration.url" class="form-control" id="inputUrl"
placeholder="Url">
</div>
</div>
<div class="form-group">
<label for="inputPort" class="col-sm-2 control-label">Port</label>
<div class="col-sm-10">
<input type="number" v-model="databaseConfiguration.port" class="form-control" id="inputPort"
placeholder="Port">
</div>
</div>
<div class="form-group">
<label for="inputUsername" class="col-sm-2 control-label">Username</label>
<div class="col-sm-10">
<input type="text" v-model="databaseConfiguration.username" class="form-control"
id="inputUsername" placeholder="Password">
</div>
</div>
<div class="form-group">
<label for="inputPassword" class="col-sm-2 control-label">Password</label>
<div class="col-sm-10">
<input type="password" v-model="databaseConfiguration.password" class="form-control"
id="inputPassword" placeholder="Password">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default">Save</button>
</div>
</div>
</form>
</div>
</div>
All the code can be found here.
Your this is pointing to the wrong object in your callbacks. Try using an arrow function, a closure, or bind.
Here is an example using an arrow function.
axios.get('/config/database')
.then(response => {
this.databaseConfiguration = response.data;
console.log(response.data);
})
.catch(error =>{
this.errors.push(error);
console.log(error);
})
See How to access the correct this inside a callback.
Related
I have only one form for update and create and one button in this form. I want when I will click on submit button then alert will must show automatically update or create that alert which i will get request through controller. I am not able to use data-ajax call. So tell me about how I will show-ajax call. or give me a sample of this and this is my code and help me about this.
<form id="blogForm" enctype="multipart/form-data" asp-controller="Admin" asp-action="AddBlog" method="post">
<div class="card-body">
<div class="form-group">
<input type="hidden" asp-for="blogRequestDTO.Id" />
</div>
<div class="form-group">
<label asp-for="blogRequestDTO.Title">Title</label>
<input type="text" asp-for="blogRequestDTO.Title" class="form-control" placeholder="Enter blog name">
<span asp-validation-for="blogRequestDTO.Title" class="text-danger"></span>
</div>
<!-- For Image-->
<div class="col-md-6">
<div class="form-group">
<label asp-for="blogRequestDTO.Image" class="control-label"></label>
<div class="custom-file">
<input asp-for="blogRequestDTO.Image" class="custom-file-input" id="customFile">
<label class="custom-file-label" for="customFile">Choose file</label>
</div>
<span asp-validation-for="blogRequestDTO.Image" class="text-danger"></span>
</div>
</div>
</div>
<!-- /.card-body -->
<div class="card-footer">
<button id="submitBtn" type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
Maybe what you want is to use onclick to call ajax when submitting.
Below is my test code you can refer to it.
#model Project.Models.blogRequestDTO
<form id="blogForm" enctype="multipart/form-data" asp-controller="Home" asp-action="AddBlog" method="post">
<div class="card-body">
<div class="form-group">
<input type="hidden" id="Id" asp-for="#Model.Id" />
</div>
<div class="form-group">
<label asp-for="#Model.Title">Title</label>
<input type="text" id="Title" asp-for="#Model.Title" class="form-control" placeholder="Enter blog name">
<span asp-validation-for="#Model.Title" class="text-danger"></span>
</div>
<!-- For Image-->
<div class="col-md-6">
<div class="form-group">
<label asp-for="#Model.Image" class="control-label"></label>
<div class="custom-file">
<input id="Image" asp-for="#Model.Image" class="custom-file-input" id="customFile">
<label class="custom-file-label" for="customFile">Choose file</label>
</div>
<span asp-validation-for="#Model.Image" class="text-danger"></span>
</div>
</div>
</div>
<!-- /.card-body -->
<div class="card-footer">
<button id="submitBtn" class="btn btn-primary" onclick="Test()" type="submit" >submit</button>
</div>
</form>
<script>
function Test()
{
var formData = new FormData();
formData.append("Id", $("#Id").val());
formData.append("Title",$("#Title").val());
formData.append("Image",$("#Image")[0].files[0]);
debugger;
$.ajax({
url: '/Home/AddBlog',
method: 'POST',
contentType: 'json',
data: formData,
processData: false,
contentType: false,
cache: false,
success: function (response) {
alert('success');
},
error: function (response, error) {
alert('error');
}
});
}
</script>
I have a JavaScript file inside my wwwroot folder referenced from my views. I want some variables in the file set server-side like this:
var someProperty = '#(Model.SomeProperty)';
The content inside wwwroot is static, so I thought I'd convert the JavaScript file into a Razor Page and put it /Pages/SomeFile/Index.cshtml
However, I cannot figure out how to change content type to text/javascript. Any idea how to do this or is there a better way to serve up JavaScript that contains data set server-side?
so I thought I'd convert the JavaScript file into a Razor Page and put it /Pages/SomeFile/Index.cshtml
There is no way to implement Razor code in separate JS files.
1.You should set variable data in your .cshtml files like below:
<div class="row">
<div class="col-md-4">
<form method="post">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="#Model.Id" class="control-label"></label>
<input asp-for="#Model.Id" class="form-control" />
<span asp-validation-for="Id" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="#Model.Name" class="control-label"></label>
<input asp-for="#Model.Name" class="form-control" />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
<div class="form-group">
<input type="button" id="button1" value="Create" class="btn btn-primary" />
</div>
</form>
</div>
</div>
#section Scripts {
<script src="~/js/site.js" type="text/javascript"></script>
<script>
$('#button1').click(function () {
Create({
name : '#Model.Name',
id: '#Model.Id'
// ... other module options
});
});
</script>
}
Your site.js file in wwwroot/js:
function Create(options) {
//get the model value like below
var name = options.name;
var id = options.id;
$.ajax({
url: "/Tests/Create?name=" + options.name,
type: 'Post',
headers: { 'RequestVerificationToken': $('input:hidden[name="__RequestVerificationToken"]').val() },
success: function (data) {
alert("success");
}
})
}
2.Another way is to put the js code in the razor pages:
<div class="row">
<div class="col-md-4">
<form method="post">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="#Model.Id" class="control-label"></label>
<input asp-for="#Model.Id" class="form-control" />
<span asp-validation-for="Id" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="#Model.Name" class="control-label"></label>
<input asp-for="#Model.Name" class="form-control" />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
<div class="form-group">
<input type="button" value="Create" onclick="Create()" class="btn btn-primary" />
</div>
</form>
</div>
</div>
#section Scripts {
<script>
function Create() {
var name = '#Model.Name'
$.ajax({
url: "/Tests/Create?name=" + name,
type: 'Post',
headers: { 'RequestVerificationToken': $('input:hidden[name="__RequestVerificationToken"]').val() },
success: function (data) {
alert("success");
}
})
}
</script>
}
I am trying to empty the form after it submits form but I am unable to do this. Here is the code
<form class="form-horizontal" #submit.prevent="addtodirectory" id="form-directory">
<div class="model-body">
<div class="card-body">
<div class="form-group row">
<label for="inputEmail3" class="col-sm-2 col-form-label">Name</label>
<div class="col-sm-10">
<input v-model="form.name" type="text" name="name"
class="form-control" :class="{ 'is-invalid': form.errors.has('name') }">
<has-error :form="form" field="name"></has-error>
</div>
</div>
<div class="form-group row">
<label for="inputEmail3" class="col-sm-2 col-form-label">Address</label>
<div class="col-sm-10">
<textarea v-model="form.address" type="text" name="address"
class="form-control" :class="{ 'is-invalid': form.errors.has('address') }"></textarea>
<has-error :form="form" field="address"></has-error>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Profession</label>
<div class="col-sm-10">
<input v-model="form.profession" type="text" name="profession"
class="form-control" :class="{ 'is-invalid': form.errors.has('profession') }">
<has-error :form="form" field="profession"></has-error>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Contact Number</label>
<div class="col-sm-10">
<input v-model="form.contact_number" type="text" name="contact_number"
class="form-control" :class="{ 'is-invalid': form.errors.has('contact_number') }">
<has-error :form="form" field="contact_number"></has-error>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">City</label>
<div class="col-sm-10">
<input v-model="form.city" type="text" name="city"
class="form-control" :class="{ 'is-invalid': form.errors.has('city') }">
<has-error :form="form" field="city"></has-error>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">State</label>
<div class="col-sm-10">
<select v-model="form.state" type="text" name="state"
class="form-control" :class="{ 'is-invalid': form.errors.has('state') }">
<has-error :form="form" field="state"></has-error>
<option value="Rajasthan">Rajasthan</option>
<option value="Gujrat">Gujrat</option>
</select>
</div>
</div>
</div>
<!-- /.card-body -->
<div class="card-footer">
<button type="submit" class="btn btn-success">Submit</button>
<button type="submit" class="btn btn-default float-right">Cancel</button>
</div>
<!-- /.card-footer -->
</div>
</form>
<script>
export default {
data() {
return {
news:{},
form: new Form({
name : '',
address:'',
profession:'',
city:'',
state:''
})
}
},
methods: { addtodirectory() {
this.$Progress.start();
this.form.post('api/addtodirectory');
Toast.fire({
type: 'success',
title: 'Directory Updated successfully'
})
$('#form-directory input[type="text"]').val('');
this.$Progress.finish();
}
}
I am using vform plugin to submit the form. Using Laravel as backend. The data is being submitted in database but I am not able to clear the form. please help in this regarding. Should I use jquery or javascript to clear the form? I tried different ways but I could not figure out the problem.
Simply empty your form object after form submit.
form: new Form({
name : '',
address:'',
profession:'',
city:'',
state:''
})
Well it was simple and I did following code for emptying the form.
addtodirectory(event) {
this.$Progress.start();
this.form.post('api/addtodirectory');
// document.getElementById("form-directory").reset();
console.log('durgesh');
// document.getElementsByName('name').value = '';
Toast.fire({
type: 'success',
title: 'Directory Updated successfully'
})
this.form.name = "";
this.form.profession ="";
this.form.address="";
this.form.city = "";
this.form.state = "";
this.$Progress.finish();
},
after submitting the form I did not used the form. so after doing this I emptied the form.
Or in a one-liner:
Object.keys(form).forEach(v => form[v] = "")
instead of:
this.form.name = "";
this.form.profession ="";
this.form.address="";
this.form.city = "";
this.form.state = "";
I am learning Vue.js I have successfully made this registration form and its working fine
but I'm having a problem in showing errors.
register.vue page
<form #submit.prevent="RegisterUser" aria-label="Register">
<div class="form-group row">
<label for="name" class="col-md-4 col-form-label text-md-right">Name</label>
<div class="col-md-6">
<!-- <input id="name" v-model="name" type="text" class="form-control" name="name" value="" required autofocus> -->
<input type="text" v-model="name" class="form-control" required="required" autofocus="autofocus">
</div>
</div>
<div class="form-group row">
<label for="email" class="col-md-4 col-form-label text-md-right">Email Address</label>
<div class="col-md-6">
<!-- <input id="email" v-model="email" type="email" class="form-control" name="email" value="" required> -->
<input type="email" v-model="email" required autofocus class="form-control">
{{ errors.email }}
</div>
</div>
<div class="form-group row">
<label for="password" class="col-md-4 col-form-label text-md-right">Password</label>
<div class="col-md-6">
<!-- <input id="password" v-model="password" type="password" class="form-control" required> -->
<input type="password" v-model="password" class="form-control" required>
</div>
</div>
<div class="form-group row">
<label for="password-confirm" class="col-md-4 col-form-label text-md-right">Confirm Password</label>
<div class="col-md-6">
<!-- <input id="password-confirm" v-model="password_confirmation" type="password" class="form-control" required> -->
<input type="password" v-model="confirm_password" class="form-control" required>
</div>
</div>
<div class="form-group row mb-0">
<div class="col-md-6 offset-md-4">
<button type="submit" class="btn btn-primary">
Register
</button>
</div>
</div>
</form>
This is my scripts in register.vue page working registration fine
<script>
export default {
// props: ['name'],
data: function() {
return {
name: '',
email: '',
password: '',
confirm_password: '',
errors: {},
};
},
methods: {
RegisterUser() {
axios.post('/register', {
name: this.name,
email: this.email,
password: this.password,
password_confirmation:this.confirm_password
})
.then(function(response){
swal({
title: "Good job!",
text: "Login Success",
icon: "success",
button: "Okay",
})
.then((willDelete) => {
if (willDelete) {
window.location.href = '/home';
}
});
})
.catch(function (error) {
console.log(error.response.data);
});
}
}
}
</script>
This is the Errors I want to fetch...
How to fetch and how this errors on my vue components?
Note!! This solution is based on ES6 so you might have to transpile this to ES5
I had this issue a while back so I wrote a simple class to help manage validation messages from the server. https://gist.github.com/nonsocode/e6f34a685f8be1422c425e3a20a69a4b
You can use it by importing this to your template
import ErrorBag from 'path-to-errorbag-class'
and use it in your data method like so
data: function() {
return {
name: '',
email: '',
password: '',
confirm_password: '',
errors: new ErrorBag,
};
},
In your template, you can check if there's a validation error and then decide how you ant to handle it. I'll assume you're using bootsrap 4
<div class="form-group row">
<label for="email" class="col-md-4 col-form-label text-md-right">Email Address</label>
<div class="col-md-6">
<input type="email" v-model="email" required autofocus :class="{'form-control': true, 'is-invalid': errors.has('email')}">
<div class="invalid-feedback" v-if="errors.has('email')" >{{ errors.first('email') }}</div>
</div>
</div>
in the catch method of your ajax request,
axios(...)
.then(...)
.catch(function (error) {
if (error.response && error.response.status == 422) {
const errors = err.response.data.errors;
this.errors.setErrors(errors);
}
});
After successfully submitting to your server, you can call the clearAll method on the errorbag to clear all errors from the bag
In my home page i have to create records and when i am creating the records and clicking on submit button and getting like added successfully. After that the created record is not available in the list records.When i'm creating another new record and submit it the previous created record is displays in the list.
Type Script code is:
import { Component, OnInit } from '#angular/core';
import {FormControl, Validators, NgForm } from '#angular/forms';
import { VisitService } from '../shared/visit.service';
import { ToastrService } from 'ngx-toastr';
import { Response, RequestOptions, Http, Headers } from '#angular/http';
import { CookieService } from 'ngx-cookie-service';
#Component({
selector: 'app-visit',
templateUrl: './visit.component.html',
styleUrls: ['./visit.component.css']
})
export class VisitComponent implements OnInit {
cookieValue = 'UNKNOWN';
constructor(private visitService: VisitService,private http: Http,private cookieService: CookieService, private toastr: ToastrService ) { }
ngOnInit() {
this.resetForm();
this.cookieValue = this.cookieService.get('session');
console.log('token from browser' + this.cookieValue );
const url = `http://localhost:8080//api/getallvisits/`;
// const headers = new Headers({'Content-Type': 'application/json','Authorization':'Bearer' +this.cookieValue});
let headers = new Headers({ 'Authorization': 'Bearer ' + this.cookieValue });
// const headers = new Headers();
// headers.append('Authorization', 'Bearer' +this.cookieValue );
const options = new RequestOptions({ headers: headers });
return this.http.get(url, options)
.subscribe(res => {
console.log('message from' + res);
// this.refresh();
alert('successfullyyy...');
// console.log('message from' + people.json())
});
}
resetForm(form?: NgForm) {
if (form != null)
form.reset();
this.visitService.selectedVisit = {
'ID':null,
'UserName': '',
'Height': null,
'Weight': null,
'Temperature': null,
'BloodPressure': '',
'PatientNote': '',
'NurseNote': '',
'DoctorNote': '',
}
}
onSubmit(form: NgForm) {
if (form.value.ID == null) {
this.visitService.createVisit(form.value)
.subscribe(data => {
this.resetForm(form);
this.visitService.getVisitList();
this.toastr.success('New Record Added Succcessfully', 'Employee Register');
})
}
else {
this.visitService.updateVisit(form.value.ID, form.value)
.subscribe(data => {
this.resetForm(form);
this.visitService.getVisitList();
this.toastr.info('Record Updated Successfully!', 'Employee Register');
});
}
}
}
And my HTML page is:
<form class="visit-form" #visitForm="ngForm" (ngSubmit)="onSubmit(visitForm)">
<input type="hidden" name="ID" #ID="ngModel" [(ngModel)]="visitService.selectedVisit.ID">
<div class="form-row">
<div class="form-group col-md-6">
<mat-form-field class="example-full-width">
<input class="form-control" matInput placeholder="UserName" name="UserName" #UserName="ngModel" [(ngModel)]="visitService.selectedVisit.username"
placeholder="User Name" required>
<div class="validation-error" *ngIf="UserName.invalid && UserName.touched">This Field is Required.</div>
</mat-form-field>
</div>
<div class="form-group col-md-6">
<mat-form-field class="example-full-width">
<input class="form-control" matInput placeholder="Height" name="Height" #Height="ngModel" [(ngModel)]="visitService.selectedVisit.height" placeholder="Height"
required>
<div class="validation-error" *ngIf="Height.invalid && Height.touched">This Field is Required.</div>
</mat-form-field>
</div>
</div>
<div class="form-group">
<mat-form-field class="example-full-width">
<input class="form-control" matInput placeholder="Temperature" name="Temperature" #Temperature="ngModel" [(ngModel)]="visitService.selectedVisit.temperature" placeholder="Temperature">
</mat-form-field>
</div>
<div class="form-group">
<mat-form-field class="example-full-width">
<input class="form-control" matInput placeholder="Weight" name="Weight" #Weight="ngModel" [(ngModel)]="visitService.selectedVisit.weight" placeholder="Weight">
</mat-form-field>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<mat-form-field class="example-full-width">
<input class="form-control" matInput placeholder="Blood Pressure" name="BloodPressure" #BloodPressure="ngModel" [(ngModel)]="visitService.selectedVisit.bloodpressure" placeholder="Blood Pressure">
</mat-form-field>
</div>
<div class="form-group col-md-6">
<mat-form-field class="example-full-width">
<input class="form-control" matInput placeholder="Patient Note" name="PatientNote" #PatientNote="ngModel" [(ngModel)]="visitService.selectedVisit.patientnote" placeholder="Patient Note">
</mat-form-field>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<mat-form-field class="example-full-width">
<input class="form-control" matInput placeholder="Nurse Note" name="NurseNote" #NurseNote="ngModel" [(ngModel)]="visitService.selectedVisit.nursenote" placeholder="Nurse Note">
</mat-form-field>
</div>
<div class="form-group col-md-6">
<mat-form-field class="example-full-width">
<input class="form-control" matInput placeholder="Doctor Note" name="DoctorNote" #DoctorNote="ngModel" [(ngModel)]="visitService.selectedVisit.doctornote" placeholder="Doctor Note">
</mat-form-field>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-8">
<button [disabled]="!visitForm.valid" type="submit" class="btn btn-lg btn-block btn-info">
<i class="fa fa-floppy-o"></i> Submit</button>
</div>
<div class="form-group col-md-4">
<button type="button" class="btn btn-lg btn-block btn-secondary" (click)="resetForm(visitForm)">
<i class="fa fa-repeat"></i> Reset</button>
</div>
</div>
</form>
Anyone please refer that.Thank You
See if you are displaying the value in html table or like that then after submit you have to destroy the table .
and again Reinit the table then only it will display the current added value as well.
So You can do that or else call the onload function when submit function ends .
or if you have some other issue then let me know in details.