Variable is undefined javascript - javascript

Hello I made a "login screen" that when you enter a name you will be transfer to another html file. I made a welcome back screen that says Welcome back, "username". But for some reason the variable that I use to take the value of the username field is undefined.
This is the login screen html code:
<form id="login-form" metod="post" action="main.html">
<div class="txt_field">
<input id="username" type="text" required>
<label>username</label>
</div>
<input onclick="validate()" type="submit" id="submit" value="Login">
</form>
</div>
<script type="text/javascript" src="functions.js"></script>
-> this is the js file:
let username1;
function validate(){
username1=document.getElementById(username).value;
}
document.getElementById('show_username').innerHTML = username1;
-this is the after login html file
<center>
<h1>Welcome back,<br>
<span id="show_username"></span>
</h1>
</center>
<script type="text/javascript" src="functions.js"></script>
**ofc I didn't include all the code for basic reasons.

Here is what happens in JavaScript when you load your page:
// username1 is set to null
let username1;
// validate() function is created
function validate(){
username1=document.getElementById(username).value;
}
// show_username element is populated with username1 (still null)
document.getElementById('show_username').innerHTML = username1;
When you call the validate function, username1 is updated but document.getElementById('show_username') is not.
You also are referencing a username variable instead of 'username' as a string.
Your code will work if you move line 5 into the validate function, and fix that issue.
let username1;
function validate(){
username1=document.getElementById('username').value;
document.getElementById('show_username').innerHTML = username1;
}

Related

Google reCaptcha attribute 'data-callback' causing page refresh on alert

I have added Google reCaptcha v3 script to my form. The form also includes validation that alerts the user to complete the input field. Now when the user clicks on submit button directly, an alert is shown and when OK is clicked the page refreshes and form data is submitted in the backend. I have tried adding return false and e.preventdefault() in the function but the page still resets after the alert. If I try to add any additional condition to the data-callback function, the submit button stops working.
HTML
<html>
<head>
<script src="https://www.google.com/recaptcha/api.js"></script>
<script>
function onSubmit(token) {
document.getElementById("demo-form").submit();
}
</script>
<script>
function validateForm() {
var fname = document.forms.WebForm.fname.value;
if (fname == "") {
alert("Please fill out all the fields");
return false;
}
}
</script>
</head>
<body>
</style>
<div class="container">
<form action="https://www.samepage.com" method="post" id="demo-form" name="WebForm">
<div>
<div>
<input name="fname" id="fname" type="text" placeholder="First name*" required/>
</div>
</div>
<div>
<div>
<input type = "submit" style = "font-weight: bold;" value="Submit" class="g-recaptcha button" data-sitekey="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
data-callback='onSubmit'
data-action='submit'
onClick="return validateForm()"/>
</div>
</div>
</form>
</div>
</body>
</html>
Even the required attribute in the input tag doesn't work with the recaptcha script added. When I remove the data-callback attribute and the supporting script functions, the alert and form works as expected.

Sender email address not included in EmailJS

When I submit the form, I receive the user's message. However, I don't know who it's from. I don't receive their email address, nor their name. I tried looking at their documentation but wasn't able to get past this. Any help will be appreciated. Thank you!
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/emailjs-com#2/dist/email.min.js"></script>
<script type="text/javascript">
(function () {
// https://dashboard.emailjs.com/admin/integration
emailjs.init("MY_USER_ID");
})();
</script>
<script type="text/javascript">
window.onload = function () {document.getElementById("contact-form").addEventListener("submit", function (event) {
event.preventDefault();
// generate a five digit number for the contact_number variable
this.contact_number.value = Math.random() * 100000 | 0;
// these IDs from the previous steps
emailjs.sendForm("MY_SERVICE_ID", "MY_TEMPLATE_ID", this).then(
function () {
console.log("SUCCESS!");
},
function (error) {
console.log("FAILED...", error);
}
);
});};
</script>
</head>
<body>
<form id="contact-form">
<input type="hidden" name="contact_number" />
<label>Name</label>
<input type="text" name="user_name" />
<label>Email</label>
<input type="email" name="user_email" />
<label>Message</label>
<textarea name="message"></textarea>
<input type="submit" value="Send" />
</form>
</body>
{{message}} is the only thing you can receive from the form for now because your template has two dynamic variables {{from_name}}, {{message}} but you are sending contact_number, user_name, user_email and message which is written in name attributes for each inputs in the form.
You have to match names of template variables and names of form inputs. If you want to maintain your form, you have to modify your template like
from You got a new email from {{from_name}}: {{message}}
to You got a new email from {{user_name}}({{user_email}}): {{message}}
You can also use built-in variables without getting input but I'll leave them because you need to read the documentation for good.

How to verify the elements of a form in Javascript then Move to a PHP page?

