Initialise a html input text field from a php variable - php

I'm a beginner to web programming and need help with html input field initialisation from a php variable. I have one php file with a table with input fields and buttons etc. javascript and jquery is used to handle the processing. Now I want to get data from a server which will be stored in php variables. This is a code extract:
<body>
<php?
$voltage = "012";
// $_POST['voltage']; // tried this
?>
<table>
<td><input name="GETVOLTS_textfield" type="text" id="GETVOLTS_textfield" value="<?php echo $_POST['voltage'];?>" size="3" maxlength="3" />
%</td>
</table>
</body>
I get a message Undefined index : voltage
At this stage I am working with XAMPP localhost and don't have any database, I need to be able to handle the variables locally before worrying about the DB.
Any help would be much appreciated.

Try isset()
<input name="GETVOLTS_textfield" type="text" id="GETVOLTS_textfield" value="<?php echo isset($_POST['voltage'])?$_POST['voltage']:'';?>" size="3" maxlength="3" />

if you want to use the variable $voltage your code should look like this:
<input name="GETVOLTS_textfield" type="text" id="GETVOLTS_textfield" value="<?php echo $voltage; ?>" size="3" maxlength="3" />
you can set $voltage with a specific posted var
$voltage = $_POST['voltage'];
but you should test if your variable $_POST['voltage'] is set, because you will get your mentioned error if nothing or just this variable is not posted
you can do this with isset
if(isset($_POST['voltage'])
{
$voltage = $_POST['voltage'];
}
else
{
$voltage = '';
}

I get a message Undefined index : voltage
Was there a voltage value posted in the form? There's an order of events taking place here. First your server-side code executes, then the page renders, then the user posts the form value to server-side code. So if in the first step you're looking for a form value:
$_POST['voltage'];
That value isn't going to be there because the user hasn't posted it yet. You can test for the value before trying to use it:
if (isset($_POST['voltage'])) {
// the value exists
}
This is commonly used when the same page (and, thus, the same server-side code) is used for both creating the form and handling the posted form. If that's the case for you then you'll need to include such conditionals because the server-side code can't use form values that aren't posted yet.

Just use $voltage. The $_POST array will only have values in it if a form submitted values to your script.

<td><input name="GETVOLTS_textfield" type="text" id="GETVOLTS_textfield" value="<?php echo $voltage;?>" size="3" maxlength="3" />

1) May-be you should consider doing : (despite it's not recommanded, that's what you're trying to do)
$voltage = "012";
$_POST['voltage'] = $voltage;
2) You don't need $_POST variables. Just echo $voltage !

Related

PHP Undefined Variable, but it's defined and has a value

I am working on a PHP project - I had one form post a date to another form
I made some changes (although none to the input in question)
Now all other inputs are updated with their Posted values, except the date
If I manually set the date in HTML it works:
<div><input type="date" class="form-control" id="DateCourse" name="DateCourse" value="2009-01-01"></div>
If I set it to the following, it doesn't:
<div><input type="date" class="form-control" id="DateCourse" name="DateCourse" value="<?php echo (isset($DateCourse))?$DateCourse:'';?>"></div>
The below:
$DateCourse = ($_POST["DateCourse"]);
var_dump($_POST["DateCourse"]);
var_dump($DateCourse);
Returns:
string(10) "2019-01-05" - means the post value is set
Notice: Undefined variable: DateCourse in /home/bitecons/bts.biteconsulting.co.za/v2/editccr.php on line 119 - how can it be undefined, I just defined it
NULL
What on earth am I doing wrong? Apart from using PHP :P
Flow as requested:
Records.php:
This is the function to prepopulate my posted fields:
function Prefill(x) {
TabletoEdit = x.closest('table').id;
SelectedRow = x.rowIndex;
document.getElementById("EntryEditing").value = x.cells[19].innerHTML;
document.getElementById("DateCourse").value = x.cells[0].innerHTML;
document.forms["records"].submit();
}
Then I also have:
<form action="editrec" method="post" id="records">
<input type='hidden' name='Period' id='Period' />
<input type='hidden' name='Month' id='Month' />
<input type='hidden' name='res' id='res' />
<input type='hidden' name='CustName' id='CustName' />
<input type='hidden' name='DateCourse' id='DateCourse' />
</form>
The Prefill gets called, then submits the form
I have tracked and DateCourse has data, but when getting to the other form, it "disappears":
if(!empty($_POST)) {
$DateCourse = ($_POST["DateCourse"]);
$CustName = ($_POST["CustName"]);
}
For example, CustName is filled in, but not DateCourse?
Side question:
Would this return true if another post var is not set (unrelated to this one):
if(!empty($_POST))
I think You use wrong Code
you Must Submit First Form And Then Use $DateCourse this In another Form in POSTBACK
One of the best way is to define $DateCourse too like
<?php
$DateCourse = "";
if(!empty($_POST["DateCourse"])) {
$DateCourse = ($_POST["DateCourse"]);
}
?>
<div><input type="date" class="form-control" id="DateCourse" name="DateCourse" value="<?php echo $DateCourse;?>"></div>
Okay, apologies folks, but it may help others in the future.
I had a function call to an old function - this failed, causing my variable to never get defined... I knew it was something stupid, but sometimes one needs a sound board...

