Is this possible to accomplish with html and php? - php

I've made the form below. Is it possible to make it that when user enters the number of fields, for example 6, that the table below has 6 rows. It would be great if it would be possible to make it without any submit button (so that the trigger for this action is exiting from the text input box).
Here is the html code of this form:
<fieldset>
<legend>Student Information</legend>
Number of fields: <input type="text"><br />
Total number of characters: <input type="text">
<br>
<br>
<table border="1">
<th></th>
<th>field</th>
<th>number of characters</th>
<tr>
<td>1</td>
<td><input type="text"></td>
<td><input type="text"></td>
</tr>
<tr>
<td>2</td>
<td><input type="text"></td>
<td><input type="text"></td>
</tr>
</table>
</fieldset>
If this is not possible (without submit button), than in which way would you accomplish the same result? Thank you for any help and/or suggestions.

PHP is server side, it runs only once, when the page is loading. HTML is not a programming language. You could generate the table with PHP, but only if you had a submit button that reloaded the page. If it has to happen because of a user event, it always needs to be done with Javascript.
That means, you will need Javascript to make this work without reloading the page. Ideally, you would use Jquery (Javascript's most popular plugin) to manipulate the DOM.
If you had this input :
<input id="field" type="text">
You could call the on-leave event like this :
$("p").focusout(function()
{
// Delete the previous table, and create a new one, here
});
As for creating the actual table, it isn't complicated, but it is a bit of work. You should read the following reference to start you up :
http://www.tutorialspoint.com/jquery/jquery-dom.htm
You will need to "install" JQuery before-hand, you can simple insert this at the top of your code :
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>

Okay here is the post only script you require
<?php
$rows=2;
if(isset($_POST['submit']))
{
if($_POST['submit']=='Update')
{
if(isset($_POST['rows'])) $rows=max($rows, intval($_POST['rows'])); // minimum 2 rows
}
else
{
// process posted data here
// reset post or jump to another page
$_POST=array();
//header("Location:index.php");
//exit();
}
}
?>
<form method="post">
<fieldset>
<legend>Student Information</legend>
Number of fields: <input type="text" name="rows" value="<?php echo $rows; ?>"><br />
Total number of characters: <input type="text">
<input type="submit" name="submit" value="Update"/>
<br>
<br>
<table border="1">
<th></th>
<th>field</th>
<th>number of characters</th>
<?php
for($loop=1;$loop<=$rows;$loop++)
{
echo '<tr>';
echo '<td>'.$loop.'</td>';
echo '<td><input name="field['.$loop.']" value="'.$_POST['field'][$loop].'" /></td>';
echo '<td><input name="chars['.$loop.']" value="'.$_POST['chars'][$loop].'" /></td>';
echo '</tr>';
}
?>
</table>
<input type="submit" name="submit" value="Submit"/>
</fieldset>
</form>
It will default to 2 rows (minimum), and retain the data when you update the rows.
If the rows get reduced, then the end ones disappear

It certainly would be doable with just PHP.
So for example, if you typed in '6' rows you could catch the form post and do something like (template form for within the HTML):
<?php for($i=0; $<=$_POST['rows'];$i++): ?>
<!-- This being your whatever html for the table -->
<tr><td></td></tr>
<?php endfor; ?>

Related

Get value of a table data on button click

I am building a online exam application, here paper name and no. of papers are retrieved from database. Now I want to get the paper code of that paper for which I clicked the start button. Code for the table is here:
<form method="post" action="exam_page.php" >
<table >
<tr style="background-color: #7F859E;color:white; height:50px;">
<th style="padding-left:140px; width:550px;">Paper</th>
<th style="padding-left:40px;">Time</th>
<th style="padding-left:40px;">Duration</th>
<th style="padding-left:40px; width:250px;"></th>
</tr>
<?php
$i=1;
while($row=mysql_fetch_array($rs)){?>
<tr style="height:80px; background-color: #CCCCCC;">
<td style="padding-left:40px;">
<input type="text" value="<?=$row['paper_code']?>" name="paper_code<?=$i?>" readonly><?=$row['paper_name']?>
</td>
<td style="padding-left:40px;">
<input type="text" value="<?=$row['time']?>" readonly style="width:90px;">
</td>
<td style="padding-left:40px;">
<input type="text" value="<?=$row['duration']?> Min" readonly style="width:90px;">
</td>
<td style="padding-left:40px;"><button style="width:100px;">Start</button></td>
</tr>
<?php $i++; } $_SESSION['exam']=$i; ?>
</table>
</form>
Name your submit button, (also make it a submit type) and assign the paper code to its value attribute.
<button type="submit" style="width:100px;" name="clicked" value="<?=$row['paper_code']?>">
Start
</button>
Now, in exam_page.php you can get the value of the clicked button from $_POST['clicked']. (Or whatever you decide to name it.)
To get the values from the other inputs associated with the button you clicked, you can add the paper code to their names instead of using $i.
<input type="text" value="<?=$row['time']?>" name="time[<?=$row['paper_code']?>]">
and in exam_page.php you can get the value from $_POST['time'][$_POST['clicked']], etc.
If they aren't intended to be editable in your form, though, I would recommend using something else to display them and just loading them from the database in exam_page.php instead. Otherwise, your users will be able to override the readonly attribute and submit different values.
Try using javascript onclick functions:
<script>
function getPaperCode(paperCode)
{
alert(paperCode);
}
</script>
Then edit your input add onclick event:
<input type="text" value="<?php echo $row['paper_code']; ?>" onclick="getPaperCode('<?php echo $row["paper_code"]; ?>');" name="paper_code<?php echo $i; ?>" readonly><?=$row['paper_name']?>
Once you click. it will alert the value of the button
passed your unique id value or examcode via hidden field like this
<input type="hidden" name="id" value="<?=$row['eid']?>">
and on button click perform query like
$id=$_POST['id'];
select * from table_name where id='$id';

.submit() Jquery method attached to dynamically loaded form is not submitting any "POST" data in browsers except IE

This is a bit weird but this time I have came across something that works on IE and not on other browsers like firefox and chrome..
Here is the issue:
I am dynamically loading a part of a page, that contains a form, into my existing page with jquery .load() method.
I have used .on method to attach event handler for the newly added elements.
But when I click on submit button the form submit method works fine, but it doesnt send any data in post query ( by the way, I have specified form method=POST")
The main issue is that before I fire the .load() method to obtain new elements and replace the existing ones, the .submit() works FINE. IT SENDS THE POST DATA.
But after the dom is replaced, there is no data in POST.
jQuery Code:
$(document).on("click", ".s_edit",function()
{$(this).parents('tr').children('form').submit();});
.s_edit is the form submit button:
PHP/HTML code (CodeIgniter):
<tr>
<form method="post" action="<?php echo base_url();?>index.php/userlist/inline_edit/<?php echo $r['id'];?>">
<td><input class="record_edit" type="text" name="name" id="name<?php echo $r['id'] ?>"/></td>
<td><input class="record_edit" type="text" name="age" id="age<?php echo $r['id']; ?>"/></td>
<td>
<span class="record_edit">
<input id="gen_m<?php echo $r['id']; ?>" type="radio" name="gender" value="m"/>Male<br/>
<input id="gen_f<?php echo $r['id']; ?>" type="radio" name="gender" value="f"/>Female
</span>
</td>
<td><input class="record_edit datepick" type="text" name="joining_date" id="joining_date<?php echo $r['id']; ?>"/></td>
<td>
<div class="record_edit">
<input type="submit" value="save" class="s_edit"/>
<input type="button" class="cancel_edit" value="Cancel"/>
</div>
</td>
</form>
</tr>
Because you have <tr><form><td>, other browsers are stripping the form element out, or re-arranging it in the DOM tree.
I.E. In Firefox,
<table>
<tr>
<form>
<td>a</td>
</form>
</tr>
</table>
goes to
<table>
<tbody><tr>
<form></form>
<td>a</td>
</tr>
</tbody></table>
Hence, your form is no longer wrapping the elements in the td.
Ok..I replaced the table formatting with div and table display properties in css..firefox and mozilla as Benno suggested was getting rearranged except for IE..still it somehow worked before invoking .load method of jquery..but now its working completely fine..

PHP POST value from a looped table

Please help me out of this.....
I am designing a table which is inside a form.
the table is generated based on while loop.
In each row there is a download button.
when i click download the POST value should get the same row information.
But my POST variable is giving me the last row information only.
I tried using input-type as hidden... But it did not work
Here is the code for your reference
enter code here
<form name="simpleform" method="post" action="insert.php">
<?php
$data = "environment";
$user_name = $_SESSION['username'];
$serch = mysql_query("SELECT * FROM data WHERE (data_category = '" . $data . "') ");
while ($record=mysql_fetch_assoc($serch))
{?>
<tr class="warning">
<td >
<input type="text" value=<?php echo $record['data_ID'];?> readonly="readonly" >
<input type="hidden" value=<?php echo $record['data_ID'];?> name="dataid" />
</td>
<td >
<input type="text" value=<?php echo $record['data_name'];?> readonly="readonly" >
<input type="hidden" value=<?php echo $record['data_name'];?> name="dataname" />
</td>
<td >
<input type="text" value=<?php echo $record['data_downloads'];?> readonly="readonly">
<input type="hidden" value=<?php echo $record['data_downloads'];?> name="datadown" />
</td>
<td >
<input type="text" value="" >
<input type="hidden" value="" name="datause" />
</td>
<td>
<input type="submit" name="simplesubmit" value="Go to download" />
</td>
</tr>
<?php }
exit;
?>
</tbody>
</form>
The problem is that you are using the same name attribute for all your controls. Thus, when PHP receives the form, they get overwritten, and you only see the last value of the form.
The simplest way to avoid that is just appending [] to the end of your names -- eg name=dataid[]. This will make PHP take all arguments as an array, so you don't lose data.
The second problem, is that your submit button also has the same name - you should diversify it by using some row-specific data in its name, such as 'name="submit-'.$record['data_name'].'"'
For more info, more code from you is needed, such as what are the data you are printing like.
Every post button can have its name and value, so if you change your code to produce a traceable post button name you can just do whatever you want with that.
<table>
<tr>
<td>...</td>
<td>...</td>
<td><input type="submit" name="submit[1]" value="OK" />
</tr>
<tr>
<td>...</td>
<td>...</td>
<td><input type="submit" name="submit[2]" value="OK" />
</tr>
</table>
When the form is posted its very easy to capture which button is clicked;
if ($_POST["submit"]) {
$id = key($_POST["submit"]);
}
Thanks for info... and good response. As you said , i replaced the same and saw the post value is giving me all arguments as array. My purpose is to let the client download file that he clicks. so if the client click the first row button in the table, the post value should get only that Data_name. So that i can run a query to get the URL of that data_name and download

Validating form input in PHP

is it possible to write a PHP page say form.php with a php function generalValidate($form) that is able to perform the following scenario :
user browse to form.php
user gets an html form
user fills form and the form is sent back with POST method to form.php
form.php activate generalValidate($form) where form is the just recived form filled by user
generalValidate($form) returns true if this form is valid (for exemple properly filled), false else.
i think that another way to describe my question will be - is there a general way to iterate over an HTML form sent by a client (perhaps a form that the php page itself sent to client in the first place) while activating some code over each of the form values?
dont eat me if its a bad question, im really just trying to learn :)
a code exemple to fill for your convinience :
<?php
function generalValidate($form) {
...
}
if (!isset($_SESSION))
session_start();
else if (generalValidate(...)) {
}
?>
<html>
<head>
</head>
<div>
<p>Register</p>
</div>
<form id="regfrm" action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="post" align="center">
<table align="center">
<tr>
<td>First Name :</td>
<td><input name="fname" value="<?php if (isset($_POST["fname"])) {echo v($_POST["fname"]);}?>" required></input></td>
</tr>
<tr>
<td>Last Name :</td>
<td><input name="lname" value="<?php if (isset($_POST["lname"])) {echo v($_POST["lname"]);}?>" required></input></td>
</tr>
<tr>
<td>Email :</td>
<td><input id="email" name="email" value="<?php if (isset($_POST["email"])) {echo v($_POST["email"]);} else {echo "xo#xo.xo";}?>" required></input></td>
</tr>
<tr>
<td>Password :</td>
<td><input name="pw" type="password" value="e" required></input></td>
</tr>
<tr>
<td>Retype password :</td>
<td><input name="pw" type="password" value="e" required></input></td>
</tr>
</table>
<input type="submit" value="Register" ></input>
</form>
</body>
</html>
Yes. Although iterating over the fields gives you a little less clarity and makes it more messy when you want to determine how to validate said field (for example, to know if whether the value should be a name or a number or whatever), but you can do it this way:
In your PHP script you could have something like:
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Determines if the form was sent through the POST method
foreach ($_POST as $fieldName => $formValue) {
// Validate $formValue
}
}
What I think you want to ask is if form data can be manipulated without knowing the form's variable names. I say this because you want to have a general purpose function where the code can be reused for any form. Since this may be any form that currently exists or a form you will create in the future you will not know the name of the variables in the form.
This code captures the form's input. All you have to do now is create a function that does whatever to the $name and $item values as they are looped through.
<?php
foreach($_POST as $name => $item) {
print "name::$name item::$item<br>";
}
?>
<html><title>test</title>
<form method="post">
field one: <input type="text" name="one">
<br>
field two: <input type="text" name="two">
<input type="submit" value="go!">
</form>
</html>
Of course, it is possible to have the page in which the original form resides as the recipient of the form dialog. Through the session variables, but mainly through the contents of the button variables you can determine which state your form is currently in (after having clicked a submit button you will get a $_REQUEST array element with the name of the button holding the value of the button).
Take a look at the answer here.
This is actually a canonical question for receiving form data in PHP. There are lots of ways to do it.

