post data in server api using javascript - 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);">

Related

How to submit a form to an external page using C# ASP.NET?

I am trying to submit data from a form to an external web page, but after submitting it, a "Thank you for contacting us" page appears.
<form action="HTTPS://WWW.externalPage.com/encoding?encoding=UTF-8" method="POST" class="row">
<div class="col-6">
<label class="form-label" for="first_name">first_name: </label>
<input class="form-control mb-3" id="first_name" maxlength="40" name="first_name" required size="20" type="text" />
</div>
<div class="col-6">
<label class="form-label" for="last_name">last_name: </label>
<input class="form-control mb-3" id="last_name" maxlength="80" name="last_name" required size="20" type="text" />
</div>
<div class="col-6">
<label class="form-label" for="mobile">mobile: </label>
<input class="form-control mb-3" id="mobile" maxlength="40" name="mobile" required size="20" type="text" />
</div>
<div class="col-6">
<label class="form-label" for="email">email: </label>
<input class="form-control mb-3" id="email" maxlength="80" name="email" required size="20" type="text" />
</div>
<div class="col-6">
<label class="form-label" for="company">company: </label>
<input class="form-control mb-3" id="company" maxlength="40" name="company" required size="20" type="text" />
</div>
<div class="col-12 buttonSubmit">
<input class="btn btn-dark" type="submit" name="submit" onclick="Gracias()">
</div>
</form>
With this I am sending the data to the controller, but it must go to another web page (ex: http://web.ReciveData.com/)
I tried to send the form to the web page like this
<form action="http://web.ReciveData.com/" method="POST" class="row">
Submit button with "Thanks()" function:
<input class="btn btn-dark" type="submit" name="submit" onclick="Thanks()">
JavaScript:
function Thanks() {
window.location.href("http://web.MyWebPage.com/Home/Thanks")
}
Also try this:
document.addEventListener('DOMContentLoaded', function () {
var formulario = document.getElementById('form');
var validateName = function (e) {
if (formulario.first_name.value.length == 0) {
return false;
}
return true;
};
var validateEmail = function () {
if (formulario.email.value.length == 0) {
return false;
}
return true;
};
var validatePhone = function () {
if (formulario.mobile.value == "") {
return false;
}
return true;
};
var validateMsj = function () {
if (formulario.mensage.value.length == 0) {
return false;
}
return true;
};
var validar = function () {
return validateName() &&
validateEmail() &&
validatePhone() &&
validateMsj();
};
formulario.addEventListener("submit", handleSubmit);
async function handleSubmit(event) {
event.preventDefault();
if (validar()) {
const form = new FormData(this);
const response = await fetch(this.action, {
method: this.method,
body: form,
headers: {
'Accept': 'application/json'
}
});
if (response.ok) {
this.reset();
window.location.href = 'Http://web.MyWebPage.com/Home/Thanks'
}
}
}
});
But it does not work. Basically what I'm trying to do is load the data, send it to the external web page, and a web page that I created to thank the contact is displayed.
I can think of absolutely nothing, and what I found on the internet are mostly basic examples..
I changed the header to
headers: {
/* 'Accept': 'application /x-www-urlencoded'*/
'Access-Control-Allow-Origin:': 'https://www.externalPage.com'
}
And now the problem is on line fetch(this.action):
Uncaught (in promise) TypeError: Failed to execute 'fetch' on 'Window': Invalid name
at HTMLFormElement.handleSubmit

Issue posting data to api in react js

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)
})
}

How to run http post request in vue.js

I'm just learning Vue and I'm making http post request in vue.js and flask as the backend. When I run the program am getting 404 error code. I do not know how to debug the problem but when I test using postman it is working perfect. when I use axios but I am encountering 404.
Below is my frontend code :
<template>
<div>
<h3> {{msg}}</h3>
<p> we help you drive your business with the modern technology. </p>
<div class="alert alert-success" v-if="isSuccess">
Post Created Successfully
</div>
<form #submit.prevent='OnCreateTown' class="add-town">
<div class="form-control">
<label>task</label>
<input type="text" class ="form-control" v-model="text" name="text" placeholder="name" />
<input type="number" step="any" class ="form-control" v-model="text" name="text" placeholder="elevation" />
<input type="text" class ="form-control" v-model="text" name="text" placeholder="grid reference" />
<input type="number" step="any" class ="form-control" v-model="text" name="text" placeholder="longitude" />
<input type="number" step="any" class ="form- control" v-model="text" name="text" placeholder="latitude" />
<input type="text" class ="form- control" v-model="text" name="text" placeholder="postcode_secto" />
<input type="text" class ="form- control" v-model="text" name="text" placeholder="nuts_region" />
<input type="number" step="any" class ="form- control" v-model="text" name="text" placeholder="northing" />
<input type="number" step="any" class ="form- control" v-model="text" name="text" placeholder="easting" />
<input type="text" class ="form- control" v-model="text" name="text" placeholder="town_type" />
<input type="text" class ="form- control" v-model="text" name="text" placeholder="local_government_area" />
</div>
<input type="submit" value="submit" class="btn btn-block" />
</form>
</div>
</template>
<script>
import axios from 'axios';
export default {
name: 'CreateTown',
props:{
msg: String
},
data(){ // the data expected from the form
return{
form: {
name: '',
elevation: '',
grid_reference: '',
longitude: '',
latitude: '',
postcode_secto:'',
nuts_region:'',
northing:'',
easting :'',
town_type:'',
local_government_area:'',
isSuccess: false,
}
};
},
methods:{
OnCreateTown(){ // when the submit button is clicked, the form data is sent to the backend
axios.post('https://david.darwinist.io/proxy/5000/town.json', this.form)
.then((response) => {// checking response in the console
this.isSuccess = true;
console.log(response.data);
this.$emit('towncreated');
}).catch(err =>{
console.log(err)});
},
},
};
and this is my backend :
def addTown(session, town_dict):
# Try and get the Country from the database. If error (Except) add to the database.
town = Town()
# Add attributes
town.county = addGetCounty(session, town_dict["county"], town_dict["nation"])
town.name = town_dict["name"]
town.grid_reference = town_dict["grid_reference"]
town.easting = town_dict["easting"]
town.northing = town_dict["northing"]
town.latitude = town_dict["latitude"]
town.longitude = town_dict["longitude"]
town.elevation = town_dict["elevation"]
town.postcode_sector = town_dict["postcode_sector"]
town.local_government_area = town_dict["local_government_area"]
town.nuts_region = town_dict["nuts_region"]
town.town_type = town_dict["town_type"]

