html
<div class="form-group ">
<input type="file" [(ngModel)]="model.files" name="files" #files="ngModel" class="form-control" id="files" multiple="">
</div>
<div class="form-group ">
<label for="productname">Name</label>
<input type="text" class="form-control" id="productname" required minlength="5" pattern="^[a-zA-Z0-9/,-. ]*$" maxlength="30" [(ngModel)]="model.productname" name="productname" #productname="ngModel">
</div>
<div class="form-group ">
<label for="sales">Sales price/rate</label>
<input type="text" class="form-control" id="sales" pattern="[0-9]+" required minlength="0" maxlength="10" [(ngModel)]="model.sales" name="sales" #sales="ngModel">
</div>
<button type="submit" class="btn btn-success " (click)="save(productname,sales,files);onChangeroot(root)">Submit</button>
component.ts
export class NewProductComponent {
productservice:ProductsService
selectedFile = null;
onfileSelected(event){
console.log(event);
this.selectedFile =<File>event.target.files[0];
}
save1(productname,sales,files)
{
let obj = {
'pro_name':productname.value,
'sales':sales.value,
'image':files.value
}
var json = JSON.stringify(obj)
console.log(json)
const fd = new FormData();
fd.append('image', this.selectedFile , this.selectedFile.name );
this.http.post('http://127.0.0.1:8000/product/images/',fd)
this.service.save_user1(json).subscribe(response => console.log('Inserted Successfully'),
error => console.log(error));
}
}
service.ts
export class ProductsService {
save_user1(exp_data:any): Observable<any[]>{
console.log("console",exp_data)
let headers = new Headers({ 'Content-Type': 'application/json'});
let options = new RequestOptions({ headers: headers });
console.log("options",options)
return this.http.post("http://127.0.0.1:8000/product/", exp_data, options)
.map(response => response.json())
.catch(error => Observable.throw(error.statusText));
};
}
After selecting image in console event is working while submitting the form except that image all other data are so successfully stored in database.
I am tried in this way but not able to post image,.so please help me how to do that ?
I think your service method need to be change. Usually we have to send file as multipart form data. My working copy is :
let formData: FormData = new FormData();
formData.append('file', this.imageFile);
this.http.post(this.url , formData) .subscribe(
(result) => {
console.log(result);
},
(error) => {
console.error(error);
}
);
Related
The aim of my application is to take a URL submitted by a user in a form, pull data from it, manipulate that data, and then submit the manipulated data to a Postgres database.
Current Status
So far I have developed a form on the front end of the application (irrelevant validation / styling code has been removed from this excerpt):
const Feeds = ({ visible }) => {
const handleSubmit = async (e) => {
e.preventDefault();
try {
const body = { feedTitle, websiteUrl, currency, feedUrl };
await fetch('/api/form', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body)
});
console.log('body: ', body);
} catch (error) {
console.error(error);
}
};
return (
<Form onSubmit={(e) => handleSubmit(e)} id="myForm" visible={visible}>
<HeaderContainer>
<Header>Add a new feed</Header>
<HeaderDescription>Please complete all of the required fields below and submit to add a new feed.</HeaderDescription>
</HeaderContainer>
<FormContainer>
<InputContainer>
<Label>Feed title</Label>
<Input type="text" placeholder="" value={feedTitle} onChange={(e) => handleChangeFeedTitle(e)} />
</InputContainer>
<InputContainer>
<Label>Website url</Label>
<Input type="text" placeholder="" value={websiteUrl} onChange={(e) => handleChangeWebsiteUrl(e)} />
</InputContainer>
<InputContainer>
<Label>Currency</Label>
<Select onChange={(e) => handleChangeCurrency(e)} name="currency" id="currency-select">
{currencies.map((option, index) => (
<option key={index} value={option.value}>
{option.text}
</option>
))}
</Select>
</InputContainer>
<InputContainer>
<Label>Feed url</Label>
<Input type="text" placeholder="" value={feedUrl} onChange={(e) => handleChangeFeedUrl(e)} />
</InputContainer>
</FormContainer>
{allValid ? <Button type="submit" form="myForm">Save</Button> : <DisabledButton>Save</DisabledButton>}
</Form>
)
};
export default Feeds;
On submission, this POST request hits the /api/form API endpoint:
const handler = async (req, res) => {
const body = req.body;
const response = await fetch(body.feedUrl)
.then(res => res.text())
.then(content => console.log(content))
.catch(err => console.error(err));
console.log('body: ', body);
res.status(200).json({ data: `${body}` })
};
export default handler;
Here I have simply console logged the content coming back from the API. Instead I need to manipulate it using a function and then submit the manipulated data to a database using a separate function.
The Problem
My question is, where should I implement these functions so that they trigger on the server side?
Thanks
**When I click on the upload button it gives an error: TypeError: Cannot read property 'name' of null
FORM
<form class="form" #submit.prevent="upload">
<input required name="name" v-model="name" placeholder="Name" type="text" autocomplete="off">
<input required name="email" v-model="email" placeholder="E-mail" type="email" autocomplete="off">
<input required name="phone" v-model="phone" placeholder="+7(555)555555" maxlength=13 minlength=13 type="phone" autocomplete="off">
<textarea required name="message" v-model="message" rows="4" placeholder="Message" autocomplete="off"></textarea>
<div >
<button class="button" #click="upload">
<div >
<img class="upload" src="#/img/upload.png"></div>
Upload
</button> </div>
<button class="button">Send</button>
</form>
SCRIPT
import { usersCollection, storage } from '../../firebase/init'
export default {
data() {
return {
name: '',
email: '',
message: '',
phone:'',
file: null,
}
},
methods: {
async upload() {
try {
const fileRef = 'uploads/files/' + this.file.name
const snapshot = await storage.ref(fileRef).put(this.file)
let data = {
name: this.name,
email: this.email,
message: this.message,
phone: this.phone,
image: fileref
}
const doc = await usersCollection.add(data)
await this.resetForm()
} catch(e) {
console.log(e)
}
}
}
}
help find the error pls
The reason is your trying to read the name attribute from the file variable which is not an object
data() {
return {
name: '',
email: '',
message: '',
phone:'',
file: {}, // changed null to {}
}
},
I got a Firebase auth you can login and logout.
But I want that the currentUser can change the email.
I have a password reset function that send a email with a link and you can reset your password but It didn't work with the email change.
This is the profile page
Here is the code
<template>
<div class="container">
<div class="card">
<div class="card-header">
<h1>Profile</h1>
</div>
<div v-if="!isHidden" class="alert alert-success" role="alert">
<strong>Email sended</strong>
</div>
<div class="card-body">
<form action="#" #submit.prevent="submit" #click="isHidden = !isHidden">
<div class="form-group row mb-0">
<div class="col-md-7 offset-sm-6 offset-md-7 offset-xl-9">
<input type="submit" class="btn btn-primary" #click="resetPassword" value="Reset your password">
</div>
</div>
</form>
<div class="">
<input type="email" class="form-control" v-model="email">
<input type="submit" class="btn btn-primary" #click="resetEmail" value="Reset your email">
</div>
</div>
</div>
</div>
</template>
<script>
import firebase from "firebase";
/* eslint-disable */
export default {
data() {
return {
email: "",
password: "",
isHidden: true
};
},
methods: {
login(e) {
firebase.auth().signInWithEmailAndPassword(this.email, this.password)
.then(user => {
alert('You are logged in as ' + this.email);
this.$router.push('/index');
location.reload();
},
err => {
alert(err.message);
})
e.preventDefault();
},
resetPassword() {
const auth = firebase.auth();
auth.sendPasswordResetEmail(auth.currentUser.email).then(() => {
console.log('Email send');
// Email sent.
}).catch((error) => {
// An error happened.
console.log(error);
});
},
resetEmail() {
const auth = firebase.auth();
auth.updateEmail(this.email).then(() => {
console.log('Email changed');
// Email sent.
}).catch((error) => {
// An error happened.
console.log(error);
});
}
}
};
</script>
When I run this I get this error:
Uncaught TypeError: auth.updateEmail is not a function
at VueComponent.resetEmail (Profile.vue?5a88:64)
at invoker (vue.runtime.esm.js?2b0e:2023)
at HTMLInputElement.fn._withTask.fn._withTask (vue.runtime.esm.js?2b0e:1822)
What do I do wrong because I read the Firebase doc and checkt on Google but I do something wrong.
The updateEmail() method is not a method of the "root" Firebase Auth service but a method of a User.
So you have to do something along the following lines:
const auth = firebase.auth();
auth.currentUser.updateEmail(this.email).then(() => {...});
hello i'm new in Angular , i'm trying to send to my backend(Symfony2.8) a Subject , Email and Message . when i route the the localhost:4200/contact , i get no error , no excption and the nothing happend , the URL becomes localhost:4200/contact? . here is my component,service and html file: (BTW i used this method to add and object to the database and it works normally)
export class ContactComponent {
contactForm: any;
constructor(private formBuilder: FormBuilder, public router: Router ,private cService: ContactService) {
this.contactForm = this.formBuilder.group({
'subject': ['', Validators.required],
'email' : ['', Validators.required],
'msg': ['', Validators.required],
});
}
sendMessage()
{
// console.log(this.contactForm.value.subject,this.contactForm.value.email,this.contactForm.value.msg);
this.cService.sendMsg(this.contactForm.value.subject,this.contactForm.value.email,
this.contactForm.value.msg)
.subscribe(
response => {
alert("Thanks for contacting us");
},
error => {
alert(error);
}
);
export class ContactService {
url:string = '/web/contactus';
constructor (private http: Http) {
}
sendMsg(subject: string,email: string, msg: string): Observable<any> {
let body = JSON.stringify({
subject,
email,
msg
} || null);
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
console.log(body);
return this.http.post(this.url, body, options)
.map(res => res.json().data)
.do(data => console.log(JSON.parse(JSON.stringify(data || null ))))
.catch(this.handleError);
}
private extractData(res: Response) {
let body = res.json();
return body || { };
}
<form [formGroup]="contactForm" (submit)="sendMessage()">
<div class="form-group">
<label >Subject</label>
<input class="form-control" formControlName="subject" placeholder="Subject"/>
<span *ngIf="!contactForm.controls.subject.valid">required</span>
</div><!-- /.form-group -->
<div class="form-group">
<label>E-mail</label>
<input class="form-control" formControlName="email" placeholder="Email"/>
<span *ngIf="!contactForm.controls.email.valid">required</span>
</div><!-- /.form-group -->
<div class="form-group">
<label >Message</label>
<textarea class="form-control" formControlName="msg" rows="6"></textarea>
<span *ngIf="!contactForm.controls.msg.valid">required</span>
</div><!-- /.form-group -->
<button class="btn btn-primary pull-right" type="submit" [disabled]="!contactForm.valid">Post Message</button>
</form>
Looks like it is throwing some exception. In console click on the preserve log and then try the same. You may see some exceptions
I am just getting started with my project using Meteor/React.
In my "Customer.jsx"
Customer = React.createClass({
propTypes: {
//customer: React.PropTypes.object.isRequired
},
getInitialState: function () {
return { customers: [] };
},
mixins: [ReactMeteorData],
deleteThisCustomer(){
Meteor.call("removeCustomer", this.props.customer._id);
},
getMeteorData() {
let query = {};
//query = {checked: {$ne: true}};
return {
customers: Customers.find(query, {sort: {createdAt: -1}}).fetch()
};
},
handleSubmit(event) {
event.preventDefault();
// Find the text field via the React ref
var data = {};
data['first_name']= ReactDOM.findDOMNode(this.refs.customerFirstName).value.trim();
data['last_name'] = ReactDOM.findDOMNode(this.refs.customerFirstName).value.trim();
console.log(data);
Meteor.call("addCustomer", data);
// Clear form
ReactDOM.findDOMNode(this.refs.customerFirstName).value = "";
ReactDOM.findDOMNode(this.refs.customerLastName).value = "";
},
renderCustomers() {
return this.data.customers.map((customer) => {
return <Customer
key={customer._id}
customer={customer.first_name}
/>
});
},
singleCustomer(){
return(
<li className="customerClassName">
<button className="delete" onClick={this.deleteThisCustomer}>
×
</button>
<label>Here{ this.props.customer }</label>
</li>
);
},
render() {
return (
<div className="container">
<header>
<h1>Add new Customer</h1>
<form role="form" className="form-inline" onSubmit={this.handleSubmit} >
<div className="form-group">
<label>First Name</label>
<input type="text" className="form-control" ref="customerFirstName" placeholder="First Name." />
</div>
<div className="form-group">
<label>Last Name</label>
<input type="text" className="form-control" ref="customerLastName" placeholder="Last Name." />
</div>
<button type="submit" className="btn btn-default">Add Customer</button>
</form>
</header>
<ul>
{this.singleCustomer()}
</ul>
</div>
);
}
});
I keep getting an errors of all sorts every time I try to add first_name or last_name. Matter of fact I think that the whole order and structure of my render() is a nightmare.
Any ideas?
Any help would be appreciated.
Thanks in Advance :)