How to retrieve and display data using a PHP function within an HTML form

I have been working on this for probably 20 hours of research and trial/error with no solution in sight I figured I'd try here and see if someone can finally point me in the right direction and give me some solid advice.
Here's the setup. I have a page (customer_search.php) that has an HTML form, I want the user to be able to search the DB by $last_name and the results be displayed on a table on the same page.
First: IS THIS POSSIBLE? I have read so much over the past few days, I doubt myself but then I think it can be done without using Java and using purely PHP/HTML.
I also use MVC model.
THIS IS THE MAIN PAGE (customer_search.php)
<?php include '../view/header.php';
?>
<div id="main">
<h1>Customer Search</h1>
<div id="content">
<form action="" method="post" id="aligned"
<label>&nbsp Last Name</label>
<input type="text" name="last_name"/>
<br />
<label> <label>
<input type="submit" value="Search" />
</div>
<div id="content">
<h2>Results</h2>
<table>
<tr>
<th>Name</th>
<th>Email Address</th>
<th>City</th>
<th> </th>
</tr>
<tr>
<td><?php echo $_POST['firstName'] .' '. $_POST['last_name']; ?></td>
<td><?php echo $_POST['email']; ?></td>
<td><?php echo $_POST['city']; ?></td>
<td><form action="customer_display.php" method="post">
<input type="hidden" name="action" value="get_customer" />
<input type="hidden" name="customer_id"
value="<?php echo $_POST['customer_ID']; ?>" />
<input type="submit" value="Select" />
</form>
</td>
</tr>
</table>
<br />
</div>
</div>
<?php include '../view/footer.php'; ?>
THIS IS customer_db.php in the MODEL folder which contains a function that I'd like to use, get_customers_by_last_name($last_name)
<?php
function get_customers() {
global $db;
$query = 'SELECT * FROM customers
ORDER BY lastName';
$customers = $db->query($query);
return $customers;
}
function get_customers_by_last_name($last_name) {
global $db;
$query = "SELECT * FROM customers
WHERE lastName = '$last_name'
ORDER BY lastName";
$customers = $db->query($query);
return $customers;
}
I apologize for the OVERLOAD of code, but this is my first post on here and I've tried everything I can think of. I just want to search the DB by last name on the html form and then have the results displayed on the table (on the same page) and I don't care if the page has to refresh. I know PHP is server-side and not client so it needs to refresh. I just can't seem to get the results to actually display in the table, if I could just get the results there, the next step is to SELECT the customer which passes it to the next page customer_display.php but I'll cross that bridge when there. Thanks for your help, and I really am begging for some help/lessons on this. I'm desperate!!!! :(
Hi you did your homework and are correct that the page HAS to be refreshed.
Unless you plan to use an Ajax call with javascrcipt (jQuery for exemple)
To do what you ask, you have to put the PHP at the beginning.
You put it in an If() statement that will only be valid if the form has been posted.
Here is what I would do with your code:
<?php
if(isset($_POST['last_name'])){
include_once 'customer_db.php';
$customers = get_customers_by_last_name($_POST['last_name']);
}
include '../view/header.php';
?>
<div id="main">
<h1>Customer Search</h1>
<div id="Search">
<form action="" method="post" id="aligned"
<label>&nbsp Last Name</label>
<input type="text" name="last_name"/>
<br />
<label> <label>
<input type="submit" value="Search" />
</form>
</div>
<?php if(isset($customers)){ ?>
<div id="Results">
<h2>Results</h2>
<table>
<tr>
<th>Name</th>
<th>Email Address</th>
<th>City</th>
<th> </th>
</tr>
<tr>
<?php while ($a_customer = mysql_fetch_assoc($customer)) { ?>
<td><?php echo $a_customer['firstName'] .' '. $a_customer['last_name']; ?></td>
<td><?php echo $a_customer['email']; ?></td>
<td><?php echo $a_customer['city']; ?></td>
<td><form action="customer_display.php" method="post">
<input type="hidden" name="action" value="get_customer" />
<input type="hidden" name="customer_id"
value="<?php $a_customer['customer_ID']; ?>" />
<input type="submit" value="Select" />
<?php } ?>
</td>
</tr>
</table>
<br />
</div>
<?php }?>
</div>
<?php include '../view/footer.php'; ?>
Some crucial advices:
Use Mysqli (or PDO) library instead of Msql for php
you should not trust user input data on your search form you can use the janitor.class to sanitize the post.
When you have more time check these links concerning PHP security : Evil User, PHP security , PHP Secure coding
Oh! and don't give two elements in the same page the same id Value the purpose of the id is to give each element a unique identifier.
I have had success doing this same thing in the past using JQuery and jTable.
This uses AJAX calls which allows you to call PHP scripts without reloading the page.
You can find out everything you need to know here: http://www.jtable.org/
Use AJAX to make a call to a PHP object that instantiates your model and returns your results in a JSON string. Upon receiving the results, use a JavaScript loop to iterate through the JSON and output your table.
I recommend jQuery, which has its own .ajax() function, and it's easy to manipulate the DOM with your result set. Go read the jQuery docs.
This is what AJAX is for... asynchronous communication with the server (i.e. not on a page load). Your best bet would probably be to use JQuery or another JS framework, which will make the AJAX calls a snap: $.ajax();:
Something like:
$.ajax({
type: "POST",
url: '/directory/to/php_script_that_outputs_the_table_html.php',
data: { name: "Smith"},
success: function(data) {
$('.class_of_div_to_recieve_code').html(data);
}
});

Categories