Undefined index in php? - php

I am trying to get the value from a textbox in another page I created and the textbox is automatically set to 0 but it keeps on telling me that the index is undefined? but once you click the confirm button the value gets submitted but I want it to automatically set as 0 without having to click the button.
This is page1:
<?php
if(isset($_POST['topscart']))
{
$_SESSION['topscart']=$_POST['topscart'];
print"<script language=javascript>
window.location='ACCOUNT.php';
</script>";
}
?>
This is page 2:
<td>No. of Female Tops Ordered: </td>
<td><center><?php
print" ".$_SESSION['topscart'];
?>
</td>
Textbox Code in page 1:
No. of Female Tops in Your Cart: <input type="text" value="0" size="10" name="topscart" id="topscart" >
Total: <input text="text" size="10" value="0" name="topstotal" id="topstotal" >
<input type ="submit" value="Confirm Order"></button>
<input type ="reset" id="topsbutton2" name="topsbutton2" value="Cancel Order"></button>
</center>

I couldn't quite understand the purpose but you must click the button to populate the $_POST variable.
If you must, set the value to 0 and automatically get it in $_POST then you need to use JS also - on page load fill-up the "topscart" with 0, and use .click() of the button.
Hope this helps

<?php
if(isset($_POST['topscart']))
{
session_start();
$_SESSION["topscart"] = $_POST['topscart'];
print"<script language=javascript>
window.location='ACCOUNT.php';
</script>";
}
?>
2nd page
<?php
session_start();
echo $_SESSION["topscart"];
?>

I think you want to default the session value to 0 unless it is set by the initial form? If that is the case then update the code on page 1 to:
<?php
if(isset($_POST['topscart']))
{
$_SESSION['topscart']=$_POST['topscart'];
print"<script language=javascript>
window.location='ACCOUNT.php';
</script>";
} else {
$_SESSION['topscart'] = 0;
}

Related

How to send the PHP value back to the HTML form?

I've been trying to build a program using PHP cookies. The user interface basically looks like this.
My basic program
The logic is this. When the user enters the product name, price and quantity and clicks on the "Add" button, the total value which is price*quantity will fall on the "Total bill value" textbox. The user can go on adding more and more values for "Price" and "Quantity" and each time he clicks on "Add", all the values get added. So this should be done by using cookies. The "Clear" button will reset the cookie, and the "Print" button will also be using the same cookie to print out everything the user has entered upto that point.
Anyways I just started coding, and I'm already stuck. I'm not sure what my mistake is. When I click on the "Add" button, the value doesn't get added every time I enter a price and quantity. Instead the page refreshes to give only the product of the price and quantity entered at one time. This is my code.
`
<form method="POST" >
<ul style="list-style-type:none;">
<li>
Product Name: <input type="text" name="ProductName"> <br>
Price: <input type="number" name="Price" value="price"> <br>
Quantity: <input type="number" name="Quantity" value="qty"><br>
<input type="submit" name="btnClick" value="Add">
<input type="submit" name="btnReset" value="Clear">
<input type="submit" name="btnPrint" value="Print"><br>
Total Bill Value: <input type="text" name="Bill">
</li>
</ul>
</form>
<?php
if($_SERVER["REQUEST_METHOD"] == "POST")
{
$result=0;
if(isset($_POST["btnReset"]))
{
setCookie("result", $result);
}
elseif(isset($_POST["btnClick"]))
{
if(isset($_COOKIE["result"]))
{
$result=$_COOKIE["result"];
}
$result= $_POST["Price"]*$_POST["Quantity"];
echo $result;
setCookie("result", $result);
}
else
{
echo "Product: ".$_POST["ProductName"];
echo "Price: ".$_POST["Price"];
echo "Quantity: ".$_POST["Quantity"];
}
}
?>
</body>
`
I'm sure that this is a stupid mistake I'm struggling on. However I am an absolute beginner and would so appreciate if somebody could point out my mistake and explain it to me.
So there are two things I want to know mainly:
Why is my cookie not being set when the Add button is clicked?
How to put the value calculated in PHP back to the html form, so that the "Total Bill Value" textbox will have the total value?
Thanks in advance!
Edit: I did figure out my mistake. I should have put $result=$result + $_POST["Price"]*$_POST["Quantity"];
Then the values get added up.
However would like to know how to put the total bill value calculated in PHP back to the HTML form
You should call setcookie() before you output any HTML, so move the PHP code above the rest.
To set the form input:
<?php
if (isset($result)) {
$bill = $result;
} else {
$bill = '';
}
?>
Total Bill Value: <input type="text" name="Bill" value="<?php echo $bill; ?>">
please use setcookie instead of setCookie
This will work
Happy Coding

