Clear form data after submission - javascript

I'm new to programming and I'm using google spreadsheets to receive data from a simple registration form on my static site. Everything is working but I would like to reset the form data after sending the data. I already researched right here in the forum and I did not find any solution that did not erase the data for sending in the reset.
<script>
const scriptURL = 'url-sheet'
const form = document.forms['submit-to-google-sheet']
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))
})
</script>
<form class="apply" id="apply" name="submit-to-google-sheet">
<div class="j-row apply-field">
<div class="j-col j-col-3">
<label for="Gamertag">Gamertag <span class="gold" title="Required field">*</span></label>
</div>
<div class="j-col j-col-8 push-1">
<input type="text" name="gamertag" placeholder="gamertag" maxlength="12" required>
</div>
</div>
<div class="j-row apply-field">
<div class="j-col j-col-3">
<label for="Discord">Discord <span class="gold" title="Required field">*</span></label>
</div>
<div class="j-col j-col-8 push-1">
<input type="text" name="discord" placeholder="usuário" maxlength="32" required>
<span class="gold">#</span>
<input type="number" name="id" placeholder="1234" maxlength="6" required>
</div>
</div>
<div class="j-row apply-field">
<div class="j-col j-col-3">
<label for="Refferal">Reference?</label>
</div>
<div class="j-col j-col-8 push-1">
<input type="text" name="ref" placeholder="Name" maxlength="20">
</div>
</div>
<input type="text" name="submit" style="display:none" />
<div class="j-row apply-field">
<div class="j-col j-col-12">
<button class="button full-width black" type="submit">Submit</button>
</div>
</div>
</form>

To set the form back to its initial state call reset() on it. Given your logic it would make sense to do this after the AJAX request was successful, so place the call in the then() handler function:
form.addEventListener('submit', e => {
e.preventDefault()
fetch(scriptURL, { method: 'POST', body: new FormData(form)}).then(response => {
console.log('Success!', response)
form.reset();
}).catch(error => console.error('Error!', error.message))
})

Add this to your javascript:
$( '#apply' ).each(function(){
this.reset();
});

try document.getElementById("apply").reset();
<script>
const scriptURL = 'url-sheet'
const form = document.forms['submit-to-google-sheet']
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))
document.getElementById("apply").reset();
})
</script>

Related

Fetch API post data is not transferring data to views.py in Django

I am creating a Django app and for that I am trying to access data received from a POST request, using JavaScript fetch API but it is not working. I can see that the page is not refreshing after hitting the submit button because of the e.preventDefault(); but the values are not getting fetched at all. I can't get what my mistake is. I have tried to remove all unnecessary parts to debug. Please let me know where am I going wrong.
views.py
def home(request):
if request.method=="POST":
options_value=request.POST['dropdown_val']
value=request.POST['val']
print(options_value,value)
index.html
<form method="POST" action="" id="form">
{% csrf_token %}
<div class="d-flex justify-content-center" style="margin-top: 6rem">
<div class="dropdown" style="display: flex" id="dropdown">
<select
class="form-select"
aria-label="Default select example"
name="options_value"
id="dropdown_val"
>
<option disabled hidden selected>---Select---</option>
<option value="1">Profile UID</option>
<option value="2">Employee ID</option>
<option value="3">Email ID</option>
<option value="4">LAN ID</option>
</select>
</div>
<div class="col-3 bg-light" style="margin-left: 2rem">
<input
type="text"
class="form-control"
id="in3"
type="text"
placeholder="Enter Value"
name="value"
id="value"
/>
</div>
<div style="margin-left: 2rem">
<input
class="btn btn-primary"
type="submit"
value="Submit"
style="background-color: #3a0ca3"
/>
</div>
</div>
</form>
<script>
let form = document.getElementById("form");
let dropdown_val = document.getElementById("dropdown_val");
let val = document.getElementById("value");
const csrf = document.getElementsByName("csrfmiddlewaretoken")[0].value;
form.addEventListener("submit", (e) => {
e.preventDefault();
const newform = new FormData();
newform.append("dropdown_val", dropdown_val.value);
newform.append("val", val.value);
newform.append("csrfmiddlewaretoken", csrf);
fetch("", {
method: "POST",
body: newform,
})
.then(response => response.json())
.then(data => {
console.log('Success:', data);
})
.catch(error => {
console.error('Error:', error);
});
});
</script>
The problem is that you have 2 id tags in the input field:
<input
type="text"
class="form-control"
id="in3" <--- problem is here
type="text"
placeholder="Enter Value"
name="value"
id="value"
/>
remove the id='in3' and it should work. You can check that error in the Console of the browser when you submit the form.

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