How to change tag's inner html to the username?

I am trying to change (div.class=loguser)'s innerhtml to the username that has logged in. To get the username, I wrote a function that gets input of username and password from the register_button which is inside (div#register). I wrote an object(addData) which takes the username and password and stores it in an array(datas). After putting it in the array, I made a function where it verifies if the username and password exists in the array. If it does exist, it is suppose the change the innerhtml to the username. But it is not working. And I cant even submit the form while registering.
let datas = [];
const addData = (ev) => {
ev.preventDefault();
let data = {
username: document.getElementById('rusername').value,
password: document.getElementById('rpassword').value
}
datas.push(data);
document.forms[0].reset();
}
document.addEventListener('DOMContentLoaded', () => {
document.getElementById('register_button').addEventListener('click', addData);
});
function isUserValid(username, password) {
var username = document.getElementById('lusername').value;
var password = document.getElementById('lpassword').value;
for (var i = 0; i < datas.length; i++) {
if (datas[i].username === username &&
datas[i].password === password) {
var name = username;
document.getElementsByClassName('loguser').innerHTML = username;
}
}
}
<body>
<div class="loguser">
<td>
<ul class="nav-area">
<li class="dropdown">User
</li>
</ul>
</td>
</div>
</tr>
</table>
</div>
<div class="wrapper">
<div class="login_box">
<div class="login_header">
<img src="images/alimama.png" alt=""> <br> Login or Register!
</div>
<div id="login">
<form action="" method="POST">
<input id="lusername" type="text" name="lusername" placeholder="Username" required>
<br>
<input id="lpassword" type="password" name="lpassword" placeholder="Password">
<br>
<input type="submit" name="login_button" value="Login">
<br>
Need an account? Register here!
</form>
</div>
<div id="register">
<form action="" method="POST">
<input id="rusername" type="text" name="rusername" placeholder="Username" required>
<br>
<input id="rpassword" type="password" name="rpassword" placeholder="Password" required>
<br>
<input id="register_button" type="submit" name="register_button" value="Register">
<br>
Already have an account? Sign in here!
</form>
</div>
</div>
</body>
isUserValid() shouldn't take username and password as parameters, since it gets them from the inputs. It should take an event parameter, so you can call it as an event listener.
document.getElementsByClassName() returns a NodeList. You need to use [0] to access the first match to set its innerHTML. You could also use document.querySelector(), it just returns the first match.
The login button doesn't have an ID. Add id="login_button" so you can add an event listener to it.
Instead of your loop you can use the find() method to search an array.
let datas = [];
const addData = (ev) => {
ev.preventDefault();
let data = {
username: document.getElementById('rusername').value,
password: document.getElementById('rpassword').value
}
datas.push(data);
document.forms[0].reset();
}
document.addEventListener('DOMContentLoaded', () => {
document.getElementById('register_button').addEventListener('click', addData);
});
function isUserValid(e) {
e.preventDefault();
var username = document.getElementById('lusername').value;
var password = document.getElementById('lpassword').value;
var found_user = datas.find(d => d.username === username && d.password === password);
if (found_user) {
document.getElementsByClassName('loguser')[0].innerHTML = found_user.username;
}
}
document.getElementById("login_button").addEventListener("click", isUserValid);
<body>
<div class="loguser">
User
</div>
<div class="wrapper">
<div class="login_box">
<div class="login_header">
<img src="images/alimama.png" alt=""> <br> Login or Register!
</div>
<div id="login">
<form action="" method="POST">
<input id="lusername" type="text" name="lusername" placeholder="Username" required>
<br>
<input id="lpassword" type="password" name="lpassword" placeholder="Password">
<br>
<input type="submit" id="login_button" name="login_button" value="Login">
<br>
Need an account? Register here!
</form>
</div>
<div id="register">
<form action="" method="POST">
<input id="rusername" type="text" name="rusername" placeholder="Username" required>
<br>
<input id="rpassword" type="password" name="rpassword" placeholder="Password" required>
<br>
<input id="register_button" type="submit" name="register_button" value="Register">
<br>
Already have an account? Sign in here!
</form>
</div>
</div>
</body>

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).

Categories

Resources