Ignoring initial loading of PHP_SELF

I am learning PHP and I have a page that reloads back to itself. I want to know if you can ignore a certain function on the initial loading of the page and only call it once the form submit button has been clicked.
The page is passed a 'ticketID' and loads the information from it. I then want to be able to add a note using the following form method:
<form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<strong>Add Note:</strong>
<textarea name="note" rows="5" cols="40" value=><?php echo htmlspecialchars($note);?></textarea>
<span class="error">*<?php echo $noteErr;?></span><br>
The user then clicks on a submit button to submit the note for processing:
<button type='submit' name='ticketID' value= <?php echo $_POST['ticketID'];?> >View</button>
</form>
The 'ticketID' is then passed back to the page to reload the information.
If the submit button is pressed and no note has been entered I want a message box to display informing the user to include a note. I have tried:
if (!empty($_POST["note"]))
{
echo "This has updated...";
} else {
echo "Missing!";
}
However this loads the error message even on the initial load of the page. I have tried setting a variable to the POST ticketID value and clearing the POST value after the page has displayed and before testing for the error message:
$tempTicketID = $_POST['ticketID'];
$_POST['ticketID'] = NULL;
Then testing the error message, and finally setting the POS value back before the page ends to allow it to reload correctly again:
$_POST['ticketID'] = $tempTicketID;
However the POST value doesn't save and the page reloads with no information.
Any help would be great appreciated.
Here's the full code layout:
##LOAD THE PAGE INFO...
#Set the temp variable and clear the post value
$tempTicketID = $_POST['ticketID'];
$_POST['ticketID'] = NULL;
#Load the form
<form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<strong>Add Note:</strong>
<textarea name="note" rows="5" cols="40" value=><?php echo htmlspecialchars($note);?></textarea>
<span class="error">*<?php echo $noteErr;?></span><br>
<button type='submit' name='ticketID' value= <?php echo $_POST['ticketID'];?> >View</button>
</form>
#Test if the note is empty and the form button has been pressed
if (!empty($_POST["note"]))
{
echo "This has updated...";
} elseif (empty($_POST["ticketID"] {
echo "Missing!";
}
#Set POST value back to reload the page
$_POST['ticketID'] = $tempTicketID;
We need to restructure the form just a bit to make this happen. You can check if the form is submitted by testing for the button that must be clicked to submit. However, you're using that button for multiple purposes. To simplify, we'll have a separate submit button, and pass the ticketID value through the form with a hidden input. You shouldn't need the code that unsets the $_POST values.
<button type='submit' name='submit'> View</button>
<input type='hidden' name='ticketID' value= <?php echo $_POST['ticketID'];?> />
Then you can test if the form has been submitted with this quick check:
if (isset($_POST['submit'])) {
if (!empty($_POST["note"]))
{
echo "This has updated...";
} else {
echo "Missing!";
}
}

Session variable not working

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

How do I make a button appear after inputting text in an HTML form?

I'm coding an HTML form where I've implemented an anti-spam system where two random numbers are generated and the user is asked to input the sum into a text field. If the answer is right, then the 'submit' button appears and the user can move on. If the answer is incorrect, then a notification saying, 'Incorrect answer'. The HTML form itself is in a table. In the very last row of cells I've put this code in:
<td>
<?php
$firstnumber = rand(0, 5);
$secondnumber = rand(0,6);
echo 'Anti-spam: '.$firstnumber.' + '.$secondnumber.' = ?</td><td><input name="human" placeholder = "Do the math">';
?>
</td>
<tr>
<td colspan="2">
By submitting this form you are agreeing to the terms of service and agreements.<br><br>
<?php
$answer = $_POST['human'];
if($answer == $firstnumber + $secondnumber) {
echo '<input id="submit" name="submit" type="submit" value="I Agree"> <input id="reset" name="reset" type="reset" value="Reset">'; }
else {
echo '<font color=#ea596c>Incorrect answer</font>';
?>
</td>
But the 'submit' button won't reappear when the answer is entered into the box :(
option 1 (not too secure) add hidden input with correct answer
<input type="hidden" name="answer" value="<?=$firstnumber+$secondnumber;?"/>
and check the data after submit
if($_POST["anwer"]==$_POST["human"]) ...
option 2 remember the correct answer with SESSION. If you want to do server side check, you must display submit button - the data must be sent to the server. To display/hide the submit button, you must do client side check and use javascript, see option 3.
<?
session_start(); // necessary to use session vars
$firstnumber = rand(0, 5);
$secondnumber = rand(0, 6);
if(!empty($_SESSION["answer"]) && $_SESSION["answer"]==#$_POST["human"]) {
// the math was ok
}
$_SESSION["answer"] = $firstnumber + $secondnumber; // must be AFTER the check
?>
<form method="post">
<?="$firstnumber + $secondnumber = ";?>
<input name="human" type="text" placeholder="do the math"/>
<input type="submit"/> <!-- can't be hidden without javascript -->
</form>
option 3 client side javascript solution, something like vasiljevski recommend
<span id="first"></span> + <span id="first"></span>
<input oninput="check(this)" placeholder="do the math"/>
<input type="submit" id="submit" style="display: none"/>
<script>
var first=Math.floor(Math.random()*10);
var second=Math.floor(Math.random()*10);
var gid = document.getElementById.bind(document);
gid("first").innerHTML = first;
gid("second").innerHTML = second;
function check(input) {
gid("submit").style.display = input.value==first+second ? "inline" : "none";
}
</script>
You would need to add some JavaScript to your form to achieve that.
Add a keypress event on input and check if entry is valid.
<input id="antispam" name="human" onkeyup="checkEntry" placeholder = "Do the math">';
?>
<script>
function checkEntry()
{
var x=document.getElementById("antispam");
if (x=={correct answare})
{
[add submite button]
}
else
{
[add incorrect text]
}
</script>
You are generating new random numbers on every page load. So when the user is doing the math and submitting the form, it happens a new request and your random numbers are generated new, so the calculation cannot match (randomly it could be the same result).
You have to store the math result in session or an hidden input field (encoded or something else) that you know the result after submitting the form.
Or you want to check the result in JavaScript to show the button, but I wouldn't do an humanity check on the client.

Null textbox then Redirect

So i have a form method post in index.php where in it will send the data from a textbox to another page which is print.php.
now what i want to do is if the textbox from index.php is null it wont redirect to print.php or if it redirect to print.php it will be redirected back to index.php.
index.php format
<form action="print.php" method="post" target="_blank">
<input type="text" name="faidf" id="faidf" size="25" value="" maxlength="25"/></td>
<input type ="submit" value="Print">
print.php
<?php
$faidf = $_POST['faidf'];
if(isset($_POST['faidf'])) {
echo "<td><font size=2>FAID:$faidf</td><td></font></td>";
}
else {
echo "FAID is missing";
}
?>
instead of FAID is missing could i redirect it home because i have about 10more php wherein it needs the variable of $faidf so the whole printd.php is utterly useless if the textbox is blank.thanks
You can do this by two ways:
Way 1:
Use JQuery/JavaScript for the form validation process onsubmit of the form. It will redirect only in case where there is data found in textbox.
Way 2:
Check the length of provided post data and if the length is less than 1 return it to the previous page.
I will advice you to use the JavaScript/JQuery as it will run on all cross browsers and easy to implementation and changed easyly
first add onchange function to your textbox
<input type="text" onchange="myFunction(this)" name="faidf" id="faidf" size="25" value="" maxlength="25"/>
and add an Id for the button
<input type ="submit" value="Print" id="btn" />
and add script tag in your page :
function myFunction(e)
{
var x=document.getElementById("btn");
if (e.value == ''){
x.setAttribute('disabled','disabled');
}else{
x.removeAttribute('disabled');
}
}
and instead of your echo at print.php add location header
header("Location: index.php");

Categories