How to handle and process data from a form? - php

This is my code (index-wamp.php):
`<!DOCTYPE html>
<html>
<head>
<title>Index of Commons || Sandwich Fun®</title>
<!-- SANDWICH FUN (C) COURTESY OF MISTY CO, WITH PARTNERS
2023-02-04 20:48
--Revision--
--Revision-- -->
<!-- Det är psykologi. Frågan är bara hur psykologi riktigt tänker. Det verkar väldigt konstigt. -->
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="smorgass.css">
<meta charset="UTF-8"> <!-- This is a game! -->
<meta name="author" content="Elise Knuuti of Misty Co">
<meta name="keywords" content="horses, game, horse-sim">
<meta name="description" content="A fully-featured horse game (sim) for ALL ages!">
<!-- It is forbidden to talk about Granberg in the company. -->
<!-- & Linda Jonasson & -->
<!-- The voices talk so creepy. They have destroyed my whole life. -->
<!-- Kommer att skicka ett hatbrev till Granberg -->
<!-- I'm going to code my game. I saw a picture of Magdalena Andersson. They are really creepy in Sweden. Ulf Kristersson is a perfect prime minister. -->
<!-- I have to explain my code. I have a few bugs. They are difficult. Josefine's mamma is banned. I have this one bug, problem with it. I don't understand the bug, it was text in the PHP book. :) Hm... What kind of bug can that be? Really, it's because it's a dangerous game! :D Now I get it! -->
</head>
<body>
<form action='register.php' method='POST'>
<fieldset>
<label for="username">Användarnamn:</label>
<input type='text' name='username'><br>
<label for="email">E-post:</label>
<input type='text' name='email'><br>
<label for="password">Lösenord:</label><input type="password" name="password"><br>
<input type='submit' value='LOGGA IN()!'>
</fieldset>
<?php
$a = $a + rand(1,10);
$b = $b + rand(1,10);
$answer = $a + $b;
?>
<?php echo "$a + $b ="; ?>
<input type='text' name='hausin'>
<input type='submit' name='captcha_reloaded' value='Sign in with CAPTCHA'>";
<!-- <?xml version="1.0" encoding="UTF-8"?>
<note>
<to>Computer HQ</to>
<from>Elise Knuuti</from>
<heading>Reminder</heading>
<body>We have high security in the company. I just finished a CAPTCHA (it's working!), and I need to fix the bugs. This is a painting computer. You should recall I want to create a phone.</body>
</note> -->
</body>
</html>`
Now, I want to check if the user put in the right result of the addition! Do I do this on the page register.php? Or, do I do this in the same file (index-wamp.php)? And so on.
I want to know how to process form data.

I think I solved it.
<form action='<?php if ($answer === $hausin) { echo "register.php"; } ?>' method='POST'>

Related

I'm trying to figure out how to get the variable $_GET to work so that the H1 tag turns into what the user imputted

