I've built a contact form and I'm trying to get my user inputted values to post using axios so I then get an email with the data inputted by the user.
I keep getting undefined values in my emails being sent. My server side is fine, I'm not to worried about that. What's the best approach for this?
document.querySelector(".contact-btn").addEventListener("click", sendIt);
function sendIt(event) {
event.preventDefault();
axios
.post("https://us-central1-selexin-website.cloudfunctions.net/app/sendemail", {
name: "",
email: "",
number: "",
message: "",
})
.then((res) => {
console.log(res);
});
}
this might work, also you can re-read documentation on POST Request Axios Documentation
For Live view how it works you can check on CODEPEN
const form = document.querySelector("form")
const input = document.querySelector("input")
const submitUser = () => {
axios.post('https://us-central1-selexin-website.cloudfunctions.net/app/sendemail', {
firstName: input.value,
})
.then(response => {
console.log(response);
})
.catch(error => {
console.log(error);
});
}
form.addEventListener("submit", (e) => {
submitUser()
e.preventDefault()
})
<form>
<input type="text">
<button type="submit">Submit</button>
</form>
Related
I am curious how to reset a q-form when the submit action is triggered. I run a function onSubmit but I am not sure how in that method to reset the q-form without having to do each field individually which is annoying. Here is my code:
//methods
const onSubmit = (event) => {
let jsonData =
{
FirstName: firstName.value,
LastName: lastName.value,
PhoneNumber: phoneNumber.value,
EmailAddress: emailAddress.value,
Message: message.value,
Token: token.value
}
api.post('/api/contactus', jsonData)
.then((response) => {
})
.catch(() => {
console.log('API request failed')
})
}
The documentation has an example of exactly what you want
// <q-form ref="myForm">
// to reset validations:
function reset () {
myForm.value.resetValidation()
}
or Options API:
this.$refs.myForm.resetValidation()
This function is shown in the documentation as being tied to a "Reset" button but there's no reason you can't use it after submitting as well.
i have form with three input fields with type as
i have design the form but how to send data as object in gcloud field ?
code for gcloud input field:
<label>gcloud keyfile json</label>
<TextareaAutosize
name="gcloud_keyfile"
type="text"
id="gcloud_keyfile"
value={values.gcloud_keyfile}
onChange={handleChange}
/>
while for form submission i have used formik and code is shown below :
const initialValues = {
organ: "",
env: "",
gcloud_keyfile: "" ,
};
const { values, errors, touched, handleBlur, handleChange, handleSubmit } =
useFormik({
initialValues,
validationSchema: GcpSchema,
onSubmit: async (values, action) => {
try {
let response = await axios.post(
`${state.baseUrl}accounts/gcp/`,
{
organization: values.organ,
environment: values.env,
gcloud_keyfile_json: JSON.stringify(values.gcloud_keyfile),
});
if (response.status === 200) {
setMsg("You Are Successfully Create the Account");
action.resetForm();
return Promise.resolve();
}
} catch (error) {
console.error("There was an error!", error);
}
},
});
i have used json stringify but that doesn't work
i used JSON.parse(gcloud_keyfile_json)
to convert string into object and apply validation on the input field to take only object value
I want to add some company details to mongo DB, and the details include a company logo. So I want to upload the picture to Cloudinary and then save the URL in Mongo DB with the other details.
But my code doesn't seem to work. When I fill the form and click on submit, the image gets uploaded to Cloudinary but it does not get saved in the Database.
To store the image
const [ companyLogo, setCompanyLogo] = useState("");
const [ companyLogoURL, setCompanyLogoURL] = useState("");
Function to execute on submit
const handleCompanySubmit = (evt) => {
evt.preventDefault();
const data = new FormData()
data.append("file", companyLogo)
data.append("upload_preset", "Sprint")
data.append("cloud_name", "sprint-ccp")
fetch("https://api.cloudinary.com/v1_1/sprint-ccp/image/upload",{
method:"post",
body:data
})
.then(res => res.json())
.then(data => {
setCompanyLogoURL(data.url)
})
.catch(err => {
console.log(err)
})
//check for empty fields
if (
isEmpty(companyName) ||
isEmpty(companyAddress) ||
isEmpty(companyRegNumber) ||
isEmpty(companyContactNumber)
) {
setCompanyErrorMsg("Please Fill All The Fields");
}else {
let formData = new FormData();
formData.append('companyName', companyName);
formData.append('companyAddress', companyAddress);
formData.append('companyRegNumber', companyRegNumber);
formData.append('companyContactNumber', companyContactNumber);
formData.append('companyLogo', companyLogoURL);
setCompanyLoading(true);
addCompany(formData)
.then((response) => {
setCompanyLoading(false);
setCompanySuccessMsg(response.data.successMsg)
setCompanyData({
companyName: "",
companyAddress: "",
companyRegNumber: "",
companyContactNumber: ""
});
})
.catch((err) => {
setCompanyLoading(false);
setCompanyErrorMsg(err.response.data.errorMsg)
})
}
};
const handleCompanyLogo = (evt) => {
setCompanyLogo(evt.target.files[0])
};
frontend view
<form className="register-form" onSubmit={handleCompanySubmit} noValidate>
<label className="text-secondary">Company Logo :</label>
<input type="file" className="form-control" onChange={handleCompanyLogo}/>
//remaining input fields
<button className="btn btn-info submitButton" >Submit</button>
</form>
api for adding company
export const addCompany = async (data) => {
const config = {
headers: {
"Content-Type": "application/json",
},
};
const response = await axios.post(
"http://localhost:5000/api/auth/clients/company",
data,
config
);
return response;
};
controller in backend
exports.addNewCompany = async(req,res)=>{
const {
companyName,
companyAddress,
companyRegNumber,
companyContactNumber,
companyLogo
} = req.body;
const company = await Company.findOne({ companyName });
if (company) {
return res.status(400).json({
errorMsg: `${req.body.companyName} already exists`,
});
}
try{
const newCompany = new Company();
newCompany.companyName = companyName;
newCompany.companyAddress = companyAddress;
newCompany.companyRegNumber = companyRegNumber;
newCompany.companyContactNumber = companyContactNumber;
newCompany.companyLogo = companyLogo;
await newCompany.save();
res.json({
successMsg: `${req.body.companyName} Company Added Successfully`
});
} catch (err) {
console.log("clientsController error - Add Company ", err);
res.status(500).json({
errorMsg: "Server Error. Please Try again",
});
}
};
The error i get in the console is this
clientsController error - Add Company Error: Company validation failed: companyLogo: Path companyLogo is required.
at ValidationError.inspect
(C:\CCP\sd08_2021\Backend\node_modules\mongoose\lib\error\validation.js:47:26)
Can you please help me out ?
I think that your error is caused by a more trivial problem :
When you send the POST request with fetch, you don't actually wait for its completion (it's a promise), so the code in the if ... else {...} statement is executed before the termination of the fetch() !
setCompanyLogoURL(data.url) has not been called yet, so formData.append('companyLogo', companyLogoURL); set a blank string instead of the value returned by the call to the Cloudinary API.
The solution would be to make handleCompanySubmit async, and to await for the fetch() promise completion.
I need to register a new user with API. Back-end developer gave me screenshot how he implemented registration on PhP. Unfortunately, he doesn't know react so he can't help me. I already have input forms saving them in state. Could you please help me what's going on in the picture below and how make registration on React.
and my code. Let me know if I missing any field. I have url , but I dont know where to add user/create, company/create links:
signUp(event) {
event.preventDefault()
const formdata = new FormData()
formdata.append("email", this.state.userLogin.email)
formdata.append("password", this.state.userLogin.password)
formdata.append("name", this.state.userLogin.name)
formdata.append("companyName", this.state.userLogin.companyName)
formdata.append("region", this.state.userLogin.region)
axios
.post("http://dev.***********.com/", formdata)
.then(res => {
if (res.data) {
console.log('success')
this.props.history.push("/settings")
}
})
.catch(error => {
console.log(error)
})
}
you are missing some fields for the post request,
but this is how I would do it:
const data = {
username: YOU_NEED_THIS,
label: YOU_NEED_THIS,
label_short: YOU_NEED_THIS,
email: this.state.userLogin.email,
password: this.state.userLogin.password,
name: this.state.userLogin.name,
companyName: this.state.userLogin.companyName,
region: this.state.userLogin.region,
};
axios
.post("http://dev.***********.com/", data)
.then(.....)
In my React application, I have a form with only username and password (later I will add "confirm password" as well), when submitting a request with JSON should be send that contains the email and password in its body.
Password can only be accepted after few checks and if it passes all of those conditions then it will be accepted.
render() {
return (
<form className="demoForm" onSubmit={this.handleUserInput} >
.
.
.
.
<button type="submit" className="btn btn-primary" disabled={!this.state.formValid}>Sign U p</button>
</form>
);
}
handleUserInput = (e) => {
const name = e.target.name;
const value = e.target.value;
this.setState({[name]: value}, () => { this.validateField(name, value) });
axios.post('****', {
value
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
}
I am using axios like above, my problem is that I dont know what should be instead of this ****, I am using local host. Is this a good way to do this?
You should add the address you are posting your call to. (i.e. /api/validate_user)
Just on a side note, try separating your actions.
onChangeHandler(e) {
e.preventDefault()
const { value, id} = e.target
this.setState({
[id]: value
})
}
to update the state and then to submit
onSubmitHandler(e) {
var self = this;
e.preventDefault()
const { userName, password } = this.state;
// Do validation of password
axios.post('/api/validateUser', {
user: userName,
password: password
}).then(e => {
if(e.success){
console.log("success")
}
else if(e.error) {
console.log("error logging in")
}
})
}