Post json data using fetch api failed - javascript

Am new in javascript , and am trying to POST data with an API endpoint but data is not posting , I have printed in the console , but I see Slow network is detected. See https://www.chromestatus.com/feature/5636954674692096 for more details. Fallback font will be used while loading: https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/fonts/fontawesome-webfont.woff2?v=4.7.0 in Google chrome.
But internet connection is good and stable.
This is my vanilla javascript for posting data :
function onSignUp() {
signupform
var email = document.signupform.email_edt.value;
var driver_rb = document.getElementById("driver_rb").checked;
var password_edt = document.signupform.password_edt.value;
var r_password_edt = document.signupform.r_password_edt.value;
var url = 'https://tuvuge-app.herokuapp.com/api/v1/signup';
//var data = {username: 'example'};
var data = {
username: email,
email: email,
password: password_edt,
isDriver: 'True'
};
fetch(url, {
method: 'POST',
body: JSON.stringify(data), // data can be `string` or {object}!
headers: {
'Content-Type': 'application/json'
}
}).then(res => res.json())
.catch(error => console.error('Error:', error))
.then(response => console.log('Success:', response));
}
Then I attached the onSignUp() function to the button in html as below :
<form class="admin-modal-content" name="signupform" onSubmit="onSignUp();" action="index.html" method="post">
<div class="container">
<h4>Sign Up</h4>
<p>Please fill in this form to create an account.</p>
<hr>
<label for="email">
<b>Email</b>
</label>
<input type="email" placeholder="you#example.com" id="email_edt" name="email_edt" required>
<label for="email">
<b>Select an Option</b>
</label>
<p>
<input type="radio" name="driver_rb" value="driver" id="driver_rb">
<label>Driver</label>
</p>
<p>
<input type="radio" name="passenger_rb" id="passenger_rb" value="passenger">
<label>Passenger</label>
</p>
<label for="psw">
<b>Password</b>
</label>
<input type="password" placeholder="Enter Password" id="password_edt" name="password_edt" required>
<label for="psw-repeat">
<b>Repeat Password</b>
</label>
<input type="password" placeholder="Repeat Password" id="r_password_edt" name="psw-r_password_edt" required>
<div class="clearfix">
<button type="submit" class="btn">Sign Up</button>
</div>
</form>
What am I missing ,because the endpoint has a message it brings when there's a success or failure of data posting , but I see the above message.
What am I missing?

Related

Sending data by html form (POST method)

I have a question regarding POST method. I'm trying to record the data from form into txt file. But the string is empty (in txt file I have only "The request: ")
HTML:
<form
action=""
method="POST"
id="form"
class="section-contact-me-form"
>
<fieldset>
<div class="section-contact-me-input">
<label class="section-contact-me-input__label" for="name">Name*</label>
<input
type="text"
name="name"
class="section-contact-me-input__input _req"
id="name"
>
</div>
<div class="section-contact-me-input">
<label class="section-contact-me-input__label" for="email">E-mail*</label>
<input
type="text"
name="email"
id="email"
class="section-contact-me-input__input _req _email"
>
</div>
<div class="section-contact-me-input">
<label class="section-contact-me-input__label" for="phone">Phone</label>
<input
type="text"
name="phone"
id="phone"
class="section-contact-me-input__input phone"
>
</div>
<div class="section-contact-me-textarea">
<label class="section-contact-me-textarea__label" for="message">Your message*</label>
<textarea
rows="10"
cols="45"
name="message"
id="message"
class="section-contact-me-textarea__textarea _req"
></textarea>
</div>
</fieldset>
<div id="submit" class="submit-button">
<button class="submit-button_active">Send data</button>
</div>
</form>
JS:
form.addEventListener("submit", formSend);
async function formSend() {
const formData = {
name: document.querySelector("#name").value,
email: document.querySelector("#email").value,
phone: document.querySelector("#phone").value,
message: document.querySelector("#message").value
};
const formDatatoSend = JSON.stringify(formData)
sendData("http://localhost:3000/101_susov_newDesign/contactme.php", formDatatoSend)
.then(() => {
form.reset();
})
.catch((err) => console.log(err))
};
const sendData = async (url, data) => {
const response = await fetch (url, {
method: "POST",
body: data
})
if (!response.ok) {
throw new Error (`URL with error ${url}, status ${response}`)
};
return await response;
};
PHP:
<?php
$value = $_POST['value'];
$f = fopen('file.txt', 'a+');
fwrite($f, "The request: ".$value."\n");
fclose($f);
?>
So, the server works properly: there is the access to php code and txt file refreshes every time I use form button, but the content sended from form is empty. As I told before in txt file I have only "The request: "
Where is the eror in my code? Thanks in advance and have a good day!
You do not have a field called value so $_POST['value'] doesn't return anything. You can get the value of each field by adding it's name attribute as the array key:
$value = $_POST['phone'] would return 'The request: PHONE_NUMBER' into your TXT file.
$value = json_encode($_POST) would return the whole post into your TXT file
This should work:
$value = json_encode($_POST);

