I have a probleme. I will call JSON-RPC request. My Http post request on service.ts
service.ts
#Injectable({
providedIn: 'root'
})
export class Service {
public encoder: HttpParameterCodec;
public defaultHeaders = new HttpHeaders();
constructor(protected httpClient: HttpClient) {}
public createBriefing(
briefingData: Briefing //: Observable<any>
) {
const url = "";
let headers = new HttpHeaders();
headers.append("Content-Type", "application/json");
let body= new JsonRpcBody();
body.id = briefingData.id;
body.method = "query";
body.params = briefingData.params;
this.httpClient.post(url, JSON.stringify(body), { headers: headers })
.subscribe(response => console.log(response));
}
}
export class JsonRpcBody {
id:string;
method: string;
params: BriefingParameters[]
}
export class BriefingParameters {
id: string;
name: string[]
city: string[]
state: string[]
}
component.ts
Brifing: any = {
id: 'query01',
method: 'query',
"params": [
{
"id": "briefing01",
"name": ["FIRST", "LAST"],
"city":["LONDON", "ARSENAL"],
"state": ["ENGLAND"]
},
],
};
postBriefing(){
this.service.createBriefing(this.Brifing)
};
component.html
<form [formGroup]="guestForm" >
<table class="form-group" >
<tr>
<th> Query: </th>
<td ><input type="checkbox" formControlName="name" [(ngModel)]="Brifing.name" class="form-control" id="" formControlName="" > FIRST
<input type="checkbox" formControlName="name" [(ngModel)]="Brifing.name" class="form-control" id="" formControlName="" > LAST
</td>
</tr>
<tr>
<th> City</th>
<td ><input type="textarea" formControlName="city" [(ngModel)]="Brifing.city" class="form-control" id="" formControlName=""></td>
</tr>
<tr>
<th> State</th>
<td ><input type="textarea" formControlName="state" [(ngModel)]="Brifing.state" class="form-control" id="" formControlName=""></td></tr>
</table>
<button type="button" class="btn btn-primary" (click)="postBriefing()">Create Briefing</button>
<pre></pre>
</form>
<table>
<tr>
<th> </th>
<td> 3 rows </td>
</tr>
</table>
I want to sleep the data as
type, location, name in table.
The data is already displayed on the console, but if I write the name, adress,city in the table, the data does not appear.
what am I doing wrong?
Related
I am trying to delete a certain element from an array, that I display in a HTML-Table.
Here's the frontend:
HTML-table_frontend
I push the Data from the input into an array userData.
The HTML-Table is build within a v-forloop in VUEjs.
Upon Pressing a button, I want the dedicated function (e.g. deleteData()) to only be applied to the row that that button is in.
How can I tell the button what Array-Index it needs to target?
Here's the code snippets:
Table:
<table id="userData">
<tr>
<th>Name</th>
<th>Email Address</th>
<th>Mobile Number</th>
<th>Action</th>
</tr>
<tr v-for="(userData, k) in userData" :key="k">
<td class="name">
<input readonly class="tableDisplay" type="text" v-model="userData.name" />
</td>
<td>
<input readonly class="tableDisplay" type="email" v-model="userData.email" />
</td>
<td>
<input readonly class="tableDisplay" type="number" v-model="userData.number" />
</td>
<td>
<button type='button' class="buttonRead" #click="readData" >Read</button>
<button type='button' class="buttonEdit" #click="editData">Edit</button>
<button type='button' class="buttonDelete" #click="deleteData">Delete</button>
</td>
</tr>
</table>
Javascript in the .vue:
<script>
export default {
data() {
return{
userData:[],
newUser: {
name: '',
email:'',
number:''
}
};
},
methods: {
customSubmit(){
this.userData.push(this.newUser)
this.newUser = {
name:'',
email:'',
number:''
}
console.log(this.userData)
},
}
}
</script>
example with passing index
<button type='button' class="buttonDelete" #click="deleteData(k)">Delete</button>
methods: {
deleteData(k) {
this.userData.splice(k, 1)
}
}
or passing object
<button type='button' class="buttonDelete" #click="deleteData(userData)">Delete</button>
methods: {
deleteData(userData) {
let index = this.userData.indexOf(userData)
this.userData.splice(index, 1)
}
}
UPD. readData
<button type='button' class="buttonRead" #click="readData(k)" >Read</button>
methods: {
readData (k) {
console.log(this.userData[k].name)
},
}
also change userData variable name
<tr v-for="(rowUser, k) in userData" :key="k">
in inputs
<input ... v-model="rowUser.name" />
live example https://jsfiddle.net/8v2cx4je/
I want to get my forms to work how I have them set up. I needed multiple forms to have a update and delete option on every product item. The problem that I am having is that as soon as I add the [formGroup]="profileForm" directive in my form the form Controls stop working. I had trouble getting the reactive form to work because each of my forms are in a table row.
I unfortunately have the data on a local server so the code won't look like the picture displayed but here is the stack-blitz if you want a closer look at my code: https://stackblitz.com/github/RashellSmith/Dashboard-FrontEnd
update product ts
import { Component, OnInit } from '#angular/core';
import { Product } from '../model/Product';
import { Category } from '../model/Availability';
import { Supplier } from '../model/Supplier';
import { Home } from '../model/Home';
import { HomeService } from '../service/Home.service';
import { SupplierService } from '../service/Supplier.service';
import { CategoryService } from '../service/Category.service';
import { FormGroup, FormControl } from '#angular/forms'
#Component({
selector: 'app-update-product',
templateUrl: './update-product.component.html',
styleUrls: ['./update-product.component.scss']
})
export class UpdateProductComponent implements OnInit {
availability:boolean;
category:number;
orderBy: String;
Ascdesc: String;
page = 0;
home: Home[];
categories: Category[];
supplier: Supplier[];
selectedCategory: Category;
edit: boolean = false;
public currentProduct: number;
toogleEditMode() {
this.edit = this.edit ? false : true;
}
selectCategory (category) {
this.category = category.category;
}
available(boolean){
this.availability = boolean;
}
update($event){
this.homeService.getByParm(this.availability,this.category).subscribe(data => {
this.home = data;
});
}
profileForm = new FormGroup({
id: new FormControl(''),
name: new FormControl(''),
category: new FormControl(''),
fullPrice: new FormControl(''),
salePrice: new FormControl(''),
availability: new FormControl(''),
supplier: new FormControl(''),
discount: new FormControl(''),
});
// model = {id: null, productName: '', category: {category: null, categoryName: null}, fullPrice: '', salePrice:'', availability: false, supplier: {supplier:null,supplierName:""},discount:null};
// json = JSON.stringify(this.model);
constructor(private homeService: HomeService,private supplierService: SupplierService,private categoryService: CategoryService) { }
name = new FormControl('');
SortPrice($event:any){
let icon = document.getElementById("asc-desc1");
if(icon.className === "fas fa-angle-down"){
icon.className ="fas fa-angle-up";
this.homeService.getByPriceAsc().subscribe(data => {
this.home = data;
});
}else{
icon.className ="fas fa-angle-down"
this.homeService.getByPriceDesc().subscribe(data => {
this.home = data;
});
};
}
// model = new Newproduct(null,new Category( this.value,"name"),null,null,false,new Supplier(null,null),null);
onSubmit() {
// TODO: Use EventEmitter with form value
// console.warn(this.profileForm.value);
}
SortSale($event:any){
let icon = document.getElementById("asc-desc2");
if(icon.className === "fas fa-angle-down"){
icon.className ="fas fa-angle-up";
this.homeService.getBySaleAsc().subscribe(data => {
this.home = data;
});
}else{
icon.className ="fas fa-angle-down"
this.homeService.getBySaleDesc().subscribe(data => {
this.home = data;
});
};
}
SortDiscount($event:any){
let icon = document.getElementById("asc-desc3");
if(icon.className === "fas fa-angle-down"){
icon.className ="fas fa-angle-up";
this.homeService.getByDiscountAsc().subscribe(data => {
this.home = data;
});
}else{
icon.className ="fas fa-angle-down"
this.homeService.getByDiscountDesc().subscribe(data => {
this.home = data;
});
};
}
ngOnInit() {
this.supplierService.getAll().subscribe(data => {
this.supplier = data;
});
this.homeService.getAll().subscribe(data => {
this.home = data;
});
this.categoryService.getAll().subscribe(data => {
this.categories = data;
});
}
}
update product html
<!-- Table -->
<form [formGroup]="profileForm" (ngSubmit)="onSubmit()">
<p>
Form Status: {{profileForm.value |json}}
</p>
<div class="table-responsive">
<table class="table table-bordered table-striped">
<thead>
<tr>
<th>Id</th>
<th>Product</th>
<th>Category</th>
<th>FullPrice <i id ="asc-desc1"class="fas fa-angle-down" (click)="SortPrice($event)"></i></th>
<th>Saleprice <i id ="asc-desc2"class="fas fa-angle-down" (click)="SortSale($event)"></i> </th>
<th>Availablity</th>
<th>Supplier</th>
<th>Discount<i id ="asc-desc3"class="fas fa-angle-down" (click)="SortDiscount($event)"></i></th>
<th>Edit</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let home of home | paginate:{itemsPerPage:20,currentPage: p} ; index as i">
<ng-container *ngIf="editMode !== i">
<td [attr.data-index]="i">{{home.id}}</td>
<td>{{home.productName}}</td>
<td>{{home.category.categoryName}}</td>
<td>{{home.fullPrice}}</td>
<td>{{home.salePrice}}</td>
<td>{{home.availability}}</td>
<td>{{home.supplier.supplierName}}</td>
<td>{{home.discount }}</td>
</ng-container>
<ng-container *ngIf="editMode === i">
<td><input class="form-control" id="id" formControlName="id" placeholder={{home.id}}></td>
<td><input class="form-control" id="name" formControlName="productName" placeholder={{home.productName}}> Value: {{ profileForm.productName.value }}</td>
<td><input class="form-control" id="categoryname" [formControl]="category" placeholder={{home.category.categoryName}}></td>
<td><input class="form-control" id="fullprice" [formControl]="fullPrice" placeholder={{home.fullPrice}}></td>
<td><input class="form-control" id="saleprice" [formControl]="salePrice" placeholder={{home.salePrice}}></td>
<td><input class="form-control" id="availability" [formControl]="availability" placeholder={{home.availability}}></td>
<td>
<select class="form-control">
<option *ngFor="let supplier of suppliers">{{supplier.supplierName}}</option>
</select>
</td>
<td><input class="form-control" id="discount" placeholder={{home.discount}}></td>
</ng-container>
<!-- if assigned index to editMode matches -->
<td class="text-right" id="tableDataBtns">
<div class="btn-group" role="group">
<button (click)="editMode === i ? editMode = null : editMode = i" data-toggle="modal" data-target="#updateProduct" type="button" class="btn btn-secondary">
<ng-container *ngIf="editMode === i"><i class="far fa-save"></i></ng-container>
<ng-container *ngIf="editMode !== i"><i class="far fa-edit"></i></ng-container>
</button>
<button type="button" data-toggle="modal" data-target="#deleteProduct" class="btn btn-danger"><i class="far fa-trash-alt"></i></button>
</div>
</td>
</tr>
<div>
<select >
<option *ngFor="let supplier of suppliers" [ngValue]="supplier">{{supplier.supplierName}}</option>
</select>
</div>
</tbody>
</table>
<pagination-controls class="myPagination" (pageChange)="p= $event"></pagination-controls>
</div>
</form>
You have in your HTML a mixup with formControlName and [formControl].
In your case, you have defined the [formGroup] in your code.
So keep using formControlName instead of [formControl]
Hi You are working with reactiveForms and you just need to change [formControl] to formControlName for every input field like below
<form [formGroup] >
Your input fields are here.
<input class="form-control" id="fullprice" formControlName="fullPrice" placeholder={{home.fullPrice}}></td>
</form>
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>
Here is my problem regarding to-do task management.
I want to update an option value in select selector when the (change) event is triggered.
there are 2 Component
//app.component.ts
//array object
this.dataArr[this.counter] = {id: this.task_ID, name: this.t_name, msg: this.t_msg, date: this.task_date};
//console.log(this.counter);
console.log(this.dataArr[this.counter]);
//local storage
if (typeof(Storage) !== "undefined") {
localStorage.setItem("taskM", JSON.stringify(this.dataArr.reverse())); //put object array in reverse order to show latest object at top position
this.myObj = JSON.parse(localStorage.getItem("taskM"));
}
in this component I want to change and save select option value to localStorage
//task-form.component.ts.
import { Component, OnInit, Input, Output } from '#angular/core';
import { AppComponent } from './app.component';
#Component({
selector: 'task-data',
template: `<h3>List of Task</h3>
<div class="table-responsive">
<table class="table table-striped">
<thead>
<tr>
<th>Task Id</th>
<th>Task Title</th>
<th>Description</th>
<th>Date</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let hero of taskMM">
<td> {{ hero.id }} </td>
<td> {{ hero.name }} </td>
<td> {{ hero.msg }} </td>
<td> {{ hero.date }} </td>
<td>
<select class="form-control">
<option *ngFor="let p of taskStatus"[value]="p"> {{p}}</option>
</select>
</td>
</tr>
</tbody>
</table>
</div>
`
})
export class TaskFormComponent {
taskStatus: string[];
taskMM: string[] = JSON.parse(localStorage.getItem("taskM"));
#Input('task-s') t_status: string;
#Input() data1: any= [];
onChange(deviceValue) {
console.log(deviceValue);
}
ngOnInit() {
console.log('this is ngOnInit ');
}
constructor() {
this.taskStatus = ['Started', 'Pending', 'Completed'];
}
}
<select (change)="onChange($event.target.value)" class="form-control">
<option *ngFor="let p of taskStatus"[value]="p"> {{p}}</option>
</select>
onChange($event) {
localStorage.setItem("taskM", $event);
}
this is my jsp code:
EMAIL.JSP
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Example</title>
</head>
<body>
<form method="post" action="">
<center>
<table border="1" width="30%" cellpadding="3">
<thead>
<tr>
<th colspan="2">Enter the information</th>
</tr>
</thead>
<tbody>
<tr>
<td>To Address</td>
<td><input type="text" name="uname" value="" /></td>
</tr>
<tr>
<td>Subject</td>
<td><input type="text" name="uname" value="" /></td>
</tr>
<tr>
<td>AttachFile</td>
<td<inputtype="text"value=".\ogc\hb1_800.jpg"id=".\ogc\hb1_800.jpg" />
</td>
</tr>
<tr>
<td><input type="reset" value="Clear" /></td>
<td><input type="Submit" value="Submit" /></td>
</tr>
</tbody>
</table>
</center>
</form>
and on clicking the submit button i need to execute the java code:
final.java which is below:-
FINAL.JAVA
package com.grid;
public class final {
public static void main(String[] args) {
String ToAddress = new String[]{"8789951#gmail.com"};
String Subject = "Hi this is test Mail";
String AttachFile = {".\ogc\notepad\styles\thumbs\hb1_800.jpg"};
new Email().sendMail(ToAddress,Subject,AttachFile);
}
}
it calls the email.java
package com.grid;
import java.io.*;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
public class Email{
private String SMTP_HOST = "smtp.gmail.com";
private String FROM_ADDRESS = "n123f#gmail.com";
private String PASSWORD = *****";
private String FROM_NAME = "Abc";
public boolean sendMail(String ToAddress,String Subject,String AttachFile) {
try {
Properties props = new Properties();
props.put("mail.smtp.host", SMTP_HOST);
props.put("mail.smtp.auth", "true");
props.put("mail.debug.auth", "true");
props.put("mail.smtp.ssl.enable", "true");
Session session = Session.getInstance(props, new SocialAuth());
MimeMessage msg = new MimeMessage(session);
InternetAddress from = new InternetAddress(FROM_ADDRESS, FROM_NAME);
msg.setFrom(from);
InternetAddress[] ToAddress = new InternetAddress[recipients.length];
for (int i = 0; i < recipients.length; i++) {
ToAddress = new InternetAddress(recipients[i]);
}
msg.setRecipients(Message.RecipientType.TO, ToAddress);
msg.setSubject(Subject);
MimeBodyPart msgBodyPart = new MimeBodyPart();
// Fill the message
msgBodyPart.setText("This is message body");
// Create a multipart message
Multipart multipart = new MimeMultipart();
// Set text message part
multipart.addBodyPart(msgBodyPart);
// Part two is attachment
if (FileName != null && FileName.length > 0)
{
for (String filePath : FileName)
{
MimeBodyPart attachPart = new MimeBodyPart();
try {
attachPart.AttachFile(filePath);
} catch (IOException ex) {
ex.printStackTrace();
}
multipart.addBodyPart(attachPart);
}
}
/*DataSource source = new FileDataSource(filename);
msgBodyPart.setDataHandler(new DataHandler(source));
msgBodyPart.setFileName(filename);
multipart.addBodyPart(msgBodyPart);*/
msg.setContent(multipart);
Transport.send(msg);
return true;
} catch (UnsupportedEncodingException ex) {
Logger.getLogger(MailUtil.class.getName()).log(Level.SEVERE, null, ex);
return false;
} catch (MessagingException ex) {
Logger.getLogger(MailUtil.class.getName()).log(Level.SEVERE, null,ex);
return false;
}
}
class SocialAuth extends Authenticator {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
new PasswordAuthentication(FROM_ADDRESS, PASSWORD);
}
}
}
Now my doubt is how to execute final.java (which is a running code) on clicking the button submit in email.jsp page?
Here is a simple servlet for demonstration:
JSP:
<form method="post" action="/email">
<center>
<table border="1" width="30%" cellpadding="3">
<thead>
<tr>
<th colspan="2">Enter the information</th>
</tr>
</thead>
<tbody>
<tr>
<td>To Address</td>
<td><input type="text" name="to" value="" /></td>
</tr>
<tr>
<td>Subject</td>
<td><input type="text" name="subject" value="" /></td>
</tr>
<tr>
<td>AttachFile</td>
<td> <input type="text" name="file" value=".\ogc\hb1_800.jpg"id=".\ogc\hb1_800.jpg" />
</td>
</tr>
<tr>
<td><input type="reset" value="Clear" /></td>
<td><input type="Submit" value="Submit" /></td>
</tr>
</tbody>
</table>
</center>
</form>
Servlet:
#WebServlet(name="mytest", urlPatterns={"/email"})
public class MailServlet extends javax.servlet.http.HttpServlet{
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException {
String to = request.getParameter("to");
String subject = request.getParameter("subject");
String file = request.getParameter("file");
new Email().sendMail(to,subject,file);
response.getWriter().println("Email sent");
}
}