Retrieve JSON values from ejs - javascript

I am new to node and ejs, I have below code, and need to know how to get the values from EJs file to post it to mongoDB
EJS file
<form>
<p>
<label for="username"> Username </label>
<input type="text" for="username"/>
</p>
<p>
<label for="password"> Password </label>
<input type="password" for="password" />
</p>
<p>
<label for="email"> Email </label>
<input type="text" for="email"/>
</p>
<button type="submit">Log In</button>
</form>
JS file
$('form').on('submit', function(){
var item = $('form input');
var user = [{username:item.val()},{password:item.val()},{email:item.val()}];
console.log(user);
$.ajax({
type: 'POST',
url: '/register',
data: user,
success: function(data){
//do something with the data via front-end framework
console.log(data);
location.reload();
}
});
return false;
});
As of now when I insert to mongo DB I get a new uuid but the values are going in as "0"
please aasist

So the line var item = $('form input'); is actually a collection of each input, while the line var user = [{username:item.val()},{password:item.val()},{email:item.val()}]; is only grabbing the value of the first one (this is because of how jQuery can appear to hide a collection), instead I would try this (assuming you wanted to grab specific values out of that form):
var items = $('form');
var user = {
username: $('[name=username]', items).val(),
password: $('[name=password]', items).val(),
email: $('[name=email]', items).val()
};
With following change to your html
<form>
<p>
<label for="input-username"> Username </label>
<input type="text" id="input-username" name="username"/>
</p>
<p>
<label for="input-password"> Password </label>
<input type="password" id="input-password" name="password" />
</p>
<p>
<label for="input-email"> Email </label>
<input type="text" id="input-email" name="email"/>
</p>
<button type="submit">Log In</button>
</form>
Also the for attribute in the <label> element is to associate with an <input> that has an id attribute with the same value. So considering that ids should be unique and only resolve to a single element I would suggest adding some kind of name spacing like input- to them.

Related

How can I get a value from a form in page 1 to another page by using JavaScript?

I have only learned HTML, CSS, JavaScript and jQuery and I want to get a value from my form to my index page, which is located in different files, using the languages I know. So this is my form :
<form action="../index/index.html" method="GET">
<label for="name">Name :</label>
<input type="text" name="name" id="name" required>
<label for="email">Email :</label>
<input type="text" name="email" id="email" placeholder="eg.yourname#gmail.com" required>
<input type="submit" name="submit" id="submit">
</form>
I want the value that a user submits in the #name input in my index's div tag when the submit button is pressed (this div has the class sing-in).
Both pages have their own JavaScript and CSS so if I would import the JavaScript of the page where the form is to my index pages it will mess up both pages I guess. Therefore, I want to do this without importing the JavaScript and just by taking the value from another page into my index page. Thank you.
When you submit your form and get redrected to your index page the values of the form will be put at the end of the url as GET parameters.
Example url: localhost:80/index/index.html?name=Eddie&email=eddie#gmail.com
To read the GET parameters you can use this code:
var urlString = window.location.href
var url = new URL(urlString);
var name = url.searchParams.get("name");
var email = url.searchParams.get("email");
//Check if name and email are set
Make sure to check if name and email have actually been set in index.html
You can get the values from for like this:
if this is the form
<form action="../index/index.html" method="GET">
<label for="name">Name :</label>
<input type="text" name="name" id="name" required>
<label for="email">Email :</label>
<input type="text" name="email" id="email" placeholder="eg.yourname#gmail.com" required>
<input type="submit" name="submit" id="submit">
</form>
var name = document.getElementById('name').value;
var email = document.getElementById('email').value;
or in jquery
var name = $('#name').val();
var email = $('#email').val();
have a look:
https://www.w3schools.com/jsref/prop_text_value.asp
this might help you

jquery and javascript obtained input value of input type equals text but it is empty even though it's not