The question I'm trying to answer is below
Create a new PHP file named lab2.php.
Inside, add the HTML skeleton code and give its title “Lab Week 2"
Within the body tag, create a h1 tag that says "Enter the name of your favourite musical artist"
Add a section tag inside the body tag.
Create a form tag and use the $_GET method to get users to input their favorite artist. Store the user input into variables.
Create a submit button for the user to input their favorite artist.
Check whether the variable is empty or not.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title> Fav Artist</title>
<meta name="author" content="Sean Kingston">
<meta name="viewport" content="with=device-width, initial-scale=1.0">
</head>
<body>
<!-- H1 tag I want to change once the user clicks on submit button-->
<h1> Enter the name of your favourite musical artist </h1>
<!--Form-->
<form method="get">
<input type="text" name="name" />
<input type="submit" value="Submit" name="sub">
</form>
</body>
</html>
<?php
//isset not working//
if(isset($_GET['name'])){
echo $_GET['name'];
}
?>
<?php
show_source(FILE);
</html>
?>
i'm gonna hazard a guess and asume that this is some sort of educational task.
but nevertheless here is how i understand the tasks.
<?php
//1.Create a new PHP file named lab2.php.
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Lab Week 2</title><!-- 2.Inside, add the HTML skeleton code and give its title “Lab Week 2" -->
</head>
<body>
<h1><?php
// 5. use the $_GET method to get users to input their favorite artist. Store the user input into variables.
$favouriteMusicalArtist = $_GET['favourite_musical_artist'];
// 7.Check whether the variable is empty or not.
if (empty($favouriteMusicalArtist)) {
//3.Within the body tag, create a h1 tag that says "Enter the name of your favourite musical artist"
echo 'Enter the name of your favourite musical artist';
} else {
echo 'Your favourite musical artist is: ' . $favouriteMusicalArtist;
}
?></h1>
<!-- 4.Add a section tag inside the body tag. -->
<section>
<!-- 5.Create a form tag -->
<form method="GET">
<input type="text" name="favourite_musical_artist"/>
<!-- 6.Create a submit button for the user to input their favorite artist. -->
<button type="submit">Submit</button>
</form>
</section>
</body>
</html>
Now if this is some sort of test don't just copy of the internet. Do some fiddling around with the code and try to learn something :-)

solving problems in session? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I have created two pages , one is index.php and admin.php . In the first page or index.php , i have created a loggin form so that i can access the admin.php page trough the loggin or like this enter image description here
Now by logging in i go to admin.php page. Here is the question what i want to ask about that now when ever i click the back button or next button in the chrome. I am returning to the admin.php page . I have tryed the session_start() and the if(!isset($password) || !isset($user)){}. But this code for obvious reasons doesnt work . So can someone help me out with this ?
The code for the example is here index.php
<?php
session_start();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<title>Admin</title>
</head>
<body>
Reset
<div class="image">
<img src="img/adi.png" alt="image"> <!-- image -->
</div>
<form action="inc/login.php" method="POST"><br>
<p class="title">Log In</p>
<label for="Username">User :</label>
<input type="text" name="username" id="user"> <br> <!--username -->
<label for="Password">Password :</label>
<input type="password" name="password" id="password" ><br><br> <!-- password -->
<label for="showpassword" class="showpassword">Show Password</label>
<input type="checkbox" name="checkbox" id="chk" ><br><br> <!-- checkbox -->
<input type="submit" name="submit" value="Log in" > <!-- enter -->
</form>
<?php
if(!isset($_GET['Login'])){
exit();
}else{
$check=$_GET['Login'];
if($check=="userEmpty"){
echo "<p class='class_login'>user is empty</p> ";
}elseif($check=="passwordEmpty"){
echo "<p class='class_login'>password is empty</p> ";
}elseif($check=="wrongUser"){
echo "<p class='class_login'>user is wrong</p> ";
}elseif($check=="Password"){
echo "<p class='class_login'>password is wrong</p> ";
};
} ;
?>
<script src="js/main.js"></script>
</body>
</html>
and the code for the admin.php is this one :
<?php
session_start();
if(!isset($username) || !isset($password)){
header("location:index.php?data=closed");
exit();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<script>
window.history.forward();
</script>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<title>Document</title>
</head>
<body>
<div class="top">
Log Out
</div>
</body>
</html>
Besides using of session_start you need to store something in the session, using something like this:
$_SESSION['userId'] = <value>;
which must be set in your login.php and checked by your admin.php if user has access rigths to visit secured page. I.e. you need to check:
if (isset($_SESSION['userId']) && $_SESSION['userId'] == <value>) {
// access granted
}

Simple PHP to process HTML Form

I am sure this is very simple to many of you!! I am trying to learn basic HTML / PHP form processing. The site is hosted on a local Apache server. I have had PHP working correctly and am happy that the server is working fine.
I have two files, one is settings.html, where the user has a form of 3 elements which they can enter some float values into (humidity, temperature and light tolerances). The submit button triggers a separate file called process.php which should display the three values. The code is as follows:
settings.html:
<!DOCTYPE html>
<html>
<head>
<meta content="text/html; charset=ISO-8859-1" http-equiv="content-type">
<meta http-equiv="refresh" content="179" >
<title>Sparks - Settings</title>
<link rel="stylesheet" type="text/css" href="css/default.css">
</head>
<body>
<div id="logo">
<img style="width: 335px; height: 142px;" alt="ESP8266 Logo" src="images\imgESP8266.png">
</div>
<br>
<form method="post" action="php/process.php">
Humidity Tolerance : <input type="float" name="humTolerance" placeholder="Enter %" /><br />
Temperature Tolerance : <input type="float" name="tempTolerance" placeholder="Enter %" /><br />
Light Tolerance : <input type="float" name="lightTolerance" placeholder="Enter %" /><br />
<input type="submit" value="Submit" />
</form>
</body>
<html>
php/process.php:
<?php //process.php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$humTolerance = $_POST["humTolerance"];
$tempTolerance = $_POST["tempTolerance"];
$lightTolerance = $_POST["lightTolerance"];
}
echo <<<_END
<html>
<head>
<meta content="text/html; charset=ISO-8859-1" http-equiv="content-type">
<meta http-equiv="refresh" content="179" >
<title>Sparks - Settings</title>
<link rel="stylesheet" type="text/css" href="css/default.css">
</head>
<body>
humTolerance is: $humTolerance<br>
tempTolerance is: $tempTolerance<br>
lightTolerance is: $lightTolerance<br>
</body>
</html>
_END;
?>
This is producing the HTTP ERROR 500 and I can't see why. Please can I have some help? Thanks.
As I said in comments:
"the (first) problem is in your heredoc closing identifier it contains spaces before it."
and
"the second one: type="float" isn't a valid type for an input"
You need to replace those input types with ones that are valid.
https://developer.mozilla.org/en/docs/Web/HTML/Element/input
Note that not all browsers support certain HTML5 attributes, see the above as a reference.
So use type="number" or type="text".
PHP with spaces removed before the closing heredoc identifier.
<?php //process.php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$humTolerance = $_POST["humTolerance"];
$tempTolerance = $_POST["tempTolerance"];
$lightTolerance = $_POST["lightTolerance"];
}
echo <<<_END
<html>
<head>
<meta content="text/html; charset=ISO-8859-1" http-equiv="content-type">
<meta http-equiv="refresh" content="179" >
<title>Sparks - Settings</title>
<link rel="stylesheet" type="text/css" href="css/default.css">
</head>
<body>
humTolerance is: $humTolerance<br>
tempTolerance is: $tempTolerance<br>
lightTolerance is: $lightTolerance<br>
</body>
</html>
_END;
?>
Use PHP's error reporting also:
http://php.net/manual/en/function.error-reporting.php
If you don't have access to logs, then set that to catch and display.