fetch() API with NodeJS server makes req.redirect() not working [duplicate]

This question already has answers here:
What is the difference between post api call and form submission with post method?
(2 answers)
Closed 11 months ago.
I have a login/signup system using nodeJS. now the problem is when i use fetch() method on the client javascript side the res.redirect() method does not work. what could be the problem with fetch() API thats stopping the res.redirect method on the server.js ? the last line does not work the res.redirect('/index.html');
maybe there is another way to submit my form on the client javascript without using the fetch() method?
here is my code for my client javascript
const MyForm = document.getElementById("myform"); const username = document.getElementById("username") const email = document.getElementById("email"); const password=document.getElementById("password"); const confirmPassword = document.getElementById("confirm-password-input"); const alertMessege = document.getElementById("message");
MyForm.addEventListener('submit' , function(event) { event.preventDefault();
MatchingPassword();
});
function MatchingPassword(){
let pass = password.value.trim();
let confpass = confirmPassword.value.trim();
if(pass != 0) {
if(pass == confpass){
alertMessege.textContent = "";
console.log("Password Match");
fetch('SignUp.html' , {
method: 'POST',
headers:{
'content-Type': 'application/json',
},
body: JSON.stringify({
username: username.value,
email: email.value,
password: password.value,
}),
});
console.log("Fetched and posted");
}
else{
alertMessege.textContent = "Password doesn't match! ";
console.log("Password Does not Match!");
}
}
}
and here is the server.js
the last line does not work the
res.redirect('/index.html');
that is in this piece of code
// app.post sign up form
app.post("/SignUp.html", async function(req, res){ const {username, email, password} = req.body;
let user = await UserModel.findOne({email});
if (user){
console.log("User Already Exists");
return res.redirect("/SignUp.html");
}
user = new UserModel({
username,
email,
password,
});
await user.save();
console.log(user)
res.redirect('/index.html');
});
my html body
<body>
<form id="myform" action="SignUp.html" method="POST"> Create an account <div class="card"> <div class="card-body">
<!-- full name input-->
<div class="form-group">
<label for="fullname-input">Full name</label>
<input type="text" class="form-control" id="username" placeholder="Enter full name" name="username" maxlength="50" required>
</div>
<!-- email input-->
<div class="form-group">
<label for="email-input">Email address</label>
<input type="email" class="form-control" id="email" aria-describedby="emailHelp" placeholder="Enter email" name="email" pattern="^[\w]{1,}[\w.+-]{0,}#[\w-]{2,}([.][a-zA-Z]{2,}|[.][\w-]{2,}[.][a-zA-Z]{2,})$" title="Must be a valid email. example#example.com" required>
</div>
<!-- password input
minimum set to 8 chars(must have one letter,one number and a symbol)
-->
<div class="form-group">
<label for="password-input">Password</label>
<input type="password" class="form-control" id="password" placeholder="Password" name="password" pattern="(?=.*\d)(?=.*[!##\$%\^&\*])(?=.*[A-Za-z]).{8,}" title="Password must be at least 8 characters and at least one number, one letter and one symbol" required>
</div>
<!--Confirm password must match password input-->
<div class="form-group">
<label for="confirm-password-input">Confirm password</label>
<input type="password" class="form-control" id="confirm-password-input" placeholder="Confirm password" required>
</div>
<div>
<small id="message"> </small>
</div>
<br>
<input type="submit" class="btn btn-primary btn-block" id="sign-up-button" value="Register">
<br>
<p>Already have an account? Sign In </p>
</div>
</div>
</form>
</body>
the fetch api is not capable to change your browser url, that is why you should redirect on the front-end rather than the backend
on your back-end instead of:
res.redirect('/index.html')
use
res.json({success : true}) //if signup successfully
and on the front end just add some callback functions to your fetch
fetch('SignUp.html' , {
method: 'POST',
headers:{
'content-Type': 'application/json',
},
body: JSON.stringify({
username: username.value,
email: email.value,
password: password.value,
})
})
.then(result => result.json())
.then(data => {
if(data.success)
window.location.href = "/index.html"
})