When i try to obtain the values of input type=text is empty even though they are not. Any idea why?
var form_data = new FormData(document.getElementById('box')); // Creating object of FormData class
var cust_name = document.getElementById("cust_name").value;
var order_num = $("#order_num").val();
$("#search").click(function(){
console.log(cust_name) //they are empty even though it's not
console.log(order_num) //they are empty even though it's not
$.ajax({
url: "search.php",
method: "POST",
data: {cust_name: cust_name, order_num: order_num},
error: function (request, status, error) {
$("body").append("<div style='background:rgba(255,0,0,0.8);float:left;position:fixed'>" + request.responseText + "</div>")
}
}).done(function(msg) {
$("body").append("<div style='background:rgba(255,0,0,0.8);float:left;position:fixed'>" + msg + "</div>")
});
});
});
and here is my html code:
<form id="box" method="post">
<input type="text" id="order_num" name="order_num" placeholder="🔠Order number"/> <br/>
<input type="text" id="cust_name" name="cust_name" placeholder="🔠Customer name"/> <br/>
sent date: <input type="date" name="sent_date" id="sent_date"/><br/>
<input type="text" id="sales_person" name="sales_person" placeholder="🔠sales person"/><br/>
<input type="button" id="search" class="button" value="search" name="search"/>
</form>
You need to attach an event listener to the submit event of your form to get the values when the user submits. Here's a stripped down working example.
The problem with your code is that it runs right away when the page loads, and because JavaScript is a runtime language, it doesn't go back and update those variables with the current value.
You could also put those two variable declarations INSIDE your click handler (Shown in bottom solution).
Solution (Preferred)
document.getElementById('box').addEventListener('submit', function(e) {
e.preventDefault();
var form_data = new FormData(this);
var cust_name = document.getElementById("cust_name").value;
var order_num = document.getElementById("order_num").value;
console.log(cust_name, order_num);
});
<form id="box" method="post">
<input type="text" id="order_num" name="order_num" placeholder="🔠Order number"/> <br/>
<input type="text" id="cust_name" name="cust_name" placeholder="🔠Customer name"/> <br/>
<button type="submit">Search</button>
</form>
Notes
I used <button> instead of <input type="button">
I passed this to FormData because we have a reference to it from the event handler
I used e.preventDefault() to stop the page from refreshing by default.
Solution (Minimal Code Change)
$("#search").click(function(){
var form_data = new FormData(document.getElementById('box'));
var cust_name = document.getElementById("cust_name").value;
var order_num = $("#order_num").val();
console.log(cust_name);
console.log(order_num);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="box" method="post">
<input type="text" id="order_num" name="order_num" placeholder="🔠Order number"/> <br/>
<input type="text" id="cust_name" name="cust_name" placeholder="🔠Customer name"/> <br/>
sent date: <input type="date" name="sent_date" id="sent_date"/><br/>
<input type="text" id="sales_person" name="sales_person" placeholder="🔠sales person"/><br/>
<input type="button" id="search" class="button" value="search" name="search"/>
</form>

Save Data to Localstorage and use it to populate fields after submit

I have optin popup of two steps, first step is to capture email and name, when user click submit the data is captured, and another popup appears, the new popup has a form with more fields to get more info, plus email and name field.
what I want to do is to automatically populate the email and name field from first popup and hide them with display:none so user can't see them, after submit the data is captured again (all goes to activecampaign).
the two forms works just fine, what is not working is saving the data and calling it when needed
here is the js I'm using
jQuery(function($){
// PART I: Saving user details locally
$('#arlington-field-submit').on('click', function(){
// check if the user's browser has localStorage support
if (typeof(Storage) !== "undefined") {
// Code for localStorage/sessionStorage.
// store the full name in localStorage
var fullname = document.querySelector("input[name=arlington-name]");
localStorage.user_name = fullname.value;
// save the email in localStorage
var email = document.querySelector("input[name=arlington-email]");
$("input[name=fullname]").val(localStorage.getItem("server"));
localStorage.user_email = email.value;
}
});
// PART II: Pre-filling forms forms with locally saved values
if (typeof(Storage) !== "undefined") {
// check if the user has a name field stored
if (localStorage.user_name) {
name_field = document.querySelector("._form input[name=fullname]");
name_field.value = localStorage.user_name;
}
// check if the user has an email field stored
if (localStorage.user_email) {
email_field = document.querySelector("._form input[name=email]");
email_field.value = localStorage.user_email;
}
}
});
first form html:
<div id="arlington-element-form" class="arlington-element-form arlington-element" data-element="form">
<div id="arlington-form" class="arlington-form arlington-has-name-email arlington-has-buttons">
<div class="arlington-form-wrap"><input id="arlington-field-comments" name="arlington-comments" type="text" data-selectable="true" data-target="#builder-setting-comments_value" class="arlington-field-comments" placeholder="" value="" style="" autocomplete="off"><input id="arlington-field-name" name="arlington-name" type="text" data-selectable="true" data-target="#builder-setting-name_value" class="arlington-field-name" placeholder="Enter your name here..." value="">
<input id="arlington-field-email" name="arlington-email" type="email" data-selectable="true" data-target="#builder-setting-email_value" class="arlington-field-email" placeholder="Enter your email address here..." value="" >
<input id="arlington-field-submit" name="arlington-submit" type="submit" data-selectable="true" data-target="#builder-setting-submit_value" class="arlington-field-submit" value="JOIN NOW" >
</div>
<div class="arlington-yesno-wrap">
<button id="arlington-button-yes" type="button" name="arlington-yes" data-selectable="true" data-target="#builder-setting-yes_value" data-action="form" data-type="yes" class="arlington-button-yes arlington-button-yesno">Submit!</button>
</div></div></div>
second form html:
<form method="POST" action="xxxxxx" id="_form_8_" class="_form _form_8 _inline-form _dark" novalidate> <input type="hidden" name="u" value="8" /> <input type="hidden" name="f" value="8" /> <input type="hidden" name="s" /> <input type="hidden" name="c" value="0" /> <input type="hidden" name="m" value="0" /> <input type="hidden" name="act" value="sub" /> <input type="hidden" name="v" value="2" />
<div class="_form-content">
<div class="_form_element _x72304349 _full_width "> <label class="_form-label"> Full Name </label>
<div class="_field-wrapper"> <input type="text" name="fullname" placeholder="Type your name" /> </div>
</div>
<div class="_form_element _x10201592 _full_width "> <label class="_form-label"> Email* </label>
<div class="_field-wrapper"> <input type="text" name="email" placeholder="Type your email" required/> </div>
</div>
<div class="_form_element _x29901314 _full_width "> <label class="_form-label"> Phone </label>
<div class="_field-wrapper"> <input type="text" name="phone" placeholder="Type your phone number" /> </div>
</div>
<div class="_button-wrapper _full_width"> <button id="_form_8_submit" class="_submit" type="submit"> Submit </button> </div>
<div class="_clear-element"> </div>
</div>
</form>
Since the input which is being clicked is a submit button, chances are that the page is navigating before the JS within the click handler gets a chance to fire.
Try and replace
$('#arlington-field-submit').on('click', function(){
with:
$('#_form_8_').on('submit', function(event){
Then you can prevent the form from actually submitting so your JS can run:
$('#_form_8_').on('submit', function(event){
event.preventDefault();
// Do localStorage stuff
$(this).submit(); // submit the form normally after localStorage is saved
});
The way you look for elements is wrong, because you forgot quotes wrapping attribute values:
var fullname = document.querySelector("input[name=arlington-name]");
should be:
var fullname = document.querySelector('input[name="arlington-name"]');
And so on...
BTW I'm surprised you don't report an error like "An invalid or illegal string was specified".

django app JavaScript getElementById not working

I am trying to POST some data to Django App but every variable is working fine except one..
This is my form:
<div class="subfield">
<span>
Found a coupon for <b><span style="color:#d95b44;" id="Store_Name">{{ storeData.0.storeName }}</span>?</b>
Enter the details below to share with other users
</span>
<form>
<br>
<label for="user">Coupon code :</label>
<input type="text" id="coupon_Code" maxlength="100" />
<br>
<label for="user">Discount :</label>
<textarea rows="2" cols="19" minlength="15" id="coupon_Discount"></textarea>
<br>
<div id="buttn">
<button type="button" style="margin:0;padding:0;" onclick="javascript:submitCoupon();">Submit Coupon</button>
</div>
</form>
</div>
My JavaScript is:
<script type="text/javascript">
function submitCoupon()
{
var store_Name = document.getElementById('Store_Name').value;
var couponCode = document.getElementById('coupon_Code').value;
var couponDiscount = document.getElementById('coupon_Discount').value;
var data = {"storeName":store_Name,"couponCode":couponCode,"couponDiscount":couponDiscount,
csrfmiddlewaretoken:'{{ csrf_token }}'};
alert(store_Name);
$.ajax({ // create an AJAX call...
data: data, // get the form data
type: "POST", // GET or POST
url: "/submit_coupon/", // the file to call
dataType: "json",
success: function(response) { // on success..
alert("done");
}
});
}
</script>
Out of three variable couponCode and couponDiscount is working but not store_Name...
I have tried changing variable name,id but nothing is working
Whenever i am trying to alert store_Name i am getting undefined ....
And also console is displaying no error...
<div class="subfield">
<form>
<span>
Found a coupon for <b><span style="color:#d95b44;" id="Store_Name">{{ storeData.0.storeName }}</span>?</b>
Enter the details below to share with other users
</span>
<br>
<label for="user">Coupon code :</label>
<input type="text" id="coupon_Code" maxlength="100" />
<br>
<label for="user">Discount :</label>
<textarea rows="2" cols="19" minlength="15" id="coupon_Discount"></textarea>
<br>
<div id="buttn">
<button type="button" style="margin:0;padding:0;" onclick="javascript:submitCoupon();">Submit Coupon</button>
</div>
</form>
</div>
Store_Name's span used in the form then its run properly

targeting a specific form with serialize()

Following on from my previous question, which was so quickly answered by Meder it wasn't funny, there's now an additional question that's popped up in the process of making a reusable jQuery form submitted that doesn't take the user away from where they were.
Problem
The jQuery serialize() function is performing its magic on all forms within a page, and not the specific form which was submitted. Example code below.
How do I capture the form's unique name/id, and replace "form" within $("form").serialize() with the name of the target form so only that is serialised?
Form code
<form name="contact" id="contact" action="">
<input name="_recipients" type="hidden" value="joe#fake.com" />
<input name="_subject" type="hidden" value="Title" />
...
<fieldset>
<label for="name" id="name_label">Name</label>
<input type="text" name="name" id="name" size="30" value="" class="text-input" />
<label class="error" for="name" id="name_error">This field is required.</label><br />
<label for="email" id="email_label">Return Email</label>
<input type="text" name="email" id="email" size="30" value="" class="text-input" />
<label class="error" for="email" id="email_error">This field is required.</label><br />
<label for="phone" id="phone_label">Return Phone</label>
<input type="text" name="phone" id="phone" size="30" value="" class="text-input" />
<label class="error" for="phone" id="phone_error">This field is required.</label><br/>
<br />
<input type="submit" name="submit" class="button" id="submit_btn" value="Send your suggestion" />
</fieldset>
</form>
jQuery serialise and post
var dataString = $("form").serialize();
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "/_global/assets/scripts/formmail/formmail.asp",
data: dataString,
...
var dataString = $('#contact').serialize()
If you are attaching an event handler to a button or the form's submit event then you can refer to it with this if inside the submit event handler function scope, eg
$('#contact').submit(function() {
alert( $(this).serialize() );
});
I highly recommend reading http://docs.jquery.com/Selectors
By using the "form" string as a selector, you are actually getting all the FORM elements within the page, in order to select only one form, you can:
Get the specific form by its id attribute (using the id selector):
var dataString = $("#contact").serialize();
Or by its name attribute (using the attributeEquals selector):
var dataString = $("form[name=contact]").serialize();
$("#contact").serialize()
Instead of using serialize there's a nice plugin that allows you to post your forms asynchronously. All you have to do is:
$(function() {)
$('#contact').ajaxForm();
});
Also don't forget to assign the correct action to the form, it shouldn't be empty.

Categories