Send JavaScript Data to PHP Page - javascript

So I am new to JS and I am trying to take in a small amount of user input on a JS form. This input will then go to a PHP page as parameters for a result return on the PHP page.
I have been looking at tutorials and examples and I believe my form is named and labeled correctly, but I cannot seem to pull the form data, let alone send it to another page. I have been searching for an hour now with still no luck. :(
For reference, my JS form is page1.html and my PHP form that needs the data is page2.php. (in the same filepath)
Below is my Form code, the script at the top is just my attempt at the getting the data.
If someone could show me how to send form data to a "page2.php" I would be be very thankful!
All I need is the two text box inputs as well as the gender type.
<HTML>
<HEAD>
<TITLE>Test Input</TITLE>
<SCRIPT LANGUAGE="JavaScript">
function testResults () {
var minWeight = form.minWeight.value;
var maxWeight = form.maxWeight.value;
var genderType = form.genderType.value;
alert ("Weight Range: " + minWeight + " - " + maxWeight + "\n for all " +
genderType + "s" );
}
</SCRIPT>
</HEAD>
<BODY>
<FORM NAME="myform" ACTION="" METHOD="GET">
Enter minimum weight:
<input type="text" name="minWeight" value="0">
<BR>
Enter maximum weight:
<input type="text" name="maxWeight" value="999">
<BR>
Select gender
<input type="radio" name="genderType" value="male"/>
Male
<input type="radio" name="genderType" value="female"/>
Female
<BR>
<INPUT TYPE="button" NAME="button" Value="Submit" onClick="testResults(myform)">
</FORM>
</BODY>
</HTML>
*If the code to send form data is a little tricky, please explain it so that I can understand what is occurring.
Thank you very much!

The reason your JavaScript doesn't work is because you named your form myform but you're trying to access form.
That said, you shouldn't be using JavaScript for this. Just a simple form will do:
<form action="page2.php" method="post">
<p><label>Enter minimum weight: <input type="number" name="minWeight" value="0" min="0" required /></label></p>
<p><label>Enter maximum weight: <input type="number" name="maxWeight" value="999" min="0" required /></label></p>
<p>Select gender:
<label><input type="radio" name="genderType" value="male" required /> Male</label>
<label><input type="radio" name="genderType" value="female" /> Female</label>
</p>
<p><input type="submit" value="Submit" /></p>
</form>
Your PHP script can then reference $_POST['minWeight'], $_POST['maxWeight'] and $_POST['genderType'].

Related

Using Javascript To Show Values From HTML

I'm trying to create a HTML Page with multiple forms, and I would like
to show the values from the form on the same page (wiping the original HTML), but after using the button, nothing shows up (the page like reloaded)
Here's the code for HTML :
function Results() {
var fname = document.getElementById('fname').value;
var lname = document.getElementById('lname').value;
var gender = document.getElementById('gender').value;
var date = document.getElementById('birthday').value;
if (document.getElementById('genderM').checked) {
gender = document.getElementById('genderM').value;
} else if (document.getElementById('genderF').checked) {
gender = document.getElementById('genderF').value;
}
document.writeIn("<h3>Thank You! Here's Your Precious Data! </h3>"); document.writeIn("<p> Your Name Is : </p>" + fname + lname); document.writeIn("<p> Gender : " + gender); document.writeIn("<p> Birthday : " + birthday);
document.getElementById('forms').innerHTML = forms;
}
<!DOCTYPE HTML>
<html>
<head>
<title> The Page Number 2 </title>
<link rel="stylesheet" type="text/css" href="page2.css">
</head>
<body>
<h1> Please fill in the form for exciting contents! </h1>
<hr size="5px" color="black">
<div id="forms" class="forms">
<form onsubmit="Results()" method="post">
<div class="textFirst">
First Name
</div>
<input id="fname" type="text" name="fname"> <br>
<br>
<div class="textLast">
Last Name <br>
</div>
<input id="lname" type="text" name="lname"> <br>
<br>
<div class="textGender">
Gender <br>
<input id="genderM" type="radio" name="gender" value="male"> Male <br>
<input id="genderF" type="radio" name="gender" value="female"> Female <br>
</div>
<br>
<div class="textBirth">
Birthday <br>
</div>
<input id="birthday" type="date" name="birthday"> <br>
<input id="submit" class="buttonagain" type="submit" value="Submit!" />
</form>
</div>
</body>
</html>
Any ideas what should I do?
Edit : I'm not able to use php or server for this
Your code is riddled with syntax errors: missing parentheses, missing + operators, etc.
document.writeIn (with an uppercase I) is not a function; document.writeln (with a lowercase L) is.
<script> tags aren't self-closing, i.e. you have to write <script src="scriptPage2.js"></script>
document.getElementById('gender') returns null, because there is no element with id="gender".
You're trying to write birthday but you never declared that variable.
I have no idea what you're trying to accomplish with document.getElementById('forms').innerHTML = forms;
In general, you should make use of the browser's built-in debugger to catch all these errors. If you're using Chrome or Firefox, press Ctrl+Shift+I (in IE or Edge, press F12) and open the "Console" tab; you will see all the errors there as the JS parser encounters them.
Once that's all fixed, remove the submit event handler from <form>, and change your submit button like this:
<input id="submit" class="buttonagain" type="button" onclick="Results()" value="Submit!" />
Note the change of type from submit to button. This will prevent the page from reloading, which is the expected behavior when submitting a form.
You don't need the return and ; when calling a js function in html
<form onsubmit="Results()" method="post">
This is your answer.
function Results() {
var fname = document.getElementById('fname').value;
var lname = document.getElementById('lname').value;
var gender;
var date = document.getElementById('birthday').value;
if (document.getElementById('genderM').checked) {
gender = "Male";
} else {
gender = "Female"
}
document.writeln("<h3>Thank You! Here's Your Precious Data! </h3>");
document.writeln("<p> Your Name Is : </p>" + fname + " " + lname);
document.writeln("<p> Gender : " + gender);
document.writeln("<p> Birthday : " + date);
document.getElementById('forms').style.display = "none";
}
<!DOCTYPE HTML>
<html>
<head>
<title> The Page Number 2 </title>
<link rel="stylesheet" type="text/css" href="page2.css">
</head>
<body>
<h1> Please fill in the form for exciting contents! </h1>
<hr size="5px" color="black">
<div id="forms" class="forms">
<form onsubmit="Results();" method="post">
<div class="textFirst">
First Name
</div>
<input id="fname" type="text" name="fname" required> <br>
<br>
<div class="textLast">
Last Name <br>
</div>
<input id="lname" type="text" name="lname"required> <br>
<br>
<div class="textGender">
Gender <br>
<input id="genderM" type="radio" name="gender" value="male" required> Male <br>
<input id="genderF" type="radio" name="gender" value="female"> Female <br>
</div>
<br>
<div class="textBirth">
Birthday <br>
</div>
<input id="birthday" type="date" name="birthday"required> <br>
</div>
<input id="submit" class="buttonagain" type="submit" value="Submit!" />
</div>
</form>
</body>
</html>

Can I add a required passcode to my HTML form?

I want to put an HTML form on my website for people to send in their RSVP to a party invite. I want to require them to put in a passcode (that will be printed on their invite) before they can submit the form. Is there a way to set a field requirement to an exact match of a pre-specified pin # or password using purely HTML (and JavaScript if necessary)?
For sake of an example, let's simply say I want the person's name and a yes or no for their RSVP.
<form>
Name:
<input type="text" name="name">
RSVP:
<input type="radio" name="rsvp" value="yes">Yes<br>
<input type="radio" name="rsvp" value="no" checked>No<br>
Secret Word:
<input type="password" name="secretWord">
</form>
Yes, you would have to use Javascript, so you would want
function check(){
var pass = document.getElementById("pass_box").value;
if(pass == "Y o u r p a s s w o r d"){
// Do stuff
}else{
// Dont do stuff
}
}
and your html code would look like this:
<form>
Name:
<input type="text" name="name">
RSVP:
<input type="radio" name="rsvp" value="yes">Yes<br>
<input type="radio" name="rsvp" value="no" checked>No<br>
Secret Word:
<input type="password" id="pass_box" name="secretWord">
<button onclick="check()">Submit</button>
</form>
But this isnt very secure, because someone could just look at your code and see the password, but if its just for a party, it should be fine!
Anyway, there is your code! Hope this helps!

display html form values in same page after button

i make a html site. there is questions on the site. i made it with form .After clicking on the button, I want to see all of the answers on the same page.i dont want as alert. how can i do it?
I apologize for the misspellings.
<script>
function findSelection()
{
var serieList=document.getElementsByName('serie')
for (var i=0; i<serieList.length;i++)
{
if(serieList[i].checked)
{
}
}
var markaList=document.getElementsByName('marka')
for (var i=0; i<markaList.length;i++)
{
if(markaList[i].checked)
{
alert(markaList[i].value)
}
}
var yerList=document.getElementsByName('yer')
for (var i=0; i<yerList.length;i++)
{
if(yerList[i].checked)
{
alert(yerList[i].value)
}
}
var nasilList=document.getElementsByName('nasil')
for (var i=0; i<nasilList.length;i++)
{
if(nasilList[i].checked)
{
alert(nasilList[i].value)
}
}
}
</script>
<html>
<head>
<title>Web Tasarım Anketi </title>
</head>
<body style="background-color:#d3ea93">
<center> <h1 style="color:red"> ANKET </h1> </center>
<form >
<fieldset><legend>Soru 1 </legend>
En sevdiğiniz yabancı dizi? </br>
<label> <input type="radio" name="serie" value="Game of Thrones">Game of Thrones </label>
<label> <input type="radio" name="serie" value="Person of İnterest">Person of Interest </label>
<label> <input type="radio" name="serie" value="South Park">South Park </label>
<label> <input type="radio" name="serie" value="Black Mirror">Black Mirror </label>
</fieldset>
</form>
<form >
<fieldset><legend>Soru 2 </legend>
En sevdiğiniz bilgisayar markası? </br>
<label> <input type="radio" name="marka" value="Asus">Asus </label>
<label> <input type="radio" name="marka" value="HP">HP </label>
<label> <input type="radio" name="marka" value="Toshiba">Toshiba </label>
<label> <input type="radio" name="marka" value="Dell">Dell </label>
</fieldset>
</form>
<form>
<fieldset><legend>Soru 3 </legend>
Nerede yaşamak istersiniz?</br>
<label> <input type="radio" name="yer" value="Türkiye">Türkiye </label>
<label> <input type="radio" name="yer" value="Mars">Mars </label>
<label> <input type="radio" name="yer" value="Avustralya">Avustralya </label>
<label> <input type="radio" name="yer" value="Yeni Zelanda">Yeni Zelanda </label>
</fieldset>
</form>
<form>
<fieldset><legend>Soru 4 </legend>
Nasıl ölmek istersiniz?</br>
<label> <input type="radio" name="nasil" value="Araba Kazasında ">Araba Kazası </label>
<label> <input type="radio" name="nasil" value="Uzay Boşluğunda">Uzay Boşluğunda </label>
<label> <input type="radio" name="nasil" value="Ecelimle">Ecelimle </label>
<label> <input type="radio" name="nasil" value="Maganda Kurşunu">Maganda Kurşunu </label>
</fieldset>
</form>
<input type="button" id="btnKaydet" value="Kaydet" onclick="findSelection()"></input>
</body>
</html>
You can use javascript to achieve this but ultimately you want to learn a server-side programming language, like php. To me php is the best option.
If you Google form and click the mozilla device docs for it you'll see an attribute called action, this attribute tells the form where to go or what to do (with inline javascript, but I highly recommend against this). You'll also find an attribute called method. Method is responsible for how the form handles the input values. The two most common values are post and get.
I usually only ever use post, because I'm posting the data to a script.
The most common use is something like
<form method="post" action="/area/scripts/post/form.php">
However, getting really fun with an mvc, would more look like:
<form method="post" action="<?php echo $this->getFormAction(); ?>">
Then in your form.php page you handle the data. To see what I mean, place this in your form.php for now:
<?php
var_dump($_POST) ;
This will display your form data.
To link it back to your idea of displaying on same page, you can also use ajax, however this means including jquery into your site. It 100% makes life easier but it does increase your sites size. Of course you can opt for the .min script but still, you include in every page, so..
Anyway. Using pure html I'm not sure is possible, javascript is a browser side programming language and I'm not sure entirely if you can assign values dynamically, you probably can but I'm no javascript expert.
I recommend using php for this as it also makes it secure (if you follow convention and do it correctly using safe code)
Also, I prefer this as a comment as an actual answer because it doesn't directly deal with your problem or its associated tags, but the character limit is not enough for a comment like this. Feel free to downvote if preferred and I'll simply remove if it gets to -3
Update after seeing comment
To combine variables in javascript you use + to concat strings.
E.g.
var message = document.getElementById('myId') + ' ' + document.getElementById('myIdTwo');
alert(message);
This only an example of how to use, but this should be what you're looking for.
Good luck!
you can do it via jquery give all your fields id
and write like this
<script>
$(document).ready(function()
{
$("#Button1).click(function()
{
$("#abc1").val($("#abc").val());
})
</script>
<body>
<input type="text" id="abc" />
<input id="Button1" type="button" value="button" />
<input type="text" id="abc1" />
</body>

How to validate with Javascript?

Thanks to having to work so much, I am completely confused on JavaScript. I have tried so many things and have not gotten my form to validate even once. I have to use plain JavaScript to:
**Validate the email - the email must have # and the domain should be yahoo.com
Phone No.: Must contain exactly 10 digits
Age: Must be a positive number less than 120
The validation should happen when the user submits the form. In case any of the above validation fails, the corresponding fields should be highlighted in red
If the validation is successful, the page should redirect to http://yahoo.com**
I'm not looking for someone to necessarily give me the exact answer, but push me in the right direction, because I do have a basic understanding of JS.
<!DOCTYPE HTML>
<div id="form">
<form name="myForm" action="http://fsu.edu" onsubmit="return validateForm()" method="post">
<head>
<link rel="stylesheet" HREF="C:\Users\Neshia\Desktop\CGS3066\Form Validation Style Sheet.css" TYPE="text/css">
<script>
function ValidatemyForm()
{
var email = document.myForm.email;
var phone = document.myForm.phonenumber;
var age = document.myForm.age;
}
{
age = age.replace(/[^0-9]/g, '');
if(age.length != 10)
{
alert("not 10 digits");
}
else {
alert("yep, its 10 digits");
}
}
</script>
</head>
<div id="header">
<hr id="HR1">
<h1> Web Programming: Assignment 3 </h1>
<p> Form Validation with Javascript </p>
<hr id="HR2">
</div>
<div id="input">
First name: <br>
<input type="text" name="firstname">
<br>
Last name: <br>
<input type="text" name="lastname">
<br>
FSU Email: <br>
<input type= "text" name="email">
<br>
Phone No.: <br>
<input type="numbers" name="phonenumber">
<br>
Age: <br>
<input type="numbers" name="age">
</div>
<hr id="HR3">
<br>
<div id="Sex">
Sex: <br>
<input type="radio" name="sex" value="male"> Male
<br>
<input type="radio" name="sex" value="female"> Female
<br>
<input type="radio" name="sex" value="other"> Other
</div>
<hr id="HR32">
<div id="languages">
Programming languages you want to learn: <br>
<input type="checkbox" name="python" value="python"> Python
<br>
<input type="checkbox" name="java" value="java"> Javascript
<br>
<input type="checkbox" name="C++" value="C++"> C++
<br>
<input type="checkbox" name="lisp" valie="lisp"> Lisp
</div>
<hr id="HR32">
<div id="submit">
<input type="Submit" value="Submit">
</div>
<hr id="HR12">
</form>
</div>
Aneshia,
You have a few problems. First the function listed in the "onsubmit" attribute of your form does not match your javascript function. Also there are some problems with your {} braces. After you get that fixed be sure to call .value after your form elements to get the value of the input ie. (document.myForm.email.value).
Here is the code with some fixes:
<form name="myForm" onsubmit="return validateForm()" method="post">
<head>
<link rel="stylesheet" HREF="C:\Users\Neshia\Desktop\CGS3066\Form Validation Style Sheet.css" TYPE="text/css">
<script>
function validateForm() {
var email = document.myForm.email.value;
var phone = document.myForm.phonenumber.value;
var age = document.myForm.age.value;
console.log(age)
var okToSubmit = true;
age = age.replace(/[^0-9]/g, '');
if (age.length != 10) {
alert("not 10 digits");
okToSubmit = false;
} else {
alert("yep, its 10 digits");
}
if (age > 120 || age < 0) {
alert("Must be a positive number less than 120");
okToSubmit = false;
}
return okToSubmit;
}
Another thing that may help is to bring up the javascript console in your browser and run your function manually in the console by typeing 'validateForm();'
You may be intrigued to note that html5 now validates some of these forms so you do not need to use Javascript.
See HTML Form Validation
You asked about email, age and phone.
Consider the following examples::
<form>
<input type="email" name="email" pattern=".*#yahoo\.com"> <br>
<input type="number" min="18" max="120" name="age"> <br>
<input type="tel" name="phonenumber"> <br>
<input type='submit'>
</form>
If you want the fields to be required you could use
<form>
<input type="email" name="email" pattern=".*#yahoo\.com" required> <br>
<input type="number" min="18" max="120" name="age" required> <br>
<input type="tel" name="phonenumber" required> <br>
<input type='submit'>
</form>
See http://diveintohtml5.info/forms.html
In your comments a few days later, you mentioned needing to do this in Javascript. I think the best way is still using HTML5 and a clever way to do this if you have to use javascript might be to set the input attributes through javascript. Something like this could get you started on the logic.
While I generally do not like getting this specific in the code, I commented things so you can get a general feel for how you can work with data in javascript.
function validate(event){
// First we stop the form from even submitting until we run the code below
event.stopPropagation();
// Here we are going to place a reference to the objects we want to validate in an array
var references = ['email','age','phonenumber'];
// Now we are going to grab our list of inputs from the page
var inputs = document.getElementsByTagName('input');
// We run through a for loop to look for specific elements
for(i = 0; i < inputs.length; i++){
/*
This line simply asks, is the 'name' of this element inside our references array.
This works by using the indexOf function which is built into Javascript.
indexOf simply provides the index where it finds the phrase you are looking for.
In this example, we are using it to see if an index exists by checking it against negative 1
*/
if(references.indexOf(inputs[i].getAttribute('name')) > -1){
// A switch block lets you present a different outcome based on the criteria being looked for
switch(inputs[i].getAttribute('name')){
// In this case we see if we get an email named element
case 'email':
// We set the attributes to match our requirements for this email element and so on through this switch block for age and phonennumber
inputs[i].setAttribute('type','email');
inputs[i].setAttribute('pattern','.*#yahoo\.com');
break;
case 'age':
inputs[i].setAttribute('type','number');
inputs[i].setAttribute('min',18);
inputs[i].setAttribute('max',120);
break;
case 'phonenumber':
inputs[i].setAttribute('type','tel');
break;
}
// When we are all done, we set the elements to be required
inputs[i].setAttribute('required',true);
}
}
// Now we submit the form
event.submit();
}
<form>
<input type="text" name="email"> <br>
<input type="text" name="age"> <br>
<input type="text" name="phonenumber"> <br>
<input type='submit' onclick='validate(event)'>
</form>
<input type='text' id='txtEmail'/>
<input type='submit' name='submit' onclick='Javascript:checkEmail();'/>
<script language="javascript">
function checkEmail() {
var email = document.getElementById('txtEmail');
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (!filter.test(email.value)) {
alert('Please provide a valid email address');
email.focus;
return false;
}
}
</script>

Choosing page depending on users choices

I'm trying to create a webpage where a user asked their name(textbox) and gender(radio buttons) on the front page. This will then link to a new page will be dependent on whether they chose if they are male or female, it will also need to display their name as entered in the text box.
So far I have the name part working using javascript this is on the front page with the form action directed to a new page:
// Called on form's `onsubmit`
function tosubmit() {
// Getting the value of your text input
var mytext = document.getElementById("mytext").value;
// Storing the value above into localStorage
localStorage.setItem("mytext", mytext);
return true;
}
and this is on the other page:
// Called on body's `onload` event
function init() {
// Retrieving the text input's value which was stored into localStorage
var mytext = localStorage.getItem("mytext");
// Writing the value in the document
document.getElementById("name").innerHTML = mytext;
}
The main problem here is that this always directs to the same page. Can anyone tell me how I could solve this problem and add in the option for a user to choose their gender and the next page would be dependant on this choice?
edit: This is my form
<form class="enter-name" name="myform" onsubmit="tosubmit();" action="page1.html">
<input id="mytext" type="text" name="data" placeholder="Enter name" maxlength="12">
Male: <input type="radio" name="gender" value="male" /><br />
Female: <input type="radio" name="gender" value="female" /><br />
<input id="name-submit" type="submit" value="">
</form>
You can solve this with php - have the form post to a handler that will redirect based on the posted values. In this case the handler is in the same page:
<?php
if(isset($_POST['name'], $_POST['gender'])){
$page = ($_POST['gender']=='male')? 'male-page.php' : 'female-page.php';
header('Location:'.$page.'?name='.$_POST['name']);
die();
}
?>
<html>
<head><!-- head stuff here--></head>
<body>
<form class="enter-name" name="myform" action="" method="post">
<input id="mytext" type="text" name="name" placeholder="Enter name" maxlength="12">
Male: <input type="radio" name="gender" value="male" /><br />
Female: <input type="radio" name="gender" value="female" /><br />
<input id="name-submit" type="submit" value="">
</form>
</body>
</html>
in the redirected to page, you can access name via the query string parameter in php:
<div id="name">
<?php echo $_GET['name'];?>
</div>

Categories

Resources