How to push radio data in form submit

I'm using this code to send data to my sheet.
For The FullName, Phone, Address, ..., data is sent with no problem.
But I'm blocked to split and push value input radio data and send it to my sheet.
Example if the second input of radio is selected ( sku_order_2|quantity2|price22 )
sku = sku_order_2 quantity = quantity2 price = price22
const scriptURL = 'https://script.google.com/........'
const form = document.forms['formName']
form.addEventListener('submit', e => {
e.preventDefault()
fetch(scriptURL, { method: 'POST', body: new FormData(form)})
.then(response => console.log('Success!', response))
.catch(error => console.error('Error!', error.message))
})
<form action="" name="formName" method="post" id="formName" data-redirect="" class="form">
<input id="order1" class="variant" type="radio" name="order" value="sku_order_1|quantity1|price15" hidden="" checked="">
<input id="order2" class="variant" type="radio" name="order" value="sku_order_2|quantity2|price22" hidden="">
<input id="order2" class="variant" type="radio" name="order" value="sku_order_3|quantity3|price26" hidden="">
<input id="fullname" class="input" type="text" placeholder="Fullname" name="fullname" required="">
<input id="phone" class="input" type="number" placeholder="Phone" name="phone" required="">
<input id="address" class="input" type="text" placeholder="Address" name="address" required="">
</form>
Use the FormData methods (https://developer.mozilla.org/en-US/docs/Web/API/FormData)
You can get the order value with formData.get('order')
than you can split (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split) the string and use the result to append the fields: sku, quantity, price.
const scriptURL = 'https://script.google.com/........'
const form = document.forms['formName']
form.addEventListener('submit', e => {
e.preventDefault()
const formData = new FormData(form)
const order = formData.get('order').split('|') // Split the string using '|' into an array [sku, quantity, price]
formData.append('sku', order[0])
formData.append('quantity', order[1])
formData.append('price', order[2])
formData.delete('order')
fetch(scriptURL, { method: 'POST', body: formData})
.then(response => console.log('Success!', response))
.catch(error => console.error('Error!', error.message))
})
<form action="" name="formName" method="post" id="formName" data-redirect="" class="form">
<div>
<input id="order1" class="variant" type="radio" name="order" value="sku_order_1|quantity1|price15" checked=""> 1
<input id="order2" type="radio" class="variant" name="order" value="sku_order_2|quantity2|price22"> 2
<input id="order3" class="variant" type="radio" name="order" value="sku_order_3|quantity3|price26"> 3
</div>
<input id="fullname" class="input" type="text" placeholder="Fullname" name="fullname" required="">
<input id="phone" class="input" type="number" placeholder="Phone" name="phone" required="">
<input id="address" class="input" type="text" placeholder="Address" name="address" required="">
<input type="submit" value="Send">
</form>
If you want to split the order property, you can do the following:
Get the order values from formData
Split the retrieved order value by separator |
Map the exploded order values to their representatives sku, quantity and price
add sku, quantity and price to formData
See this fiddle: https://jsfiddle.net/Lxujkotp/1/
Extended Code:
form.addEventListener('submit', e => {
var data = new FormData(form);
var order = data.get('order');
var orderParts = order.split('|');
// WARNING: if the "order values" does not have a fix ordering, map the values here more sophisticated!
var sku = orderParts[0];
var quantity = orderParts[1];
var price = orderParts[2];
e.preventDefault();
data.delete('order');
// approach 1: plain
data.set('sku', sku);
data.set('quantity', quantity);
data.set('price', price);
// alternative approach 2: nested
// data.set('order', JSON.stringify({
// sku: sku,
// quantity: quantity,
// price: price
// }));
fetch(scriptURL, { method: 'POST', body: data })
.then(response => console.log('Success!', response))
.catch(error => console.error('Error!', error.message))
});

Fetch not giving me the response

I have a login form with username and password field. I am trying to send the username and password to my django api. But nothing shows up in console. I am trying to print response in console. THis is my code
export default class LogInComponent extends Component {
handleLoginButtonClick() {
fetch('https://myname-backend.appspot.com',{
method: "POST",
type: 'json',
data: {password:document.getElementById("username").value,
username:document.getElementById("password").value
}
})
.then(function(response) {
// We get a JWT back.
let jwt = response.auth_token;
// We trigger the LoginAction with that JWT.
console(response);
//LoginActions.loginUser(jwt);
return response;
});
}
render() {
return (
<div className="LoginPage">
<div className="login-page">
<div className="form">
<form className="register-form">
<input type="text" placeholder="name"/>
<input type="password" placeholder="password"/>
<input type="text" placeholder="email address"/>
<button>create</button>
<p className="message">Already registered? Sign In</p>
</form>
<form className="login-form">
<input id="username" type="username" placeholder="username"/>
<input id="password" type="password" placeholder="password"/>
<button onClick={this.handleLoginButtonClick}>login</button>
<p className="message">Not registered? Request Username and Password</p>
</form>
</div>
</div>
<img className="Logo_Tessact_White" src="./dev/js/images/TESSACT_logo_white.png"/>
</div>
);
}
}
This my api call guide
What am I doing wrong?
Updated Code
export default class LogInComponent extends Component {
handleLoginButtonClick() {
fetch('https://myname-backend.appspot.com/auth/login', {
method: "POST",
type: 'json',
data: {
"password": document.getElementById("password").value,
"username": document.getElementById("username").value
}
}
)
.then(function(response) {
return response.json();
})
.then(function(data) {
// We get a JWT back.
let jwt = data.auth_token;
// We trigger the LoginAction with that JWT.
console.log(data);
//LoginActions.loginUser(jwt);
return data;
});
//browserHistory.push("app")
// console.log('clicked')
// console.log(document.getElementById("password").value);
}
render(){
return (
<div className="LoginPage">
<div className="login-page">
<div className="form">
<form className="register-form">
<input type="text" placeholder="name"/>
<input type="password" placeholder="password"/>
<input type="text" placeholder="email address"/>
<button>create</button>
<p className="message">Already registered? Sign In</p>
</form>
<form className="login-form">
<input id="username" type="username" placeholder="username"/>
<input id="password" type="password" placeholder="password"/>
<button onClick={this.handleLoginButtonClick}>login</button>
<p className="message">Not registered? Request Username and Password</p>
</form>
</div>
</div>
<img className="Logo_Tessact_White" src="./dev/js/images/TE_logo_white.png"/>
</div>
);
}
Still not able to get the console printing the response.
The url seems to be wrong. You have:
fetch('https://myname-backend.appspot.com',{
and should have:
fetch('https://myname-backend.appspot.com/login',{
You are passing incorrect data i.e username in password and password in username.
Use
data: {password:document.getElementById("password").value,
username:document.getElementById("username").value
}

AngularJS $scope data is not showing any thing

The submitform() does not take the for datas to the function. Chrome console says ReferenceError: $ is not defined. Is there anything wrong in the code ?
var app = angular.module('app', []);
app.controller('testimonialController', function($scope, $http) {
$scope.formdata = {};
$scope.submission = false;
$scope.submitform = function($scope, $http) {
$http({
method: 'POST',
url: 'sendmail.php',
data: $.param($scope.formdata), // pass in data as strings
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
} // set the headers so angular passing info as form data (not request payload)
}).
success(function() {
console.log("send successfuly");
}).
error(function() {
console.log("It is failed");
});
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div id="contact-form" ng-controller="testimonialController" ng-app="app">
<h1 id="contact">Contact</h1>
<pre>Form data: {{formdata}}</pre>
<p>Take a look around the site, Do you have something in mind you would like to let me know .You can contact me by filling the form below or email hello#athimannil.com</p>
<form ng-submit="submitform()">
<div class="form-wrap">
<label for="name">Name</label>
<input type="text" name="name" ng-model="formdata.name" placeholder="Name" required>
<br>
</div>
<div class="form-wrap">
<label for="email">Email</label>
<input type="email" name="email" ng-model="formdata.email" placeholder="Email" required>
<br>
</div>
<div class="form-wrap">
<label for="comment">Message</label>
<br>
<textarea name="comment" id="comment" ng-model="formdata.comment" placeholder="Comment" cols="30" rows="10" required></textarea>
<br>
</div>
<input type="submit" name="submit" value="Send">
</form>
</div>
This is the console message when use
$http({
method : 'POST',
url : 'sendmail.php',
data : $scope.formdata, // pass in data as strings
headers : { 'Content-Type': 'application/x-www-form-urlencoded' } // set the headers so angular passing info as form data (not request payload)
}).
data: $.param($scope.formdata)
This line uses jQuery's $.param method. You have to include it, if you want to use it

Categories