I want to verify the inputs by javascrpit function perform() and move to a php page named i.php to save the datas in the databasse.
Here is the code:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form action="i.php" method="post">
<br>
Name <input type="text" name="name" id="name" >
<span id="err"></span>
</br>
<br>
Password <input type="Password" name="Password" id="password">
<span id="perr"></span>
</br>
<br>
Gender
<input type="radio" name="gender" id="gender" value="male">Male
<input type="radio" name="gender" id="gender" value="female">Female
</br>
<br>
Department <select name="department" id="department">
<option>------</option>
<option>ECE</option>
<option>BBA</option>
<option>ENG</option>
</select>
</br>
<br>
<button name="btn" type="button" id="btn" onclick="perform()" >Button</button>
<input type="submit" name="submit" value="Submit">
<input type="reset" name="reset" value="Clear">
</br>
</form>
<script type="text/javascript">
function perform()
{
var name = document.getElementById('name').value;
var pass = document.getElementById('password').value;
var dept = document.getElementById('department').value;
var gender = document.getElementsByName('gender');
var r =3;
if (name.length==0)
{
document.getElementById('err').innerHTML = "name not found";
r++;
}
if (pass.length<=6 || pass.length>=32 )
{
document.getElementById('perr').innerHTML = "password error";
r++;
}
if(r==3)
{
window.location= "i.php";
}
}
</script>
</body>
</html>*
In i.php page i used var_dump to see the datas whether it has been submitted or not. code of the i.php page:
<!Doctype html>
<html>
<head></head>
<body>
<?php
var_dump($_POST);
?>
</body>
</html>
But its showing arry(0) {}
looks like there nothing that has been submitted.
The issue is that you're redirecting with javascript, and losing the entire form and it's data by doing so.
When the form is valid, submit it rather than redirecting
function perform() {
var _name = document.getElementById('name').value;
var pass = document.getElementById('password').value;
var dept = document.getElementById('department').value;
var gender = document.getElementsByName('gender');
var valid = true;
if (_name.length === 0) {
document.getElementById('err').innerHTML = "name not found";
valid = false;
}
if (pass.length <= 6 || pass.length >= 32) {
document.getElementById('perr').innerHTML = "password error";
valid = false;
}
if (valid) {
document.querySelector('form').submit();
}
}
Note that name is not a good name for variables or form elements, as it already exists in window.name, and that a submit button can not be named submit as it overwrites the named form.submit() function
Another option would be to just remove all the javascript, and use HTML5 validation instead.
Use this code:
<form action="i.php" method="post" onsubmit="perform();">
And in javascript make these changes:
if(r!=3) {
alert('please complete the form';
return false;
}
Javascript doesn't send POST headers with window.location!
By using this code, you don't need to use a button, javascript perform() function runs when the submit button is clicked in the form.
If form values are entered truly, javascript perform() does not return and form submits; else, the function returns and prevents submitting the form.
The problem is you are not submitting the form you are just going to a different page with javascript without passing along any variables. so instead of doing
window.location= "i.php";
you should submit the form like so
document.getElementById("formId").submit();
so you should give the form the id formId
The problem is that you are merely redirecting to the i.php page without posting any data. Replace this line in your JS:
window.location = "i.php";
with this
document.getElementsByTagName('form')[0].submit();
This will find the form in your DOM and submit it along with the data that has been input, preserving the values for your action page.
You also need to rename your submit-button for this to work. Otherwise you will not be able to call the submit function on the form programmatically.
<input type="submit" name="submit-btn" value="Submit" />
should do the trick. However, I don't really see the point of the submit button in addition to your validation/submission button.
Full code sample of the solution here: https://jsfiddle.net/dwu96jqw/1/
by press btn you redirect only and your form dont submitted for transfer via _POST
you should change your code :
<form action="i.php" method="post" id ="form1">
and :
if(r==3)
{
form1.submit();
}
window.location will redirect you to the page, to preserve field values return it
if(r==3)
{
return true;
}

.HTML File has Password in URL [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I usually code in Java, but I knew a little HTML, so I decided I would learn more. My problem is that I have a password field and a submit button. When I hit the button, it checks to see if the password is right, and then asks you what your name is. It then changes a text field to say You got it right, NAME. The thing is, when you hit submit, the code submitted is added to the URL, so if you type password as the password, ?password is added on to the URL. That is fine with me, but since the URL is changed, the page reloads, making the text field go back to normal. I am using Google Chrome. Is there anyway around this, or is it because I am running a .HTML file, not going to a website?
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<title>Ryan Club Homepage</title>
<script>
function codeEnter(){
var s = document.getElementById("in").value;
var correct = "lolliPiper5";
if(s === correct){
var name = prompt("What is your name");
document.getElementById("cde").innerHTML = "You got the password right!, " + name;
}
}
</script>
</head>
<body style="font-family:'Myriad Pro' ">
<form onsubmit="codeEnter();">
<input type="password" name="code" id="in">
<br />
<input type="submit" value="Ready!">
</form>
</body>
</html>
Thank you!
You need to use JavaScript / jQuery to prevent the form from submitting. I am using jQuery 2.1.1.
For password field let's assume it 123 for now.
The e.preventDefault() method stops the default action of an element from happening. Here it stops the submit button to submit the form to URL specified in form's action attribute.
$(document).ready(function(){
$("#name_container").hide();
$('#submit').on("click",function(e){
e.preventDefault();
$password = $('#password').val();
if($password == '123'){
$("#password_container").hide();
$("#name_container").show();
$("#result").html("");
}
else{
$("#result").html("Password is incorrect.");
}
$name = $("#name").val();
if($name != '' && $name != null ){
$("#form").hide();
$("#result").html("You got it right, "+$name);
}
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="page.html" method="post" id="form">
<div id="password_container">
Password: <input type="password" id="password" />
</div>
<div id="name_container">
Name: <input type="text" id="name" />
</div>
<input type="submit" id="submit">
</form>
<div id="result">
</div>
(Updated)
Here you go:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body style="font-family:'Myriad Pro' ">
<form id="form" method="post" action="#">
Password:
<input type="password" name="code" id="in">
<br />
<input type="submit" value="Ready!" id="submit">
</form>
<div class="ps"></div>
<script>
$(document).ready(function () {
$('#submit').on("click", function (e) {
e.preventDefault();
$password = $('#in').val();
if ($password == 'lolliPiper5') {
$name = prompt("Enter your name", "ACCESS GRANTED");
$(".ps").html("Welcome to the team, " + $name);
}
});
});
</script>
</body>
</html>
In your simplified (I hope) code you need at least set
<form onsubmit="return codeEnter()">
...
// and in the script
function codeEnter(){
var s = document.getElementById("in").value;
var correct = "lolliPiper5";
if(s === correct){
var name = prompt("What is your name");
document.getElementById("cde").innerHTML = "You got the password right!, " + name;
}
else return false; //do not submit
}
In the real world if you actually wanted to submit the password, hidden from the user you would change the form code to
<form onsubmit="codeEnter();" method="post">
By default the form submits data to the server via a GET request which causes the values to show in the url, thus this is usually only used for making queries such as page numbers (?page=num) etc (all insensitive data).
However, when you set method="post" the form sends data using a POST request which is invisible to the user and in some cases encrypted before sending and therefore much safer.
An example of a for using method="POST" can be found here

jQuery.get to read a file and use the data into a form

I want the script to do the following:
On page load, read a text file with a number (just one line)
Increment the number by 1
Insert the number in an <input> box of the form
Once <form> is submitted, write the number to the text file
When the form gets loaded again, it will rerun the code and the number will increment by 1. This is basically to pre-populate a field with a unique and progressive number prior to form submission.
I am currently using jQuery, PHP and of course HTML:
HTML:
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js">
$.get("http://www.domain.com/tools/formdata.txt");
function test(){
$.get('http://www.domain.com/tools/formdata.txt', function(data){
x = data++;
});
}
</script>
</head>
<body onload="test()"/>
<form action="save_json.php" method="post">
Contract: <input type="number" name="contract" id="contract" value="x" /><br />
<input type="submit" id="submit" value="Invia" />
</form>
</body>
</html>
PHP
<?php
if(isset($_POST['contract'])) {
// if form fields are empty, outputs message, else, gets their data
if(empty($_POST['contract'])) {
echo 'All fields are required';
}
else {
// adds form data into an array
$formdata = $_POST['contract'];
if(file_put_contents('/var/www/domain/tools/formdata.txt', $formdata)) echo 'Data successfully saved';
else echo 'Unable to save data, try again or contact IT';
}
}
else echo 'Form fields not submitted';
?>
First: I recommend that instead of javascript, you do this with PHP file_get_contents('formdata.txt') at the start of your file, and then you echo it in. That way, the value will be there on load, rather than having to wait for the HTML to render and the javascript to run. Also, it is a much better practice and will let you do a lot more things if you choose to expand the page.
However, here's the solution to the issue presented:
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
<script>
var x;
function test(){
$.get('file.txt', function(data){
console.log('data',data);
var x = ++data;
console.log('x',x);
$('#contract').val(x);
});
}
</script>
</head>
<body onload="test()"/>
<form action="aoeu.php" method="post">
Contract: <input type="number" name="contract" id="contract" /><br />
<input type="submit" id="submit" value="Invia" />
</form>
</body>
</html>
The things to note:
Close off your <script> tag including the jquery library, then open another one after it.
No need to do the first $.get() you have - save it for the function.
var x = data++; - this increments data AFTER its value has been assigned to x. So, it will never increase. Do ++data instead, and it increments before.
You need to place it somewhere afterwards. How you had the input (value='x') is just trying to put the character "x" into the input. Use javascript to edit the functions value, as in my example.
Your PHP works fine.

Categories

Resources