Form that completes Values in PHP

I have a normal form in a PHP page, I send data to the php page from another for using POST. The PHP page runs some scripts to update data to SQL but on that page I have a second form that needs to be completed with data from the initial form prior to updating the SQL.
$recipient_nr = $_REQUEST['recipient_nr'];
Here I draw the info from the first form
Now I want to use this in a new form on the current PHP page how do I state this in the new form
<input type="text" name="recipient_nr" id="recipient_nr" value=".$recipient_nr.">
This is what I am attempting but it is not working I know I have too many "'" xxx"'" in the lines but not sure how to remidy this
Do you generate the new form in PHP? If so, where is the code where you do that?
If this is some kind of ...?> <input type="..."...> <?php ... page generation then you'll need to echo that $recipient_nr into the PHP-generated response:
...
?>
<input type="text"
name="recipient_nr"
id="recipient_nr"
value="<?php echo $recipient_nr; ?>">
<?php
...
Or, if you have short echos turned on,
...
?>
<input type="text"
name="recipient_nr"
id="recipient_nr"
value="<?= $recipient_nr ?>">
<?php
...
use this:
<input type="text" name="recipient_nr" id="recipient_nr" value="<?php echo $recipient_nr; ?>">
Something like this:
$recipient_nr = array_key_exists('recipient_nr', $_REQUEST)
? (string) $_REQUEST['recipient_nr']
: 'default value or empty string';
And output it:
<input type="text"
name="recipient_nr"
id="recipient_nr"
value="<?=$recipient_nr?>">
But if you want store this data for/between other pages you can use $_SESSION global array for save it.

AJAX .load() returns NULL

I'm building a website in PHP and I'm trying to implement asynchonous behaviour on some occasions, in this case to load an HTML form into an overlay and making it visible. This works as intended, however I'm now testing everything considering existing data.
So I basically created a variables.php file that sets values to the $_SESSION global and was working from there. Everything was working as expected on index.php, but as soon as I click the overlay I notice the values aren't passing through to populate the form that was added.
I already poked google for a few hours to no avail. I've added echo var_dump($_SESSION); on the index.php file and the values are all there. However on the overlay it returns NULL. I've even include_once("loginForm.php") right in the middle of index.php and that gave me the values. So there's something I'm missing in order to get the values to apply to .load() elements.
Here's some code:
variables.php
//added values to the $_SESSION global for testing purposes
$_SESSION['email'] = 'john#john.com';
$_SESSION['password'] = 'johnny';
$_SESSION['name'] = 'John';
$_SESSION['surname'] = 'Smith';
$_SESSION['country'] = 'UK';
$_SESSION['phoneOption'] = 'Mobile';
$_SESSION['phone'] = '987654321';
header-login.php
//this form accepts an email to check ifExists() and decide what's next
//the input #preLoginEmail assumes the value correctly
<form action="header-login.php" name="preLoginForm" id="preLoginForm" method="post">
<div id="login-part2">
<table id="preLoginTable">
<tr>
<td colspan="2">
<input type="text" id="preLoginEmail" title="Email" name="test-email" tabindex="1" size="10" maxlength="60" placeholder="Email" value="'. $email .'" />
</td>
</tr>
<tr>
<td><a title="forgotten password" href="header-login.php" id="preLoginForgot">forgot password?</a></td>
<td><input type="submit" class="btn1" name="preLoginRegisterButton" id="preLoginRegisterButton" tabindex="1" value="Login / Register" /></td>
</tr>
</table>
</div>
echo var_dump($_SESSION);//works
</form>
onClickEvents.js
//this call retrieves the HTML correctly although the variables dont get assigned to the input's value
$( "#preLoginForm" ).submit(function( event ) {
event.preventDefault();
var $form = $( this ),
term = $form.find( "input[name='test-email']" ).val(),
url = $form.attr( "action" );
verifiedEmail = validateEmail(term);
if(verifiedEmail){
// Put the results in a div
$('#olContainer').load("../inc/loginForm.php");
overlayOn();
}
else {
$('.session-stat').css({ "background-color": "#A60000" });
}
});
loginForm.php
//when this form is loaded there are no values in the inputs and var_dump($_SESSION) returns NULL
<form id="loginForm" name="loginForm" method="post" action="booking.php">
//some blocks are static and created in plain html
<input name="email" type="text" class="dDown12" id="agentuser" size="20" maxlength="20" value="<?php echo $email; ?>" />
//others are php variables to make the if/else statement more readable
$countryBlock ='<input name="agentuser" type="text" class="dDown12" id="agentuser" size="20" maxlength="20" value="'. $country .'" />';
echo var_dump($_SESSION); //NULL
I kinda ran out of ways to figure out what's going wrong, and I just started learning about AJAX this week. If u need anything else just let me know in comments I'll try to be quick to edit. Thanks in advance.
#Fernando - I didn't know which way you decided to go, but if you have to use $_SESSION for this, include:
session_start();
at the beginning of each file you plan to use sessions on, before any content is rendered. Also, be careful to have a means for your users to overwrite their values, ie. with a post, so that once a value gets put in session, there is a way to change it and it doesn't keep overwriting the (new) value. I usually clear out my sessions on Page one of the form. You can do a
unset($_SESSION['test-email']);
...to unset the values. You can use a foreach loop here too.
A great site to compare the speed of loops in PHP is http://www.phpbench.com/ also.
Best of luck!