Contact form redirection is not working

i have set up a contact form for my website but i am having an issue with the submit button is not redirecting to my thank-you.php once i click it, i have tried so many things to resolve this but i have had no luck what so ever.
It just redirects to a blank page, you can test the submit form here http://www.sacredpurity.com/sacredpurity/contactform.php
Here is the code for the contact form
<i>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<title>Sacred Puritys Online Store - Bringing you health and vitality</title>
<!-- Bootstrap Core CSS -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<!-- Custom CSS -->
<link href="css/shop-homepage.css" rel="stylesheet">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<!-- Navigation -->
<nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">
<div class="container">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav">
<li>
Home
</li>
<li>
About
</li>
<li>
Order
</li>
<li>
Contact
</li>
</ul>
</div>
<!-- /.navbar-collapse -->
</div>
<!-- /.container -->
</nav>
<!-- Page Content --> <br><br><br><br>
<div class="container">
<div class="row">
<div class="col-md-3">
<img src="http://www.sacredpurity.com/sacredpurity/Images/spwebsitelogo.png">
<b><center><p class="lead">Our Products</p> </center></b>
<div class="list-group">
Turpentine
Castor Oil
Activated Charcoal
Organic Coffee
Sugar Cubes
Enema Kits
B12 Methylcobalamin
Niacin (Vitamin B3)
Chromium Chelate
<br>
<br>
</div>
</div>
<?PHP
/*
Contact Form from HTML Form Guide
Contact Form from HTML Form Guide
This program is free software published under the
terms of the GNU Lesser General Public License.
See this page for more info:
http://www.html-form-guide.com/contact-form/php-contact-form-tutorial.html
*/
require_once("./include/fgcontactform.php");
require_once("./include/captcha-creator.php");
$formproc = new FGContactForm();
$captcha = new FGCaptchaCreator('scaptcha');
$formproc->EnableCaptcha($captcha);
//1. Add your email address here.
//You can add more than one receipients.
$formproc->AddRecipient('contact#sacredpurity.com'); //<<---Put your email address here
$formproc->SetFormRandomKey('n91LqHNvMrpoXte');
if(isset($_POST['submitted']))
{
if($formproc->ProcessForm())
{
$formproc->RedirectToURL("thank-you.php");
}
}
?>
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
<head>
<meta http-equiv='Content-Type' content='text/html; charset=utf-8'/>
<title>Contact us</title>
<link rel="STYLESHEET" type="text/css" href="contact.css" />
<script type='text/javascript' src='scripts/gen_validatorv31.js'></script>
<script type='text/javascript' src='scripts/fg_captcha_validator.js'></script>
</head>
<body>
<font size="5">Contact Us</font> <br><br>
If you have a query please drop us a note using the form below.
<br><br>
The fastest way for us to respond is through our contact us form as we can respond throughout the day while we are busy packing orders for quick dispatch.
<br><br>
Please note that we are an online company that currently does not use any other forms of contact except via this contact form or email (contact#sacredpurity.com).
<br><br>
We will typically respond within hours of receiving your message.
<br><br>
<form id='contactus' action='<?php echo $formproc->GetSelfScript(); ?>' method='post' accept-charset='UTF-8'>
<fieldset >
<input type='hidden' name='submitted' id='submitted' value='1'/>
<input type='hidden' name='<?php echo $formproc->GetFormIDInputName(); ?>' value='<?php echo $formproc->GetFormIDInputValue(); ?>'/>
<input type='text' class='spmhidip' name='<?php echo $formproc->GetSpamTrapInputName(); ?>' />
<div class='short_explanation'><font size="2"><b>* required fields</b></font></div>
<div><span class='error'><?php echo $formproc->GetErrorMessage(); ?></span></div>
<div class='container'>
<label for='name' >Your Full Name*: </label><br/>
<input type='text' name='name' id='name' value='<?php echo $formproc->SafeDisplay('name') ?>' maxlength="50" /><br/>
<span id='contactus_name_errorloc' class='error'></span>
</div>
<div class='container'>
<label for='email' >Email Address*:</label><br/>
<input type='text' name='email' id='email' value='<?php echo $formproc->SafeDisplay('email') ?>' maxlength="50" /><br/>
<span id='contactus_email_errorloc' class='error'></span>
</div>
<div class='container'>
<label for='message' >Message:</label><br/>
<span id='contactus_message_errorloc' class='error'></span>
<textarea rows="10" cols="50" name='message' id='message'><?php echo $formproc->SafeDisplay('message') ?></textarea>
</div>
<div class='container'>
<div><img alt='Captcha image' src='show-captcha.php?rand=1' id='scaptcha_img' /></div>
<label for='scaptcha' >Enter the code above here:</label>
<input type='text' name='scaptcha' id='scaptcha' maxlength="10" /><br/>
<span id='contactus_scaptcha_errorloc' class='error'></span>
<div class='short_explanation'>Can't read the image?
<a href='javascript: refresh_captcha_img();'>Click here to refresh</a>.</div>
</div>
<div class='container'>
<input type='submit' name='Submit' value='Submit' />
</div>
</fieldset>
</form>
<!-- client-side Form Validations:
Uses the excellent form validation script from JavaScript-coder.com-->
<script type='text/javascript'>
// <![CDATA[
var frmvalidator = new Validator("contactus");
frmvalidator.EnableOnPageErrorDisplay();
frmvalidator.EnableMsgsTogether();
frmvalidator.addValidation("name","req","Please provide your name");
frmvalidator.addValidation("email","req","Please provide your email address");
frmvalidator.addValidation("email","email","Please provide a valid email address");
frmvalidator.addValidation("message","maxlen=2048","The message is too long!(more than 2KB!)");
frmvalidator.addValidation("scaptcha","req","Please enter the code in the image above");
document.forms['contactus'].scaptcha.validator
= new FG_CaptchaValidator(document.forms['contactus'].scaptcha,
document.images['scaptcha_img']);
function SCaptcha_Validate()
{
return document.forms['contactus'].scaptcha.validator.validate();
}
frmvalidator.setAddnlValidationFunction("SCaptcha_Validate");
function refresh_captcha_img()
{
var img = document.images['scaptcha_img'];
img.src = img.src.substring(0,img.src.lastIndexOf("?")) + "?rand="+Math.random()*1000;
}
// ]]>
</script>
<!-- /.container -->
<center> <br>
<div class="container">
<hr>
<!-- Footer -->
<footer>
<div class="row">
<div class="col-lg-12">
<p> * This statement has not been evaluated by the Food and Drug Administration. This product is not intended to diagnose, treat, cure, or prevent any disease.
This dietary supplement is not a substitute for a licensed physician's medical advice. If any of its constituents, claims, or instructions herein conflict
with that of a treating licensed physician, defer to the opinion of the physician. This supplement and its supporting information is intended for people
in good health. It is the user's responsibility to know his or her medical history and ensure that supplements he or she takes do not create an adverse reaction.
<br><br>
Sacred Purity warrants that the products listed above and sold through our online system will be merchantable and free from material defects. Sacred Puritys makes
no other warranties, whether expressed or implied, including the implied warranty of fitness for a particular purpose. In the event that this product is found to
be defective, Sacred Puritys sole responsibility shall be to either refund the purchase price for the product or replace it with a product free of defects, at Sacred Puritys
option. Sacred Puritys shall not be responsible for any damage resulting from the improper use of this product. In addition, Sacred Puritys shall not be liable for
any special, indirect, consequential, exemplary or incidental damages, including, but not limited to, loss of profits or business opportunities.
<br><br>
Purchases of products/services from us are final and non-refundable. Cancellation or return of any individual component contained within a product package will require
the remaining items to be charged at full retail value. All associated shipment costs, including duties, customs and/or brokerage fees, are non-refundable and are the
responsibility of the customer. All products are non refundable.
<br><br>
Sacred Purity (hereinafter referred to as "we" and/or "us") operates FOB shipping point, freight prepaid. This means that the responsibility for the goods transfers
from us to buyer (hereinafter referred to as "you") the moment the package leaves our warehouse. Therefore we are NOT responsible for delays, losses, damages,
thefts, confiscations, additional postal fees in transit or at destination, taxes, etc. This list of events we are NOT responsible for is incomplete and may change
at any time. All claims about missing / damaged / delayed / confiscated / modified merchandise must be made directly with the shipping carrier, NOT us.
You should buy shipping insurance if you feel you need it, please contact us if you decide to insure your package. A processed order usually ships within two business
days unless noted, and we make a best effort to ship within one business day. For temporarily out of stock items or delayed shipments, you will be contacted by e-mail
or telephone. Our website does not display quantities available because the turnover is continuous. If an item is permanently unavailable or discontinued, the charge
will be voided or a complete refund will be made to your card. We will notify you if this occurs. Unless otherwise noted, all items ship directly from our shop base in
Thailand. Contact us via e-mail for alternative shipping method / carrier, special
orders or larger orders that you think warrant an insurance.
<br><br>
It is the sole responsibility of the client/buyer to ensure that the items ordered from our online store are permissible for mailing/receipt in the destination country.
We assume absolutely no responsibility for issues arising due to ordering prohibited/restricted items and any subsequent customs/legal issues in the destination or
transit countries. We are not responsible for any additional customs charges or fees once your package has left our facility. Customs charges and fees are the sole
responsibility of the purchaser. If you are unfamiliar with customs regulations, fees and charges, please speak to your local postal or customs office for more information.
If customs fees and charges are refused at the time of delivery, your order MAY be returned and you will not receive a refund for shipment costs. If a package is lost
in transit, confiscated by authorities, damaged, stolen, etc we are NOT responsible and the issue should be taken up with the local postal, custom, and law enforcement
authorities. Again, once a package is shipped we have no responsibility for it and we will offer no refund if something happens to it after shipping. If the package
is returned to us as undeliverable, please contact us to discuss what can be done to send it again.
<br><br>Copyright © Sacred Purity 2016</p> </center>
</div>
</div>
</footer>
</div>
<!-- /.container -->
<!-- jQuery -->
<script src="js/jquery.js"></script>
<!-- Bootstrap Core JavaScript -->
<script src="js/bootstrap.min.js"></script>
</body>
</html>
Also here is the page it is meant to redirect to known as thank-you.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
<head>
<meta http-equiv='Content-Type' content='text/html; charset=utf-8'/>
<title>Thank you!</title>
<link rel="STYLESHEET" type="text/css" href="contact.css">
</head>
<body>
<h2>Thanks for contacting us!</h2>
</body>
</html>
Assuming your RedirectToURL is a function which accepts parameter as URL. try including below code in your function. if no headers are sent after the php closing tags it will directly set the headers to $url or else will use the javascript redirection.
function RedirectToURL($url)
{
if (!headers_sent())
{
header('Location: '.$url);
exit;
}
else
{
echo '<script type="text/javascript">';
echo 'window.location.href="'.$url.'";';
echo '</script>';
echo '<noscript>';
echo '<meta http-equiv="refresh" content="0;url='.$url.'" />';
echo '</noscript>'; exit;
}
}

Button type in a form, with a control script in php page not working as expected

I already posted something similar but I didn't receive good answer mainly for my fault, my way to ask wasn't good.
Now I prepared an example to explain what I'm looking for:
I've got a php file with a form and a control script in it, so I post you the stripped example versions:
<html>
<head>
<title> Inserimento</title>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />
<link href="style.css" rel="stylesheet" type="text/css">
<script>
function controllo(){
with(document.insert) {
if(citta.value=="" || citta.value=="undefined") {
alert("Attenzione: tutti i campi con asterisco devono essere compilati!");
citta.focus();
return false;
}
}
//alert("Controllo effettuato con successo. Il modulo sara inviato.");
return true;
}
</script>
</head>
<body>
<!-- <div id="scatola" align="center"> -->
<?php
echo"
<form name =\"insert\" onSubmit=\"return controllo();\" action=\"geocode_prova.php\" enctype=\"multipart/form-data\" method=\"post\">
<div id=\"inserimento\" align=\"center\">
<h1> Compila con i dati dell'Annuncio</h1>
<label for=\"citta\">Citta'* </label><input type=\"text\" name=\"citta\" id=\"citta\"/>
<button onclick=\"submit();\">Inserisci!</button>
<!-- <input type=\"Submit\" id=\"Submit\" name=\"Inserisci\"/> -->
</div>
</form>
";
?>
<!-- </div> -->
</body>
</html>
So there is a simple function that controls the only input field.
The php file called does a bunch of things, I've stripped it down to only this.
<?php
require_once("insert_ok.html");
# header('Location: insert_ok.html');
?>
So it only redirects to another page.
My problem is that if I use "input type=\"Submit\" on the first file it works correctly, and if I enter nothing in the filed it stops me, while if I use button onclick=\"submit();\ even if the input field is empty I get the error from the function but then the script let me proceed to the next page.
can you help me?
change
<button onclick=\"submit();\">Inserisci!</button>
to
<button onclick=\"return controllo(document[insert]);\">Inserisci!</button>

Categories