Issue posting data to api in react js - javascript

I am trying to send data to my contact form api through react but I am getting this problem
I tried to get input as a value to post through api when clicked on submit button but it is not working
error = the api should call like this https://edu.orgiance.com/api/contactus?secret=xxxxx-ac40-46a0-9c81-d48a1322f4bb&fname=test&email=test#test.com&mobile=8463274946&message=test
but it is calling like this
http://localhost:3000/?name=dfdfsd&email=dsffdsf%40gmail.com&phone=937285294&website=sxascsac&message=dscdscsfgcd#
My Code
import React from 'react';
const ContactForm = (props) => {
const { submitBtnClass } = props;
function handleClick() {
// Send data to the backend via POST
fetch('https://edu.orgiance.com/api/contactus?secret=f1794e34-ac40-46a0-9c81-d48a1322f4bb&fname=test&email=test#test.com&mobile=8463274946&message=', { // Enter your IP address here
method: 'POST',
mode: 'cors',
body: JSON.stringify(jsonData) // body data type must match "Content-Type" header
})
}
var jsonData = {
"contact": [
{
"fname": props.fname,
"email": props.email,
"mobile": props.phone,
"message": props.message
}
]
}
return (
<form id="contact-form" action="#">
<div className="row">
<div className="col-md-6 mb-30">
<input className="from-control" type="text" id="name" name="name" placeholder="Name" value={props.fname} required />
</div>
<div className="col-md-6 mb-30">
<input className="from-control" type="text" id="email" name="email" placeholder="E-Mail" value={props.email} required />
</div>
<div className="col-md-6 mb-30">
<input className="from-control" type="text" id="phone" name="phone" placeholder="Phone Number" value={props.phone} required />
</div>
<div className="col-md-6 mb-30">
<input className="from-control" type="text" id="website" name="website" placeholder="Your Website" required />
</div>
<div className="col-12 mb-30">
<textarea className="from-control" id="message" name="message" placeholder="Your message Here" value={props.message}></textarea>
</div>
</div>
<div className="btn-part" >
<button onClick={handleClick} className={submitBtnClass ? submitBtnClass : 'readon learn-more submit'} type="submit">Submit Now </button>
</div>
</form>
);
}
export default ContactForm;

It looks like you are creating a functional stateless component. That means your data needs to be passed in the props object, and if you are trying to access it anywhere in the ContactForm component, you would need to use this format: props.variablename . ie:
<input className="from-control" type="text" id="name" name="name" placeholder="Name" value={props.fname}required />

All of those variables are undefined. You can't initialize that jsonData object with variables that don't exist, you also can't set <input value={undefinedVariable} ... />
Since you are using form, an easy thing to do is to change it to look something like:
<form onSubmit={this.handleClick}>
...
<input type="submit" value="Submit" />
</form>
Then you can access the form data from the mouse event.
Example:
function handleClick(event) {
event.preventDefault();
const form = event.target;
const jsonData = {
"fname": form.name,
"email": form.email,
"mobile": form.phone,
"message": form.message
};
fetch('https://edu.orgiance.com/api/contactus?secret=f1794exxxxxx',
method: 'POST',
mode: 'cors',
body: JSON.stringify(jsonData)
})
}

Related

How can validate and send react form data to fire base data base?