Set Call to PHP Function, with POST Variables as Parameters, as HTML Form Action

I currently have an HTML file, with a form in it, that when submitted POSTs the form & calls a simple short PHP file that calls a function within another PHP file using the POSTed variables as parameters. The files are both below. What I am wondering is whether I can somehow skip the middleman PHP file, and simply call the function from my HTML file.
Ideally, this would set the call to the function:
insert_PE(new PE($_POST[Date],$_POST[Participant],$_POST[Time],$_POST[Result],$_POST[Notes]));
as the form action. Does anyone know how/if this can be achieved?
HTML:
<FORM ID="FORM1" METHOD="POST" AUTOCOMPLETE="off" ACTION = "writeToDL.php">
<INPUT TYPE="hidden" NAME="Date" STYLE="WIDTH:0px; " MAXLENGTH="8" TITLE="Enter Date" Value="<?php $dt = date('Y-m-d'); echo $dt ?>"/>
<INPUT TYPE="text" NAME="Time" STYLE="WIDTH:70px; " MAXLENGTH="7" ONCHANGE="validateTime();" />
<SELECT NAME = "Result">
<OPTION VALUE = OK></OPTION>
<OPTION VALUE = C>C</OPTION>
</SELECT>
<SELECT NAME = "Participant" STYLE = "WIDTH: 187">
<OPTION SELECTED VALUE = "">Select...</OPTION>
<?PHP
$allParticipants = getall_participants();
foreach($allParticipants as &$value) {
$val = $value->get_id();
echo "<OPTION VALUE='",$val,"'>";
echo $value->get_first_name()," ",$value->get_last_name();
echo "</OPTION>";
}
?>
</SELECT>
<TEXTAREA NAME='Notes' COLS='28' ROWS='5'></TEXTAREA>
<INPUT TYPE="image" SRC = "images/submit.png" VALUE="Submit Participant"/>
</FORM>
PHP File:
<?php
include_once('database/PE.php');
insert_PE(new PE($_POST[Date],$_POST[Participant],$_POST[Time],$_POST[Result],$_POST[Notes]));
?>
You COULD do something like this:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
include_once('database/PE.php');
insert_PE(new PE($_POST['Date'],$_POST['Participant'],$_POST['Time'],$_POST['Result'],$_POST['Notes']));
} ?>
<html>
... rest of your page here ...
</html>
That way the PHP code only fires if an POST was actually performed. Some would suggest checking for the presence of a form field, but that's unreliable - you might change the form down the road and forget to update the if(). Checking the request method is guaranteed to be 100% reliable.
What I am wondering is whether I can somehow skip the middleman PHP file, and simply call the function from my HTML file.
No. The client only knows about URIs.
A URI can map to a PHP program. Multiple URIs can map to the same PHP program. You can use logic to determine what functions to run for a given URI. You can't avoid having that logic in your program.
One option is to put method="_the_main_php_file_containing_function_to_be_called_"
I hope it works fine.
I think you could use a hidden field on the form, and populate it with the name of the function you want to run on "destination.php". Then a switch statement on "destination.php" could pull the name of the function from POST variable.

Basic problem of getting values of my textbox

I am just trying to learn PHP and want to get the value of the textbox using $_post function, but its not working. I am using wamp 2.1 and the code is simple as below
<form method="POST" action="c:/wamp/www/test/try.php">
<input type="text" name="nco" size="1" maxlength="1" tabindex="1" value="2">
<input
tabindex="2" name="submitnoofcompanies" value="GO"
type="submit">
</form>
<?php
if (!isset($_POST['nco']))
{
$_POST['nco'] = "undefine";
}
$no=$_POST['nco'];
print($no);
However in no way I get the value of the textbox printed, it just prints undefined, please help me out.
You first assigned the word "undefine" to the variable $_POST['nco'].
You then assigned the value of the variable $_POST['nco'] (still "undefine" as you stored there) to the variable $no.
You then printed the value stored in the variable $no.
It should be clear that this will always print the word "undefine".
If you want to print the value of the textbox with the name nco, fill out the form with that textbox, and in the page that process the form,
echo $_POST['nco'];
...is all you do.
You need to setup a form or something similar in order to set the $_POST variables. See this short tutorial to see how it works. If you click the submit button, your $_POST variables will be set.
what for you are using this line $_POST['nco'] = "undefine"; } ..?
and please cross check whether you are using form method as post and make sure that your text name is nco ... or else use the below code it will work.
<?php
$no = $_POST['nco'];
echo $no;
?>
<form name='na' method='post' action="<?php echo $_SERVER['PHP_SELF'];?>">
<input type='text' name='nco'>
</form>
thanks
Your action is wrong.
Change it to
action="try.php"

Categories