I have a form which submits data, and as a test I am attempting to first check if a variable is set on submit. If the variable is set, a text will be displayed stating something like "Variable is set". However if it isn't set, a text will be displayed saying "variable not set", once the variable hasn't been set it should then be set so next time when the form is submitted it displays variable is set however this is not working for me, for some reason it always displays that the variable is not set, my PHP code will be below:
<?php
if (isset($test)) {
echo "This var is set";
}
if (!isset($test)) {
echo "This var is not set";
$test = 'set';
}
?>
<form action="" method="post">
<input type="text" id="text" name="text" autocomplete="off"><br><br>
<input type="submit" value="submit">
</form>
I feel really stupid for not being able to do something which seems so easy, I am only just learning and sort of trying to teach myself, thank you for any help provided!!!
Working code and explanation:
<?php
$test="";
if (isset($_POST["text"])) { //always directly check $_POST,$_GET var without assigning
echo "This var is set";
$test=$_POST["text"]; // then assign
}
else{ // and use else clause for otherwise case
echo "This var is not set";
$test = 'set'; // AND if you want set to default/custom value in case of not set.
}
?>
<form action="" method="post">
<input type="text" id="text" name="text" autocomplete="off">
<br /><br />
<input type="submit" value="submit">
</form>
If you are using form to submit values, then try this one,
if (isset($_POST['text'])) {
echo "This var is set";
}
if (!isset($_POST['text'])) {
echo "This var is not set";
$test = 'set';
}
Otherwise, If a variable set to empty value like $test = '';
(It means variable is set but it has no values) It will execute your first if condition only.
<?php
$test=$_GET["text"];
if (isset($test)) {
echo "This var is set";
}
if (!isset($test)) {
echo "This var is not set";
$test = 'set';
}
?>
<form action="#" method="get">
<input type="text" id="text" name="text" autocomplete="off"><br><br>
<input type="submit" value="submit">
</form>
You haven't declared the variable $test.
Unless you've still got a bit of PHP somewhere that you haven't included here, your variable is empty. When a form is submitted, the input will be added to either the $_POST array (for method = "post") or else the $_GET array (for method = "get").
To Fix:
<?php
if (isset($_POST['text'])) {
$test = $_POST['text'];
echo "This var is set";
}
if (!isset($_POST['text'])) {
echo "This var is not set";
$test = 'set';
}
?>
<form action="" method="post">
<input type="text" id="text" name="text" autocomplete="off"><br><br>
<input type="submit" value="submit">
</form>
Related
I want to use this code for a barcode scanner as follows:
The scanned barcode is entered in the insert_code input and then I want to display "code is ok", when the value in search_code = insert_code.
My code, after validation, clears the input search_code and it is annoying to have to reintroduce the same code in search_code every time again.
What can I do to keep the value in search_code after each validation?
<form action="" method="post">
Cod I:<input type="text" name="search_code" value=""/><br/><br/>
Cod II:<input type="" name="insert_code" value=""/><br/><br/>
<input type="submit" name="button" value="validation" />
</form>
<?php
$search_code = $_POST ["search_code"];
$insert_code = $_POST ["insert_code"];
if ($search_code == $insert_code){
echo "code is ok";
} else {
echo "code is not ok";
}
?>
If you want to keep search_code input filled with the last submitted value, just echo the value of this post into the input if it was set:
<form action="" method="post">
Cod I:<input type="text" name="search_code" value="<?php echo isset($_POST['search_code'])?$_POST['search_code']:'' ?>"/><br/><br/>
Cod II:<input type="" name="insert_code" value=""/><br/><br/>
<input type="submit" name="button" value="validation" />
</form>
Also, to avoid warnings about undefined index, add this condition to your PHP code (check if those posts are set):
<?php
if(isset($_POST ["search_code"]) && isset($_POST ["insert_code"])){
$search_code = $_POST ["search_code"];
$insert_code = $_POST ["insert_code"];
if ($search_code == $insert_code){
echo "code is ok";
}else {
echo "code is not ok";
}
}
?>
You can do this without PHP, which will give a better user-experience. Here is a live example, just run to see it work:
// identify form elements:
var search_code = document.getElementById('search_code');
var insert_code = document.getElementById('insert_code');
var result = document.getElementById('result');
var button = document.getElementById('button');
// respond to button click
button.onclick = function validate() {
// show verification result:
result.textContent = search_code.value == insert_code.value
? 'code is ok'
: 'code is not ok';
// clear input when wrong:
if (search_code.value !== insert_code.value) {
insert_code.value = '';
}
return false;
};
insert_code.oninput = function () {
result.textContent = ''; // clear result;
};
<form action="" method="post">
Cod I:<input type="text" name="search_code" id="search_code" value=""/><br/><br/>
Cod II:<input type="" name="insert_code" id="insert_code" value=""/><br/><br/>
<input type="submit" id="button" name="button" value="validation" />
</form>
<div id="result"></div>
The test is done in Javascript, which responds to the button click and cancels the form's submission to the server (return false).
As a bonus the "ok/not ok" message is cleared as soon as you type a new value in the second input box.
How to use this code
Here is how the code should look in your document:
<body>
<form action="" method="post">
Cod I:<input type="text" name="search_code" id="search_code" value=""/><br/><br/>
Cod II:<input type="" name="insert_code" id="insert_code" value=""/><br/><br/>
<input type="submit" id="button" name="button" value="validation" />
</form>
<div id="result"></div>
<script>
// identify form elements:
var search_code = document.getElementById('search_code');
var insert_code = document.getElementById('insert_code');
var result = document.getElementById('result');
var button = document.getElementById('button');
// respond to button click
button.onclick = function validate() {
// show verification result:
result.textContent = search_code.value == insert_code.value
? 'code is ok'
: 'code is not ok';
// clear input when wrong:
if (search_code.value !== insert_code.value) {
insert_code.value = '';
}
return false;
};
insert_code.oninput = function () {
result.textContent = ''; // clear result;
};
</script>
</body>
Note that the content part has some differences to yours: every input has an id attribute, and there is an extra div.
I'm learning PHP and trying to understand the if .. else statements a little better, so I'm creating a little quiz. However, I have come across an issue and I don't seem to know what the issue is. My problem is that whenever I type in the age in the input area, it will give me the $yes variable every time even if I enter the wrong age.
Here is my code so far:
My html file:
<form action="questions.php" method="post">
<p>How old is Kenny?<input></input>
<input type="submit" name="age" value="Submit"/>
</p></form>
My php file:
<?php
$age = 25;
$yes = "Awesome! Congrats!";
$no = "haha try again";
if ($age == 25){
echo "$yes";
}else{
echo "$no";
}
?>
You catch the user input inside the $_POST superglobal var (because the method of your form is POST.
So
<?php
$age = 25;
should be
<?php
$age = $_POST['age'];
There is an error in HTML too. This
<input type="submit" name="age" value="Submit"/>
should be
<input type="text" name="age" value=""/>
<input type="submit" value="Click to submit"/>
Because you want one input and one button. So one html element for each element.
and <input></input> must be cleared because it's not valid syntax :-)
<form action="questions.php" method="post">
<p>How old is Kenny?</p><input type="text" name="age"></input>
<input type="submit" value="Submit"/>
</form>
$age = (int) $_POST["age"];
$yes = "Awesome! Congrats!";
$no = "haha try again";
if ($age == 25) {
echo $yes;
} else {
echo $no;
}
<?php
/* Test that the request is made via POST and that the age has been submitted too */
if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['age'] ) ){
/*
ensure the age is an integer rather than a string ..
though for this not overly important
*/
$age=intval( $_POST['age'] );
if( $age==25 ) echo "Congratulations";
else echo "Bad luck!";
}
?>
<form action="questions.php" method="post">
<p>How old is Kenny?
<input type='text' name='age' placeholder='eg: 16' />
<input type="submit" value="Submit" />
</p>
</form>
A simple html form, note that the submit button does not carry the values you want to process, they are supplied via the input text element.
First of all, you need to echo the variable; echoing "$no" will keep it as a string. Remove the quotes from "$no" and "$yes" in your if then statement. Otherwise, your code seems sound!
I am using one session variable in my php page. As per my infomation, it is accessible throughout the program and it is, but problem is that it is showing different value for the same variable at different place in php page?
the code is as follows
<html><body>
<?php session_start();
if(!isset($_SESSION['x']))
$_SESSION['x']=1;
echo "X=". $_SESSION['x'];
?>
<form>
<input type="submit" name="save" value="save" />
</form>
<?php
if (isset($_GET['save']))
{
if(isset($_SESSION['x']))
$_SESSION['x'] = $_SESSION['x']+1;
echo $_SESSION['x']."<br>";
}
else
echo "no submit";
?>
</body></html>
value becomes different before and after submit button click? Please tell me why it is so?
thanks in advavnce.
You are redeclaring the value of session variable 'x' here
$_SESSION['x'] = $_SESSION['x']+1;
This is why its appearing 1 greater than its initial value.
it is due to the code itself
if(isset($_SESSION['x'])) //It is set
$_SESSION['x'] = $_SESSION['x']+1; //Add 1 to the value
echo $_SESSION['x']."<br>"; return value with +1
Solution
The reason the output is different is the order you echo and update
//Echo
//Update Value
//Echo again
Simple solution would be to move this
if (isset($_GET['save']))
{
if(isset($_SESSION['x']))
$_SESSION['x'] = $_SESSION['x']+1;
echo $_SESSION['x']."<br>";
}
else
echo "no submit";
to above this
if(!isset($_SESSION['x']))
$_SESSION['x']=1;
echo "X=". $_SESSION['x'];
Also note set the method and the action in the form to make sure it calls itself
<form method="GET" action="[url to itself]">
<input type="submit" name="save" value="save" />
</form>
Do it like this :
<html><body>
<?php session_start();
if(!isset($_SESSION['x']))
$_SESSION['x']=1;
echo "X=". $_SESSION['x'];
?>
<form method="GET" action="">
<input type="submit" name="save" value="save" />
</form>
<?php
if (isset($_GET['save']))
{
if(isset($_SESSION['x']))
echo $_SESSION['x']."<br>";
}
else
echo "no submit";
?>
</body></html>
this way the code prints out the same value after submit as it did before.
Either way you try if you print value and change after or change value and print after, when page reloads it will change value. you could add another button called increment and add the following code inside the php :
if (isset($_GET['inc']))
{
if(isset($_SESSION['x']))
$_SESSION['x'] = $_SESSION['x']+1;
}
and this one inside the form:
<input type="submit" name="inc" value="inc" />
this way youre variable increment when you press the inc button
I have a input field as follows:
<input type="text" name="subject" id="subject" value="Car Loan">
I would like to get the input fields value Car Loan and assign it to a session. How do I do this using PHP or jQuery?
Use PHP's $_POST or $_GET superglobals to retrieve the value of the input tag via the name of the HTML tag.
For Example, change the method in your form and then echo out the value by the name of the input:
Using $_GET method:
<form name="form" action="" method="get">
<input type="text" name="subject" id="subject" value="Car Loan">
</form>
To show the value:
<?php echo $_GET['subject']; ?>
Using $_POST method:
<form name="form" action="" method="post">
<input type="text" name="subject" id="subject" value="Car Loan">
</form>
To show the value:
<?php echo $_POST['subject']; ?>
Example of using PHP to get a value from a form:
Put this in foobar.php:
<html>
<body>
<form action="foobar_submit.php" method="post">
<input name="my_html_input_tag" value="PILLS HERE"/>
<input type="submit" name="my_form_submit_button"
value="Click here for penguins"/>
</form>
</body>
</html>
Read the above code so you understand what it is doing:
"foobar.php is an HTML document containing an HTML form. When the user presses the submit button inside the form, the form's action property is run: foobar_submit.php. The form will be submitted as a POST request. Inside the form is an input tag with the name "my_html_input_tag". It's default value is "PILLS HERE". That causes a text box to appear with text: 'PILLS HERE' on the browser. To the right is a submit button, when you click it, the browser url changes to foobar_submit.php and the below code is run.
Put this code in foobar_submit.php in the same directory as foobar.php:
<?php
echo $_POST['my_html_input_tag'];
echo "<br><br>";
print_r($_POST);
?>
Read the above code so you know what its doing:
The HTML form from above populated the $_POST superglobal with key/value pairs representing the html elements inside the form. The echo prints out the value by key: 'my_html_input_tag'. If the key is found, which it is, its value is returned: "PILLS HERE".
Then print_r prints out all the keys and values from $_POST so you can peek as to what else is in there.
The value of the input tag with name=my_html_input_tag was put into the $_POST and you retrieved it inside another PHP file.
You can get the value $value as :
$value = $_POST['subject'];
or:
$value = $_GET['subject']; ,depending upon the form method used.
session_start();
$_SESSION['subject'] = $value;
the value is assigned to session variable subject.
For global use, you may use:
$val = $_REQUEST['subject'];
and to add yo your session, simply
session_start();
$_SESSION['subject'] = $val;
And you dont need jQuery in this case.
function get_input_tags($html)
{
$post_data = array();
// a new dom object
$dom = new DomDocument;
//load the html into the object
$dom->loadHTML($html);
//discard white space
$dom->preserveWhiteSpace = false;
//all input tags as a list
$input_tags = $dom->getElementsByTagName('input');
//get all rows from the table
for ($i = 0; $i < $input_tags->length; $i++)
{
if( is_object($input_tags->item($i)) )
{
$name = $value = '';
$name_o = $input_tags->item($i)->attributes->getNamedItem('name');
if(is_object($name_o))
{
$name = $name_o->value;
$value_o = $input_tags->item($i)->attributes->getNamedItem('value');
if(is_object($value_o))
{
$value = $input_tags->item($i)->attributes->getNamedItem('value')->value;
}
$post_data[$name] = $value;
}
}
}
return $post_data;
}
error_reporting(~E_WARNING);
$html = file_get_contents("https://accounts.google.com/ServiceLoginAuth");
print_r(get_input_tags($html));
If its a get request use, $_GET['subject'] or if its a post request use, $_POST['subject']
<form action="" method="post">
<input type="text" name="subject" id="subject" value="Car Loan">
<button type="submit" name="ok">OK</button>
</form>
<?php
if(isset($_POST['ok'])){
echo $_POST['subject'];
}
?>
I need to validate an empty field with php and javascript, but both of the methods fail.
<form method="POST" name="contact_form"
action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>">
<input type="text" name="pickupaddress" value="<?
if($pickupaddress == ''){
echo "";}
else{echo htmlentities($pickupaddress);}?> " id="pickupaddress"/>
<input type ="submit" name="submit" value"Reserve"/>
</form>
//////// Php validation DOES NOT WORK////////
$pickupaddress ='';
$err ='';
$pickupaddress = $_POST['pickupaddress'];
if($pickupaddress == ''){ //if empty field, I also tried == ""
$err.="Please provide pick up address.";
}
///// Javascript validation does not work.
if(form.pickupaddress ==""){
alert("empty address!");
}
//when I click submit nothing happens.
//I am thinking the problem is with
htmlentities($pickupaddress);
//Thanks for your help.
Here is hopefully simpler answer:
$pickupaddress = trim($_POST['pickupaddress']); //trims the string
if (empty($pickupaddress)){ //if empty field
$err.="Please provide pick up address.";
}
On the php side you can try trimming the value and then using empty() on the next line, though that will also invalidate 0, false, null, and other such values. Or you can try using isset.
For the javascript side you can try this function:
function IsEmpty(aTextField) {
if ((aTextField.value.length==0) ||
(aTextField.value==null)) {
return true;
}
else { return false; }
}
found here: http://www.codetoad.com/javascript/isempty.asp
$cid = $_POST['category'];
if (!empty($_POST['category']))
{
echo "<script>alert('empty field');</script>";
}
Where are you defining pickupaddress? Is it before the form or after? If the variable isn't defined, and depending on your server configuration, the value field of the input could be
Notice: undefined variable pickupaddress
Thus making the value != ''.
View your page source to ensure that the value is indeed empty.
there was a spave " " in your string: echo htmlentities($pickupaddress);}?> "
maybe that was the reason, because it was not an empty string but it was a space?
<form method="POST" name="contact_form"
action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>">
<input type="text" name="pickupaddress" value="<?
if($pickupaddress != '') {
echo htmlentities($pickupaddress);
}?>" id="pickupaddress"/>
<input type ="submit" name="submit" value"Reserve"/>
</form>
and i guess you might want to have checked if the post value is set:
if(isset($_POST['pickupaddress'])) {
$pickupaddress = $_POST['pickupaddress'];
}
the php way works for me like that ;) (the message is displayed if i dont write anything)