I am working on a program that has the user type in their course, first name, last name, and description of a program. The code is mostly done except for getting the clear the array button to work. When I use the unset array to clear the array on its own, it works but then the user cant enter in more data. I want to have the user be able to clear the data. Here is my code:
<?php
session_start();
?>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<script>
function showHint(str) {
if (str.length == 0) {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
}
xmlhttp.open("GET", "gethint.php?q="+str, true);
xmlhttp.send();
}
}
</script>
<?php
function clear(){ //this is the problem
unset($_SESSION['courses']);
return true;
}
?>
</head>
<body>
<form method="POST">
Course: <input type="text" name="courses" />
<br /><br />
First Name: <input type="text" name="firstname" />
<br /><br />
Last Name: <input type="text" name="lastname" />
<br /><br />
Description: <input type="text" name="description" />
<br /><br />
<input type="submit" name="submit" value="Submit">
</form>
<?php
// First we check if the form has been sent and we have a value
if (!empty($_POST['courses'])) {
if (!isset($_SESSION['courses']))
$_SESSION['courses'] = array(); // Initialize the array if it doesn't exist
// Add the value to our array
$_SESSION['courses'][] = array("course" => $_POST['courses'],
"firstname" => $_POST['firstname'],
"lastname" => $_POST['lastname'],
"description" => $_POST['description']);
}
// If there are values to show, print them!
if (!empty($_SESSION['courses'])) {
foreach ($_SESSION['courses'] as $course) {
echo $course['course']." ".
$course['firstname']." ".
$course['lastname']." ".
$course['description']." ".
"<br />";
}
}
?>
<input type="submit" name="Clear" value="Clear" onclick="clear()"> //this is the problem
<?php
?>
</body>
</html>
Can someone please help?
<?php
// there is nothing wrong with this function.
function clear() {
unset($_SESSION['courses']);
return true;
}
?>
Okay, this function is fine, there is nothing wrong with it. But, you can't use this function like:
<input type="submit" name="Clear" onclick="Clear()" /> <!-- this is the problem -->
You see that onclick="Clear()", and that php function clear()? Yeah, you can't execute php functions with a html onclick="". You can only do that with javascript functions.
But you can do something like this:
<?php
if(isset($_POST['Clear']))
{
// if the user submits the form, then the following code will be executed.
clear();
}
?>
<input type="submit" name="Clear" value="Clear" onclick="clear()">
clear() would be calling a javascript function. You have correctly written a php function.
Check the value of the submit button "Clear" to be "clear" and if true run the PHP function clear().
if ($_POST['Clear'] === 'clear') {
clear();
}
Related
I am having trouble with a same page AJAX/JavaScript/PHP Captcha validation code. The original code is from http://www.phpcaptcha.org. We are using a third party site to store all of our form data into a database that is edited by multiple people. Lately we've been receiving a ton of spam so we're trying to implement this Captcha.
I'll cut to the chase here. The code is set to 'return false' every time. I need it to 'return true' if certain conditions are met. The code is as follows:
<?php
session_start(); // this MUST be called prior to any output including whitespaces and line breaks!
$GLOBALS['DEBUG_MODE'] = 1;
// CHANGE TO 0 TO TURN OFF DEBUG MODE
// IN DEBUG MODE, ONLY THE CAPTCHA CODE IS VALIDATED, AND NO EMAIL IS SENT
// EMAIL is edited out for school use
if( isset($_POST['captcha_code']))
{
$a = array("error"=>0);
print json_encode($a);
}
// Process the form, if it was submitted (Original Code called process_si_contact_form())
process_si_zoho1();
?>
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/prototype/1.7.0.0/prototype.js"></script>
<script type="text/javascript">
//variables not part of original code
function reloadCaptcha()
{
//original code ElementId labled 'captcha_code'
document.getElementById('captcha').src ='securimage_show.php?sid=' + Math.random();
}
var r, Submit;
function processForm()
{
new Ajax.Request('<?php echo $_SERVER['PHP_SELF'] ?>', {
method: 'post',
//Original code did not state 'zoho1'
parameters: $('zoho1').serialize(),
onSuccess: function(transport) {
//Re-edited for school use. Not original code
try {
r = transport.responseText.evalJSON();
Submit = r.submit
if (r.error == 0) {
alert('Congrats!');
reloadCaptcha();
} else {
alert("There was an error with your submission.\n\n" + r.message);
}
} catch(ex) {
alert("There was an error parsing the json");
}
},
onFailure: function(err) {
alert("Ajax request failed");
}
});
return Submit;
}
}
</script>
The process_si-zoho1() is as follows:
<?php
//Original code process called 'process_si_contact_form())
function process_si_zoho1()
{
if ($_SERVER['REQUEST_METHOD'] == 'POST' && #$_POST['do'] == 'contact') {
// if the form has been submitted
foreach($_POST as $key => $value) {
if (!is_array($key)) {
// sanitize the input data
if ($key != '-------') $value = strip_tags($value);
$_POST[$key] = htmlspecialchars(stripslashes(trim($value)));
}
}
$captcha = $_POST['captcha_code']; // the user's entry for the captcha code
$errors = array(); // initialize empty error array
if (sizeof($errors) == 0) {
require_once dirname(__FILE__) . '/securimage.php';
$securimage = new Securimage();
if ($securimage->check($captcha) == false) {
$errors['captcha_error'] = 'Incorrect security code entered';
}
}
if (sizeof($errors) == 0) {
// no errors, send the form
//Edited out mail function from original code
//Changed JSON return array on successful validation to send new variable '$Submit' via serialized $entry
$Submit = true;
$entry = array('error' => 0, 'submit' => $Submit);
die(json_encode($entry));
} else {
$errmsg = $captcha_error;
foreach($errors as $key => $error) {
// set up error messages to display with each field
$errmsg .= " - {$error}\n";
$Submit = false;
}
//Added $Submit to the return array
$return = array('error' => 1, 'message' => $errmsg, 'submit' => $Submit);
die(json_encode($return));
}
} // POST
} // function process_si_zoho1()
?>
The 'processForm()' runs when the submit button is clicked. I'm sure i'm missing something really simple here, I'm just too involved in it. I really appreciate your help
I know that the value of 'Submit' is not defined until the PHP in the AJAX.Request() runs but I can't figure out how to define the variable from the start. FYI, the variables 'r' and 'Submit' are all declared outside the function itself so are global variables. If I try to insert a return into the try/catch it will always give me the error in the catch "There was an error parsing the json." Also, with the code as it is now, it will always give me the same error and submit the form anyways, as the value of Submit is blank. Even if I define the Global variable "Submit" as "false" it still returns as though it is blank.
If anything other than 'return false' is declared at the bottom of the function, it will submit the form without validating the Captcha. I'm very new to all this, but I've been researching for almost 2 weeks now for 4-8 hours a day and have yet to find a working code. Is it even possible? I mean, other websites use same page validation and submit to third party databases right?
I can provide more code if needed, but the problem seems to be here. If I don't try to change the return, the Captcha validates fine and the 'if (r.error == 0)' code executes fine. I have even added an alert to show the value of 'Submit' just to verify the data is transferring between the functions.
I'm at my wit's end here. I would appreciate any help.
Thanks,
Matt
The complete code (minus details) is as follows:
<?php
session_start(); // this MUST be called prior to any output including whitespaces and line breaks!
$GLOBALS['DEBUG_MODE'] = 1;
// CHANGE TO 0 TO TURN OFF DEBUG MODE
// IN DEBUG MODE, ONLY THE CAPTCHA CODE IS VALIDATED, AND NO EMAIL IS SENT
// EMAIL is edited out for school use
// Process the form, if it was submitted (Original Code called process_si_contact_form())
process_si_zoho1();
?>
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/prototype/1.7.0.0/prototype.js"></script>
<script type="text/javascript">
//variables not part of original code
function reloadCaptcha()
{
//original code ElementId labled 'captcha_code'
document.getElementById('captcha').src = '/securimage_show.php?sid=' + Math.random();
}
var r, Submit;
function processForm()
{
new Ajax.Request('<?php echo $_SERVER['PHP_SELF'] ?>', {
method: 'post',
//Original code did not state 'zoho1'
parameters: $('zoho1').serialize(),
onSuccess: function(transport) {
//Re-edited for school use. Not original code
try {
r = transport.responseText.evalJSON();
Submit = r.submit;
if (r.error == 0) {
alert('Congrats!');
reloadCaptcha();
} else {
alert("There was an error with your submission.\n\n" + r.message);
}
} catch(ex) {
alert("There was an error parsing the json");
}
},
onFailure: function(err) {
alert("Ajax request failed");
}
});
return false;
}
}
</script>
</head>
<body>
<form action="----------" id="zoho1" method="POST" name="leadForm" onsubmit="return processForm()">
<input name="----------" type="hidden" value="----------" />
<input name="----------" type="hidden" value="----------" />
<input name="----------" type="hidden" value="----------" />
<input name="----------" type="hidden" value="----------" />
<input name="----------" type="hidden" value="----------" />
<input name="----------" type="hidden" value="----------" />
<input type="hidden" name="do" value="contact" /><br />
<p>
<label for="First Name">First Name</label><br />
<input class="required" maxlength="40" name="First Name" type="text" /></p>
<p>
<label for="Last Name">Last Name</label><br />
<input class="required" maxlength="80" name="Last Name" type="text" /></p>
<p>
<label email="" for="">Email</label><br />
<input class="required validate-email" maxlength="100" name="Email" type="text" /></p>
<p>
<label for="Phone">Main Phone</label><br />
<input class="required" maxlength="30" name="Phone" type="text" /></p>
<p>
<label for="Mobile">Mobile Phone</label><br />
<input maxlength="30" name="Mobile" type="text" /></p>
<p>
<label for="State">State</label><br />
<select class="required validate-selection" name="State"><option selected="selected" value="-None-">-None-</option><option value="AL">AL</option><option value="AK">AK</option><option value="AZ">AZ</option><option value="AR">AR</option><option value="CA">CA</option><option value="CO">CO</option><option value="CT">CT</option><option value="DE">DE</option><option value="DC">DC</option><option value="FL">FL</option><option value="HI">HI</option><option value="ID">ID</option><option value="IL">IL</option><option value="IN">IN</option><option value="IA">IA</option><option value="KS">KS</option><option value="KY">KY</option><option value="LA">LA</option><option value="ME">ME</option><option value="MD">MD</option><option value="MA">MA</option><option value="MI">MI</option><option value="MN">MN</option><option value="MS">MS</option><option value="MO">MO</option><option value="MT">MT</option><option value="NE">NE</option><option value="NV">NV</option><option value="NH">NH</option><option value="NJ">NJ</option><option value="NM">NM</option><option value="NY">NY</option><option value="NC">NC</option><option value="ND">ND</option><option value="OH">OH</option><option value="OK">OK</option><option value="OR">OR</option><option value="PA">PA</option><option value="RI">RI</option><option value="SC">SC</option><option value="SD">SD</option><option value="TN">TN</option><option value="TX">TX</option><option value="UT">UT</option><option value="VT">VT</option><option value="VA">VA</option><option value="WA">WA</option><option value="WV">WV</option><option value="WI">WI</option><option value="WY">WY</option><option value="GA">GA</option></select></p>
<!--<div><label for="Mailing Zip">Mailing Zip</label><br /><input type="text" maxlength="30" name="Mailing Zip" /></div>--><!--<div><label for="Mailing Country">Mailing Country</label><br /><input type="text" maxlength="30" name="Mailing Country" /></div>-->
<p>
<label for="----------">----------</label><br />
<select class="required validate-selection" name="----------"><option selected="selected" value="-None-">-None-</option><option value="----------">----------</option><option value="----------">----------</option><option value="----------">----------</option><option value="----------">----------</option><option value="----------">----------</option><option value="----------">----------</option><option value="----------">----------</option><option value="----------">----------</option></select></p>
<p>
<label for="-------">----------</label><br />
<select class="required validate-selection" name="-------"><option selected="selected" value="-None-">-None-</option><option value="----------">----------</option><option value="----------">----------</option><option value="----------">----------</option><option value="----------">----------</option><option value="----------">----------</option><option value="----------">----------</option></select></p>
<p>
<label for="-------">------------</label><br />
<select class="required validate-selection" name="-------"><option selected="selected" value="-None-">-None-</option><option value="----------">----------</option><option value="----------">----------</option><option value="----------">----------</option><option value="---------">-----------</option></select></p>
<p>
<label for="-------">Intended Degree</label><br />
<select class="required validate-selection" name="-------"><option selected="selected" value="-None-">-None-</option><option value="--------------">-------------</option><option value="-------------">-------------</option><option value="-------------">--------------</option></select></p>
<p>
<label for="-------">How did you hear about TTU?</label><br />
<textarea class="required" height="250" maxlength="1000" name="-------" width="250"></textarea></p>
<p>
<label for="Description">Comments</label><br />
<textarea height="250" maxlength="1000" name="Description" width="250"></textarea></p>
<img id="captcha" src="/securimage_show.php" alt="CAPTCHA IMAGE" />
<input type="text" id="enterVerify" name="captcha_code" size="10" maxlength="6" />
<input type="button" id="reload" name="Reload" value="Reload" onClick="reloadCaptcha()">
<input class="form-button" name="save" type="submit" value="Submit" />
</form>
</body>
</html>
<?php
//Original code process called 'process_si_contact_form())
function process_si_zoho1()
{
if ($_SERVER['REQUEST_METHOD'] == 'POST' && #$_POST['do'] == 'contact') {
// if the form has been submitted
foreach($_POST as $key => $value) {
if (!is_array($key)) {
// sanitize the input data
if ($key != '-------') $value = strip_tags($value);
$_POST[$key] = htmlspecialchars(stripslashes(trim($value)));
}
}
$captcha = $_POST['captcha_code']; // the user's entry for the captcha code
$errors = array(); // initialize empty error array
if (sizeof($errors) == 0) {
require_once dirname(__FILE__) . '/securimage.php';
$securimage = new Securimage();
if ($securimage->check($captcha) == false) {
$errors['captcha_error'] = 'Incorrect security code entered';
}
}
if (sizeof($errors) == 0) {
// no errors, send the form
//Edited out mail function from original code
//Changed JSON return array on successful validation to send new variable '$Submit' via serialized $entry
$Submit = true;
$entry = array('error' => 0, 'submit' => $Submit);
die(json_encode($entry));
} else {
$errmsg = $captcha_error;
foreach($errors as $key => $error) {
// set up error messages to display with each field
$errmsg .= " - {$error}\n";
$Submit = false;
}
//Added $Submit to the return array
$return = array('error' => 1, 'message' => $errmsg, 'submit' => $Submit);
die(json_encode($return));
}
} // POST
} // function process_si_zoho1()
?>
<?php
if( isset( $_POST['captcha'] ))
{
$a = array("error"=>0);
print json_encode( $a );
exit();
}
?>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/prototype/1.7.1.0/prototype.js" ></script>
</head>
<body onload="processForm()">
<form id="formtest" action="" method="POST">
<input type="text" name="captcha" value="1vfvrfr">
</form>
<script>
var r, Submit;
function reloadCaptcha(){}
function processForm()
{
new Ajax.Request('<?php echo $_SERVER['PHP_SELF'] ?>', {
method: 'post',
//Original code did not state 'zoho1'
parameters: $('formtest').serialize(),
onSuccess: function(transport) {
//Re-edited for school use. Not original code
try {
r = transport.responseText.evalJSON();
Submit = r.submit
if (r.error == 0) {
alert('Congrats!');
reloadCaptcha();
} else {
alert("There was an error with your submission.\n\n" + r.message);
}
} catch(ex) {
alert("There was an error parsing the json");
}
},
onFailure: function(err) {
alert("Ajax request failed");
}
});
return Submit;
}
</script>
</body>
</html>
Thanks for all the help. I did some more research, the problem was in the JavaScript (my least experienced portion of code). I simply added to the:
if (r.error == 0)
document.forms['formname'].submit();
Thanks for the help guys! I'll definitely be using this forum again!
I am trying to do a submit form with photos. After the user loads the photos he presses the submit button, I want the form to pause for 10 seconds, animate a progress bar for those 10 seconds and then submit the form, can you guys say what I did wrong, it doesn't seem to submit the form after 10 seconds.
Here is the code:
HTML:
<form action="uploadpic.php" method="post" id="upload_form">
<input type="text" name="title" id="title">
<p id="title_p">Title</p>
<hr />
<input type="text" name="theme" id="picture_theme" size="40"/>
<p id="theme">Picture Theme<img src="../simages/info.gif" id="info" width="12" height="12" style="margin-left:10px;"></p>
<hr />
<div class="custom-upload">
<input type="file" name="picture" id="true_pic" />
<div class="fake-file">
<input disabled="disabled" >
</div>
</div>
<p id="upload_pic">Upload picture</p>
<input type="submit" name="submit" id="submit" value="Upload" />
</form>
JAVASCRIPT:
form = document.getElementById("upload_form");
size=1;
form.onsubmit = function()
{
if (size < 10)
{
setTimeout(delayedSubmit,1000);
}
return false;
}
function delayedSubmit() {
size++;
if (size<5)
{
setTimeout(delayedSubmit,1000);
alert("Counting "+size);
}
else
{
alert("Form submitted");
form.submit();
}
}
PHP :
<?php
if ($_POST['submit'])
{
$title = $_POST['title'];
$theme = $_POST['picture_theme'];
echo $title," ",$theme;
}
?>
I can tell that the form won't submit anything by the fact that the php variables won't show anything, and then page doesn't load.
When a form has a button with the name and/or id "submit", it won't work anymore (my old post was wrong).
So what you need to do is to change the name/id of the button:
<input type="submit" name="submit-button" id="submit-button" value="Upload" />
Remember: You need to change your PHP, too:
if ($_POST['submit'])
{
$title = $_POST['title'];
$theme = $_POST['picture_theme'];
echo $title," ",$theme;
}
to
if ($_POST['submit-button'])
{
$title = $_POST['title'];
$theme = $_POST['picture_theme'];
echo $title," ",$theme;
}
I'd simplify the javascript:
form = document.getElementById("upload_form");
size=0;
form.onsubmit = delayedSubmit;
function delayedSubmit () {
if (++size < 5) {
alert("Counting "+size);
setTimeout(delayedSubmit,1000);
return false;
}
alert("Form submitted");
form.submit();
}
And - of course - remove (or change) id and name from the submit button, e.g:
<input type="submit" value="Upload" />
e.g.: http://jsbin.com/equyit/1/edit
I wonder whether someone could help me please.
I've been looking through this, and many other sites and tutorials to find out how to add a button to a form which opens a PHP file, in this case, a pop up form that allows a user to upload a file to a mySQL database.
In addition to the opening of the file, I'd like to carry over the 'id' field value from the main form to the pop 'File Upload' form.
From the research I've carried out there seems to be a number of ways to do this, but from a beginners perspective I'm not sure what is the best way to do this.
Could someone perhaps please advise on what is the best way to go about this.
Many thanks and kind regards
To pass values between pages:
Main form:
<form action="myuploadform.php" method="get">
ID: <input type="text" name="id">
<input type="submit" value="Open Form">
</form>
The value of the ID text box will be accessible as $_GET['id'] in myuploadform.php.
Using GET parameters is the simplest way of passing values. Another way to pass in this GET value would be in the URL:
.../myuploadform.php?id=35 where the ID then becomes 35.
Here's a sample from my site. All it does is allow the uploading of files to the server. It should serve as a tutorial.
<html>
<head>
<script type="text/javascript">
var form_object = null;
var button_object = null;
function submit_form(obj)
{
form_object = obj.parentNode;
form_object.submit();
form_object.disabled = true;
button_object = obj;
button_object.disabled = true;
}
function enable_form()
{
form_object.disabled = false;
button_object.disabled = false;
}
function Add_HTML(html)
{
if(navigator.appName == 'Microsoft Internet Explorer')
{
document.body.insertAdjacentHTML('beforeEnd', html);
}
//Firefox uses the Netscape engine (the Netscape version that really sucked)
if(navigator.appName == 'Netscape' && parseInt(navigator.appVersion) == 5)
{
var freaky_object = document.createRange();
freaky_object.setStartBefore(document.body);
html = freaky_object.createContextualFragment(html);
document.body.appendChild(html);
}
}
</script>
</head>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data" target="upload">
<label>File:</label> <input type="file" name="file" />
<br />
<label>File:</label> <input type="file" name="swntic" />
<br />
<input type="button" value="SUBMIT"
onclick="submit_form(this);" />
</form>
<iframe src="about:blank" style="display:none;" id="upload" name="upload"></iframe>
</body>
</html>
server side code:
<?
$confirmation = "";
while(list($name) = each($HTTP_POST_FILES)) {
?>
<? if(is_uploaded_file($HTTP_POST_FILES[$name]["tmp_name"])) { ?>
<?= $HTTP_POST_FILES[$name]["name"] ?>
<br />
<?= $HTTP_POST_FILES[$name]["type"] ?>
<br />
<?= $HTTP_POST_FILES[$name]["tmp_name"] ?>
<br />
<?= $HTTP_POST_FILES[$name]["error"] ?>
<br />
<?= $HTTP_POST_FILES[$name]["size"] ?>
<br /><br />
<? } ?>
<?
if(is_uploaded_file($HTTP_POST_FILES[$name]["tmp_name"]))
{
move_uploaded_file($HTTP_POST_FILES[$name]["tmp_name"], "./uploads/" . $HTTP_POST_FILES[$name]["name"]);
chmod("./uploads/" . $HTTP_POST_FILES[$name]["name"], 0644);
$confirmation .= "<a href=\"./uploads/" . $HTTP_POST_FILES[$name]["name"] . "\">" .
$HTTP_POST_FILES[$name]["tmp_name"] . "</a> " . $HTTP_POST_FILES[$name]["type"] . ", " . $HTTP_POST_FILES[$name]["size"] . " bytes<br />";
}
}
?>
<html>
<script>
var confirmation = '<?= $confirmation ?>';
</script>
<body onload="parent.enable_form(); parent.Add_HTML(confirmation);">
</body>
</html>
It's not perfect, but can be used as a learning tool.
I am breaking my brain in this situation :)
I have a form:
<form method="post" action="">
<input type="hidden" name="entered_markers"
value="<script type='text/javascript'> document.getElementById('rout_markers').value; </script>" />
<input type="submit" value="Enter the trees you saw!" />
</p>
</form>
As you can see, the entered_markers tries to pass some JavaScript variables.
When I process the request, I do this
$chosen_markers = $_POST['entered_markers'];
Then the strange part :)
if ( empty ($chosen_markers) || !isset($chosen_markers) ) {
$errors[] = 'Please click on the map to select spots where you spotted these tree. Markers: '.$chosen_markers;
} else {
// Set something to signify that things are ok
}
And I always have the result that the validation thought the input was not empty, but when I tried to use that variable $rout_markers it just has nothing in it.
Where am I going wrong here? Isn't it sort of a strange thing that is happening? :)
Replace $rout_markers with $chosen_markers
Try it by creating a JavaScript function within your head and pass the form as the parameter to parse it's input fields. I went on and created a dummy text field name "rout_markers" and gave it a value of 300. So, on your PHP side if you look for $_POST['entered_markers'] it would echo out to be 300 if you use the example below:
<html>
<head>
<script type='text/javascript'>
function submitCoor(form){
form['entered_markers'].value = document.getElementById('rout_markers').value;
}
</script>
</head>
<body>
<input type='text' value='300' id='rout_markers' />
<form method="post" action="test.php" onsubmit="submitCoor(this)">
<input type="hidden" name="entered_markers"
value="" />
<input type="submit" value="Enter the trees you saw!" />
</form>
</body>
</html>
Try this:
<form method="post" action="" onsubmit="document.getElementById('entered_markers').value = document.getElementById('rout_markers').value;">
<p>
<input type="hidden" name="entered_markers" id="entered_markers" value="" />
<input type="submit" value="Enter the trees you saw!" />
</p>
</form>
Edit: and replace $rout_markers with $chosen_markers as suggested by webarto.
The code below will probably explain what you could be doing wrong.
$errors = array();
if (
isset($_POST['entered_markers']) // make sure the variable is available
) {
if (
is_string($_POST['entered_markers']) // make sure the data type is string (could be array when form is manipulated)
) {
$markers = trim($_POST['entered_markers']); // trim whitespace and store it in a var
if ($markers !== "") { // if the string is NOT empty
echo "Input given!";
// At this point you could add some more validation to check whether the given input is also what you expect it to be.
// Preform a regexp for lat/lng for example.
echo $markers;
} else {
$errors[] = "Parameter 'entered_markers' is empty.";
}
} else {
$errors[] = "Parameter 'entered_markers' is not a string.";
}
} else {
$errors[] = "Parameter 'entered_markers' is not found.";
}
print_r($errors);
Here's what I have:
<html>
<head>
<?php
$validForm = false;
function getValue($field){
if(isset($_GET[$field])){
return $_GET[$field];
}
else{
return "";
}
}
function validateForm(){
//magic goes here.
}
?>
</head>
<body>
<?php if($validForm == false){ ?>
<form action="class2.php" method="get">
<dl>
<dt>First Name:</dt>
<dd><input type="text" value="<?php echo htmlspecialchars(getValue('name')) ?>" name="name" />
</dd>
<dt>Last Name:</dt>
<dd><input type="text" value="<?php echo htmlspecialchars(getValue('lastname')) ?>" name="lastname" />
</dd>
<br />
<dt>
<input type="submit" value="enviar" />
</dt>
</dl>
</form>
<?php
} else {
?>
<h1>Congratulations, you succesfully filled out the form!</h1>
<?php }
?>
</body>
Where would I put the validateForm() call? I'm not sure.
What I want is to continue showing the form until the $validForm variable is true. :)
Thank you SO you always help me out.
function validateForm(){
if ( ) // Your form conditions go here
{
return true;
} else {
return false;
}
}
if ( $_GET ) // Only validate the form if it was submitted
{
$validForm = validateForm();
} else {
$validForm = false;
}
Examples for some conditions:
if ( !empty ( $_GET[ 'name' ] ) and !empty ( $_GET[ 'lastname' ] ) ) // Check if the user entered something in both fields
I can only recommend you to change your getValue function too.
It would be a good idea to change
return $_GET[$field];
to something like
return htmlspecialchars ( trim ( $_GET[$field] ) );
This will remove unnecessary whitespace and escape the output at once.
The next or probably first step you should take would be to change your form from GET to POST as it is, in most cases, a bad idea to send form data via GET.
You have to add a name to your submit button :
<input type="submit" value="enviar" name="validate" />
And after the declaration of validateForm
you put
if(getValue("validate") != "")
validateForm();
I'd check for the $_POST-variables in your getValue-function as you're trying to validate form-data (your checking $_GET-variables which is data submitted through the URL), you also may want to add "trim"
give the submit-button an id and check if the form has beed submitted that way
e.g. <input type="submit" value="enviar" id="submitButton" />
setting $validForm would look this this: $validForm = validateForm(); (instead of "$validForm = false;")
your validateForm-function should then check whether "$_POST["submitButton"]" is set and if your data is valid (set, right type, etc. etc.), if all of that is ok, return "true", otherwise "false"
<html>
<head>
<?php
$validForm = validateForm();
C.