I try it but not working
import React from "react";
import "./App.css";
import { useForm } from "react-hook-form";
import classNames from "classnames";
import { useState } from "react";
function App() {
const { register, handleSubmit,formState: { errors } } = useForm();
// console.log(errors);
const onSubmit = data => console.log(JSON.stringify(data));
const postData = async (e)=>{
e.preventDefault();
const res = await fetch("https://test1-5022f-default-rtdb.firebaseio.com/reactformData.json",
{
method:"POST",
header:{
"content-type":"application/json",
},
Here what I pass in body?
body:JSON.stringify(data)
}
)
};
There are many fields in my form but here I show some
return (
<div>
<div className="container">
<div className="form-group my-3 ">
<form name="Registration_form" id="Form" action="" method="POST" onSubmit={handleSubmit(onSubmit)}>
<div className="form-group my-3">
<label htmlFor="name">Name:</label>
<input
type="text"
name="Name"
id="Name"
className={classNames("form-control",{"is-invalid":errors.Name,})}
autoComplete="off"
{...register('Name',
{ required: true,
maxLength: 15,
pattern: /^[A-Za-z]+$/
})
}
/>
<span id="name" className="text-danger fw-bold">{errors.Name?.type === "required" && "This field is required"}</span>
<span id="name" className="text-danger fw-bold">{errors.Name?.type ==="maxLength" && "Length Should be less then 15"}</span>
<span id="name" className="text-danger fw-bold">{errors.Name?.type === "pattern" && "Digits are not allow"}</span>
</div>
</div>
<div className="form-group my-3">
<label htmlFor="email">Email: </label>
<input
type="text"
name="email"
id="email"
className={classNames("form-control",{"is-invalid":errors.email,})}
placeholder="email#example.com"
autoComplete="off"
{...register('email',
{
required: true,
pattern:/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/,
})
}
/>
<span id="mail" className="text-danger fw-bold">{errors.email?.type === "required" && "Email is required"}</span>
<span id="mail" className="text-danger fw-bold">{errors.email?.type === "pattern" &&"Invalid format"}</span>
</div>
<input type="submit" id="submit" value="submit" onClick={postData} className="btn btn-success my-3" />
</form>
That is code which I try but it not working anybody review it and give your valuable comments and suggestions
Basically I want form validation using react hook form,its done but when I stuck in passing data to fire base data base
when I use, useState then its override because react hook form already store it but how to pass it to data base with out useState??
Through react hook form
You should remove your onClick from the submit button and handle your form submission from the onSubmit event on the form. Send your form data to your firebase endpoint, from your onSubmit function like so.
<input type="submit" id="submit" value="submit" onClick={postData} <-- Remove this
className="btn btn-success my-3" />
...
const onSubmit = (data) => {
// All your form fields will the converted to json object (data)
// and will be handled by hooks form
console.log(data);
// send data to firebase API
const responseRaw = fetch(
"https://your-firebase-url",
{
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(data)
}
);
const response = responseRaw.json();
};

EmailJs is not sending email by React

I hope you are doing great, I am using Emailjs in React to get Emails. I configure Emailjs and it is properly sending test Emails but when I am trying to send from my project so it's not sending and even it is also not showing any error
Here is the template of the Email
Here is the ID and token which I hide but I am just showing this image to explain
clearly
(1) Here i import emailjs
import emailjs from '#emailjs/browser';
(2) Here is the function that will send the email, (Here in the fourth parameter I am just showing 5 characters as I hide in the above image )
function sendEmail(e) {
e.preventDefault();
emailjs.send('gmail', 'zaryabkhan864', e.target, 'G5CpT9*******')
.then((result) => {
console.log(result.text);
}, (error) => {
console.log(error.text);
});
e.target.reset()
}
(3) Here is the Form code
<form onSubmit={sendEmail}>
<div className="mb-3">
<label htmlFor="name" className="form-label">Your Name</label>
<input type="text" className="form-control" id="name" placeholder="Muhammad Zaryab Khan" name="name" />
</div>
<div className="mb-3">
<label htmlFor="email" className="form-label">Email address</label>
<input type="email" className="form-control" id="exampleFormControlInput1" placeholder="name#example.com" name="email" />
</div>
<div className="mb-3">
<label htmlFor="exampleFormControlTextarea1" className="form-label">Your Message</label>
<textarea className="form-control" id="Message" rows="5" name="message"></textarea>
</div>
<button type="submit" className="btn-theme">Send Message <i className="fa fa-paper-plane ms-2"></i></button>
</form>
Now I am receiving this error
add ref atribute for form, and ad useRef
const form = useRef<HTMLFormElement>(null);
after you should change e.target => form.current
const form = useRef();
const sendEmail = (e) => {
e.preventDefault();
emailjs.sendForm('service_id', 'template_id', form.current, 'user_id')
.then((result) => {
console.log(result.text);
}, (error) => {
console.log(error.text);
});
alert("Email Send");
};

function not pulling input data from local host

I am creating a simple login an sign up form that is used to create a user and store it in the local host. I have got the sign up form working as it should, but when I try and pull the information from the localhost, it just refreshes the page. Im just wondering how I can get the function to work correctly.
Here is my JS:
const signup = (e) => {
let user = {
firstName: document.getElementById("firstName").value,
lastname: document.getElementById("lastName").value,
email: document.getElementById("email").value,
username: document.getElementById("username").value,
password: document.getElementById("password").value,
confirm_password: document.getElementById("confirm_password").value,
};
localStorage.setItem("user", JSON.stringify(user));
console.log(localStorage.getItem("user"));
e.preventDefault();
alert("Signup Successful")
};
function login() {
var stored_username = localStorage.getItem('username');
var stored_password = localStorage.getItem('password');
var username1 = document.getElementById('username1');
var password2 = document.getElementById('password2');
if(username1.value == stored_username && password2.value == stored_password) {
alert('Login Successful.');
}else {
alert('Username or password is incorrect.');
}
}
document.getElementById("login-btn").addEventListener(type = click, login())
And here is my HTML:
<div class="bodyBx">
<section>
<div class="container">
<div class="user signinBx">
<div class="imgBx"><img src="https://images.unsplash.com/photo-1551034549-befb91b260e0?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60" style="width: 400px;" alt="" /></div>
<div class="formBx">
<form>
<h2>Sign In</h2>
<input type="text" id="username2" placeholder="Username" />
<input type="password" id="password2" placeholder="Password" />
<button id = "login-btn" type="submit" onclick="login();">Submit</button>
<p class="signup">
Need an account ?
Sign Up.
</p>
</form>
</div>
</div>
</div>
</section>
<!-- ================= Sign Up Form Start ================= -->
<section>
<div class="container">
<div class="user signupBx" id="section2">
<div class="imgBx"><img src="https://images.unsplash.com/photo-1555680206-9bc5064689db?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60" style="width: 400px;" alt="" /></div>
<div class="formBx">
<form role="form" onsubmit="signup(event)">
<h2>Sign Up</h2>
<input type="text" id="firstName" placeholder="First Name" />
<input type="text" id="lastName" placeholder="Last Name" />
<input type="email" id="email" placeholder="example#email.com..." />
<input type="text" id="username" placeholder="Username" />
<input type="password" id="password" placeholder="Password" />
<input type="password" id="confirm_password" placeholder="Confirm Password" />
<button type="submit">Submit</button>
</form>
</div>
</div>
</div>
</section>
</div>
Change the type of login button to button from submit, like below
<button id = "login-btn" type="button" onclick="login();">Submit</button>
If type=submit the form is posted to the url specified in the action attribute of the form, else to the same page if action is missing and you will see a page refresh.
Alternate method - You can also try return false; in your login()
Also your addEventListener should be like below, you don't have to provide type = click, the first param is of type string and second param is of type function. Check docs
document.getElementById("login-btn").addEventListener("click", login)
Localstorage can only store text. So you store a stringified object, which is fine, but you're trying to retrieve properties from it which don't exist.
Instead of:
var itm={someField:1};
localStorage.setItem("itm",JSON.stringify(itm));
//then later
localStorage.getItem("someField");
//localstorage doesnt know what someField is
You want:
var itm={someField:1};
localStorage.setItem("itm",JSON.stringify(itm));
//then later
itm = JSON.parse(localStorage.getItem("itm"));
someField = itm.someField
As for the refresh, check this out:
Stop form refreshing page on submit
TL;DR: Add e.preventDefault() in function login() (you'll have to change it to function login(e).

Why is the form data not saving to localstorage in react?

I have written this simple code to save my data to local storage but sometimes it works and sometimes it doesn't(no change to code). And it mostly saves empty data. what is going on here? Also the data is erased when the chrome window is closed, reopened and new data is entered.
This is the content inside return method.
<div className="wrapper">
<div className="content">
<h1>Get in touch!</h1>
<p>Connect with us by sending your views.</p>
</div>
<div className="form">
<div className="top-form">
<div className="inner-form">
<div className="label">Name</div>
<input
type="text"
placeholder="Enter your name"
id="contname"
/>
</div>
<div className="inner-form">
<div className="label">Email</div>
<input
type="text"
placeholder="Enter your email"
id="contemail"
/>
</div>
<div className="inner-form">
<div className="label">Phone</div>
<input
type="text"
placeholder="Enter your phone no."
id="contph"
required
/>
</div>
</div>
<div className="middle-form">
<div className="inner-form">
<div className="label">Subject</div>
<input
type="text"
placeholder="Enter the subject"
id="contsub"
/>
</div>
</div>
<div className="bottom-form">
<div className="inner-form">
<div className="label">Message</div>
<textarea
placeholder="Enter your message"
id="contmessage"
></textarea>
</div>
</div>
<div className="btn" id="sendmessage" onClick={ev => { this.addData(ev) }}>
Continue
</div>
</div>
and this is the portion to save data:
var contactData = [];
export default class Contact extends Component {
componentDidMount() {
window.scrollTo(0, 0)
}
addData = (ev) => {
ev.preventDefault();
let cdata = {
contactname: document.getElementById("contname").value,
contactphno: document.getElementById("contph").value,
contactemail: document.getElementById("contemail").value,
contactsubject: document.getElementById("contsub").value,
contactmessage: document.getElementById("contmessage").value
};
contactData.push(cdata);
localStorage.setItem("Contactinfo", JSON.stringify(contactData));
alert("Data Submitted succesfully!");
};
Like what others have said, Make use of the react setState. For storing in localStorage this video might help you https://www.youtube.com/watch?v=ZZS1irWSfxc

post data in server api using javascript

Hi I am very new to javascript and would like to ask how to post data in server api using javascript because when I click the button it won't save and does not return any error I am folowing this code here https://github.com/devamaz/fetchAPI/blob/master/index.html here is my js code:
function postData(event){
event.preventDefault();
let bookedUser = document.getElementById('bookedUser').value;
let bookedUserName = document.getElementById('bookedUserName').value;
let bookedEmail = document.getElementById('bookedEmail').value;
let dateBooked = document.getElementById('dateBooked').value;
let startTime = document.getElementById('startTime').value;
let endTime = document.getElementById('endTime').value;
let attendeesEmail = document.getElementById('attendeesEmail[]').value;
let bookingDesc = document.getElementById('bookingDesc').value;
fetch('http://localhost:8080/api/createBooking', {
method: 'POST',
headers : new Headers(),
body: JSON.stringify({
"bookedUser": bookedUser,
"bookedUserName": bookedUserName,
"bookedEmail":bookedEmail,
"dateBooked":dateBooked,
"startTime":startTime,
"endTime":endTime,
"attendeesEmail":attendeesEmail,
"bookingDesc":bookingDesc})
}).then((res) => res.json())
.then((booking) => alert('Data Sent'))
.catch((err)=>console.log(err))
}
and here is the html:
<form id="postData">
<div>
<input type="text" placeholder="Booked User" id="bookedUser">
</div>
<div>
<input type="text" placeholder="Username" id="bookedUserName">
</div>
<div>
<input type="text" placeholder="Email" id="bookedEmail">
</div>
<div>
<input type="date" placeholder="Date Booked" id="dateBooked">
</div>
<div>
<input type="time" placeholder="Start time" id="startTime">
</div>
<div>
<input type="time" placeholder="End time" id="endTime">
</div>
<div>
<input type="text" placeholder="Attendees Email" id="attendeesEmail[]">
</div>
<div>
<textarea id="bookingDesc" cols="20" rows="5"></textarea>
</div>
<input type="submit" value="SEND POST" onclick="postData();">
</form>
I have tested the code in the backend using postman and it works fine, Thank you in advance
It is almost all right. Just add the event param in postData() function.
Actually, there is no function postData() with no params.
So, it should be:
<input type="submit" value="SEND POST" onclick="postData(event);">

Categories

Resources