Submitting a form through Javascript via POST method

index.js
document.addEventListener('DOMContentLoaded', function() {
document.querySelector('#compose').addEventListener('click', compose_email);
document.querySelector('#compose-form').onsubmit = send_email;
// By default, load the inbox
load_mailbox('inbox');
});
function compose_email() {
// Show compose view and hide other views
document.querySelector('#compose-view').style.display = 'block';
// Clear out composition fields
document.querySelector('#compose-recipients').value = '';
document.querySelector('#compose-subject').value = '';
document.querySelector('#compose-body').value = '';
}
function send_email()
{
const recipients = document.querySelector('#compose-recipients').value;
const subject = document.querySelector('#compose-subject').value;
const body = document.querySelector('#compose-body').value;
//console.log(recipients)
fetch('/emails', {
method: 'POST',
body: JSON.stringify({
recipients: recipients,
subject: subject,
body: body,
})
})
.then(response => response.json())
.then(result => {
// Print result
console.log(result);
});
}
inbox.html
<div id="compose-view">
<h3>New Email</h3>
<form id="compose-form">
<div class="form-group">
From: <input disabled class="form-control" value="{{ request.user.email }}">
</div>
<div class="form-group">
To: <input id="compose-recipients" class="form-control">
</div>
<div class="form-group">
<input class="form-control" id="compose-subject" placeholder="Subject">
</div>
<textarea class="form-control" id="compose-body" placeholder="Body"></textarea>
<input type="submit" class="btn btn-primary"/>
</form>
</div>
Submitting a form through Javascript via POST method but I am getting an output of GET /? HTTP/1.1" 200 1667 in terminal..
It should be 201 via POST
When I am writing the fetch function in Console.It is working fine
After submitting the form it is just returning back to the inbox page.
Since you are doing a "fetch" in your code, you should prevent the default form submission on the "submit" button click (This this the default behaviour). To achieve this you can receive the "event" as a parameter in the "send_email" function and then do a "event.preventDefault()".
function send_email(event) {
// Your code
...
// Prevent the default form submission
event.preventDefault();
}
More details # https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onsubmit

How can I get my search bar work with Google?

I have this search bar and I can't connect it to Google as a search functionality, I tried with this guy's code but I couldn't:
<form id="frmSearch" action="index.html" class="searchform order-sm-start order-lg-last">
<div class="form-group d-flex">
<input type="text" class="form-control pl-3" placeholder="Buscar">
<button type="submit" placeholder="txtsearch" class="form-control search"><span class="fa fa-search"></span></button>
</div>
</form>
Thanks in advance!
You could use an AJAX call to a php page where you are going to implement cURL to get data from google searching url!
Of course you will need to code your own cURL in PHP: PHP + curl, HTTP POST sample code?
here you can find how to implement it!
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
document.addEventListener('DOMContentLoaded', () => {
const form = document.querySelector("form#frmSearch");
form.onsubmit = function() {
let keyword = encodeURIComponent(this.querySelector("input#keyword").value);
$.ajax({
url: `./php_curl_file.php?q=${encodeURIComponent(keyword)}`,
type: 'GET',
error: (err) => {
throw new Error(err);
},
success: (searchData) => {
console.log( searchData );
}
});
return false;
}
} );
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="frmSearch" class="searchform order-sm-start order-lg-last">
<div class="form-group d-flex">
<input type="text" id="keyword" class="form-control pl-3" placeholder="Buscar">
<button type="submit" placeholder="txtsearch" class="form-control search">
<span class="fa fa-search"></span> Search
</button>
</div>
</form>

Post json data using fetch api failed

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?

Categories