generating dynamic select box after form submit - php

Im building an upload form where a user can upload a document along with details about the document such as its name etc. The issue that I am having is that when a user selects a category using a select I have to generate another select which then gives the user the option of choosing a sub category. see the following:-
$(".department").change(function() {
var url = "includes/get-categories.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#upload-modal").serialize(), // serializes the form's elements.
success: function(data){
//this is where the select is generated
$(".sub").html(data); // show response from the php script.
//The alert works but the above line does not
alert("yeahhhhhhhhhhhhhhh boi");
}
});
Now this works like it should in that when the select is changed it generates another select from get-categories and gives the user another select box. But for some reason when a user submits the form and they are presented with a list of errors in the form (fields left blank etc) the select box will no longer be generated by selecting a category. I even tested the code with an alert which did work so im really confused as to why the following line doesnt work
$(".sub").html(data);
Here is my form which is pretty standard
echo "<form enctype='multipart/form-data' action='".$_SERVER['PHP_SELF']."' method='POST' autocomplete='off' id='upload-modal'>";
echo '<fieldset>';
echo '<legend>Please fill in all the fields below:- </legend>';
echo '<label for="docname">Document name</label>';
echo '<input class="block" type="text" name="docname" id="docname" value="'.$_POST['docname'].'" />';
echo '<label for="version">Version (if left blank it will be entered as 1.0)</label>';
echo '<input class="block" type="text" name="version" id="version" value="'.$_POST['version'].'" />';
//We need to now give a drop down for the admin to select a department
try {
$conn = new PDO(DB_HOST,DB_USER,DB_PASS);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare('SELECT X FROM Y WHERE Z = :id');
$stmt->execute(array('id' => A));
while($row = $stmt->fetch()) {
// if the user is an admin we provide them with the admin link
if($row['admin_level']=="super" || $row['admin_level']=="admin" && $row['department']=="Assurance" ){
echo '<select id="department" class="block department" name="department">';
echo '<option value="0">department...</option>';
echo '<option value="policies">Policies</option>';
echo '<option value="procedures">Procedures</option>';
echo '</select>';
}
echo '<p class="sub"></p>';
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
echo '<label for="keywords">Enter keywords (seperate with ",")</label>';
echo '<textarea id="keywords block" name="keywords" rows="4" cols="50" value="'.$_POST['keywords'].'"></textarea> ';
echo '<label for="filename">Supported formats - .docx & .pdf</label>';
echo '<input type="file" name="filename" id="filename" title="Supported formats - .docx and .pdf" />';
echo '<input class="submit-ie6" type="submit" name="submit" value="Upload" id="upload-modal-submit" />';
echo '</fieldset>';
echo '</form>';
Any help is most appeciated

Try using a tool like Firebug and see why after the submit, this: $(".sub").html(data); does not work. The reason probably is because after you submit the form(with errors) the:
echo '<p class="sub"></p>';
is not there.
I would suggest the below:
Get your
<p class="sub"></p>
out of try{} and just use css like:
<p class="sub" style="display:none;"></p>
So all you have to do, is when the user selects a category, create the second select box and remove the display:none from the p like:
$(".sub").html(data);
$(".sub").show();

Related

Text disppears from text field after clicking submit button html php. Need the text to stay

I have a submit button in my form which when clicked, the text in my text field disappears. I basically need the text to stay because I have another button that requires the text in that text field. The two buttons are parts of two different functions and I was wondering if there was a way to use the value of the variable in the function of one button in the function of the other.
For example, here is the code for one of the buttons:
Enter customer name<input type="text" name="cname">
<input type="submit" name="sub" value="Display">
<?php
if(isset($_GET['sub'])){
display();
}
function display(){
include 'config.php';
$searchstr=$_GET['cname'];
echo "<input type='hidden' name='cname1' value=".$searchstr.">";
$td=$_GET['cname1'];
$sql="select * from info where cname='$searchstr';";
$result=mysqli_query($conn, $sql);
if($searchstr==""){
$message="Please enter a customer name";
echo "<script type='text/javascript'>alert('$message');
window.location.href='retreive.php';</script>";
}
else{
echo "<table id='info' border='1px solid black'><tr padding='2'><th>Customer Name</th><th>Purchase Order Date</th><th>Started?</th><th>Reason (If any)</th><th>Tentative start date</th><th>Progress</th><th>Current Status</th><th></tr>";
while ($row = $result->fetch_assoc()) {
$cname=$row['cname'];
$podate=$row['podate'];
$started=$row['started'];
$reason=$row['reason'];
$tentdate=$row['tentdate'];
$progress=$row['progress'];
$status=$row['status'];
echo "<tr><td>".$cname."</td><td>".$podate."</td><td>".$started."</td><td>".$reason."</td><td>".$tentdate."</td><td>".$progress."</td><td>".$status."</td></tr>";
}
echo "</table><br>";
}
Everything works perfectly here and displays the table as required. But notice the variable $td above. I need that value displayed when my other button is clicked, which is in a different function.
Here's the code for the other button:
echo "<input type='submit' name='fp' value='Finished payment'>";
if(isset($_GET['fp'])){
echo $td;
}
Clicking that button doesn't display anything which means I am not able to read this variable outside the display function.I have tried looking up global variables in php and another solution was to use the and then use Javascript but I want to use php and I need the text to remain in the text field after the submit button is clicked so that I can read it later.
Thank you.
Once you submit the form, the text entered by the user disappeared? It's the default behavior of the browser. To avoid this either submit form using jQuery or store the value of the input into variable and echo.
Sample code for Jquery:
$("#myform").submit(function(e) {
//prevent Default functionality
e.preventDefault();
//get the action-url of the form
var actionurl = e.currentTarget.action;
//do your own request an handle the results
$.ajax({
url: actionurl,
type: 'post',
dataType: 'application/json',
data: $("#myform").serialize(),
success: function(data) {
... do something with the data...
}
});
});
==If not using Jquery==
PHP:
$myValue = $_POST['my_input_name'];
HTML:
<input type="submit" name="sub" value="<?= $myValue ?>">
You can simply create a variable for the value, then place that variable in the value section of the other input.
$name= 'Enter Name';
if(isset($_GET['cname'])){
$name = $_GET['cname'];
}
Then
<input type="text" name="cname" value="<?=$name?>">
Using placeholder attribute:
<input type="text" placeholder="Enter Name" name="cname" value="<?php echo $name; ?>
Before the $_GET['cname'] has been processed, the value within the input field is set to the text you wish to show, or simply keep it empty. Then once the $_GET['cname'] has been posted, you check to see if it is set, then set the variable to equal the returned information the user entered in the other field - $td.
<?php
$cname = ''; // or $cname = 'Enter a Name';
if(isset($_GET['sub'])){
display();
}
function display(){
include 'config.php';
$searchstr=$_GET['cname'];
$td=$_GET['cname'];
$sql="select * from info where cname='$searchstr';";
$result=mysqli_query($conn, $sql);
if($searchstr==""){
$message="Please enter a customer name";
echo "<script type='text/javascript'>alert('$message');
window.location.href='retreive.php';</script>";
}
else{
//use isset to see if that has been posted
if(isset($_GET['cname'])){
$name = $_GET['cname'];
//$name is now set to the value you wish to display in the value of the other input
//call on the value like so <input type="text" name="cname" value="<?=$name?>">
}
echo "<table id='info' border='1px solid black'><tr padding='2'><th>Customer Name</th><th>Purchase Order Date</th><th>Started?</th><th>Reason (If any)</th><th>Tentative start date</th><th>Progress</th><th>Current Status</th><th></tr>";
while ($row = $result->fetch_assoc()) {
$cname=$row['cname'];
$podate=$row['podate'];
$started=$row['started'];
$reason=$row['reason'];
$tentdate=$row['tentdate'];
$progress=$row['progress'];
$status=$row['status'];
echo "<tr><td>".$cname."</td><td>".$podate."</td><td>".$started."</td><td>".$reason."</td><td>".$tentdate."</td><td>".$progress."</td><td>".$status."</td></tr>";
}
echo "</table><br>";
}
php fiddle: Good for 48 hours only - http://main.xfiddle.com/8f416cc9/input.php

How to post multiple entries from dynamically generated textboxes in while loop

please i am currently working on a school result computation project in php. I have a page that gets all the students that enrolled for a particular subject. A while loop generates three textboxes against each student's name(CA1, CA2, and Exam). Please can anyone help me with a solution?? When the form is submitted only the last entry enters the database. Below is my code.
<?php
session_start();
include 'header_staff.php';
$subject=$_POST['subject'];
$user_id=$_SESSION['user_id'];
$get=mysql_query("SELECT * FROM staffrecord WHERE user_id='$user_id'",$conn);
$go=mysql_fetch_array($get);
$class=$go['class_id'];
$sql=mysql_query("SELECT * FROM student_enrollment WHERE class_id='$class' AND subject_id='$subject'",$conn);
echo '<form action="submitrslt.php" method="post">';
while($subj=mysql_fetch_array($sql)){
echo $subj['name'];
echo '<input type="text" name="ca1" />';
echo '<input type="text" name="ca2" />';
echo '<input type="text" name="exam" /><br><br>';
}
echo '<input type="submit" value="submit" />';
?>
The solution to your problem is to use your input arrays by simply adding [] to the input names:
while($subj=mysql_fetch_array($sql)){
echo $subj['name'];
echo '<input type="text" name="ca1[]" />';
echo '<input type="text" name="ca2[]" />';
echo '<input type="text" name="exam[]" /><br><br>';
}
Further, you can use the primary key of your table as the index in each iteration (let's suppose this would be $subj['id'], but if it is more meaningful in your case, you can also use $subj['name'] as the index):
while($subj=mysql_fetch_array($sql)){
echo $subj['name'];
echo '<input type="text" name="ca1[<?php echo $subj['id'] ?>]" />';
echo '<input type="text" name="ca2[<?php echo $subj['id'] ?>]" />';
echo '<input type="text" name="exam[<?php echo $subj['id'] ?>]" /><br><br>';
}
This way you can easily identify values from the resulting array after the post.
PS: Be sure you never trust user input without verifying or sanitizing it - make sure $_POST['subject'] is numeric. You can find plenty of useful tips on how to achieve this.
I have added comments, this will solve your problem i am assuming your subjects data is unique for the loop. And i have defined the input with the subject name which make it unique. Just for an example you can try your own method. This will output all the post variables on your action(form post) screen.
<?php
while($subj=mysql_fetch_array($sql)){
$subname = str_replace(' ','', $subj['name']); //just to replace the space
echo $subj['name'];
echo '<input type="text" name="'.$subname.'_ca1" />'; //to make the field unique for the input entries
echo '<input type="text" name="'.$subname.'_ca2" />';
echo '<input type="text" name="'.$subname.'_exam" /><br><br>';
}
echo '<input type="submit" value="submit" />';
echo '</form>';
?>
Firstly, I would suggest changing the connection to mysqli, which follows a very similar syntax to mysql except that it is not deprecated.
Secondly, the form looks fine, except that the textboxes and submit button don't have any unique identifiers, you might try putting in a unique 'id' for each of the input fields. Since your loop is combining all input fields in one form, this is likely the culprit. Furthermore, I don't see a closing tag for form, i.e. </form>.
Finally, you should look up filter_input for handling superglobals such as $_POST[].
I assume that all fields are meant to be submitted at once rather than individually?

PHP generate multiple form fields

I am working on a system to edit/create an online food menu.
On the system that creates/edits the menu I would like the user to be able to enter a new item and price in two form fields and then press 'add another item' in turn this generates another form field. The user can keep pressing 'add another item' or simply submit the form.
Ideally it would keep generating forms fields then when the form is submitted an I handle the POST array and do the DB work.
I'm just not too sure on how I can allow the user to essentially keep adding form fields.
This is system is currently written in PHP.
Hi, Looking into this and my current code, this issue I see is that the form itself is also dynamically generated from database results. Your idea I can see working when I create an entirely new menu, but what if I want to edit a current menu and add a new item to it.
This is the code that generate the current form.
if($menuItems->count()) {
echo '<form class="updateMenu" action="" method="post">';
echo '<table class="gridtable gridtableMenu">';
echo '<tr><th>Item Name</th><th>Item Price</th></tr>';
foreach($menuItems->results() as $item){
echo '<tr>';
echo '<td class="menu-name"><input type="text" name="itemName[]" value="' . $item->item_name . '" required></td>';
echo '<td class="menu-price"><input type="number" step="any" name="itemPrice[]" value="' . $item->item_price . '" required></td>';
echo '<input type="hidden" name="id[]" value="' . $item->id . '">';
echo '</tr>';
}
echo '</table>';
echo '<input type="submit" name="updateMneu" value="Update Menu">';
echo '</form>';
} else {
echo '<div class="error">No items have been added to this menu</div>';
}

PHP MYSQL: Cannot insert data from drop down box and a text box

I am trying to insert data that the user submits from a drop down box and a text box, however this data is not being inserted into my Database Table.
The Drop Down and text box code:
echo 'Tasks: <select name="selected_task">
<option value=""> ---Select ---- </option><br><br><br><br>';
/*
Query code to retrieve options goes here and assign it to a variable named '$tasks'
*/
while ($row_list = mysql_fetch_assoc($tasks))
{
echo '<option>' . $row_list['taskname'];
if ($row_list['taskname']==$select) { echo $row_list['taskname']; }
echo '</option>';
}
echo '</select>';
echo '<div id="task_hours">
<form name="hours" method="post" action="login.php?action=hours">
Hours: <input type="text" name="hours" value="" /><br />
<input type="submit" name="submit" value="Submit" />
</form>
</div>';
Database insertion code :
$posted_client = $_POST['selected_client'];
$posted_task = $_POST['selected_task'];
$conn_task = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$inserted_time = "INSERT INTO tasks (taskhours) VALUES :posted_hours WHERE taskname = :posted_task ";
$sp = $conn_task ->prepare ( $inserted_time);
$sp->bindValue(":posted_hours", $posted_hours, PDO::PARAM_STR); // Make sure you use PDO::PARAM_STR for decimals
$sp->bindValue(":posted_task", $posted_task, PDO::PARAM_STR);
$sp->execute();
$conn_task = null;
echo "Your total time has been entered!<br>";
echo "Your Total Hours: " . $posted_hours;
When the form appears and I click on the 'submit' button after entering data, no error message appears but the number of hours for the table field 'taskhours' is not being updated.
<Select>tag is a Element Of Form So when you use outside form then it doesn't work. so you have put the <Select> ('dropdown') is inside the <form> then your action page put below code and check you got the data or not in your post method.
<?php
echo "<pre>";
print_r($_POST);
?>
here you got the all the form data.
In this case, select tag isn't inside form one.
Put it inside and it will work.

How to submit a php select inside form using jquery

I have a form which only has one selector in it whos options are mostly populated by php which currently get submitted by <input type="submit" name="courseSubmit"/>
echo '<form name="CourseForm" action="" method="post">';
echo '<select name="CourseSelect"><option value="0">Select Course</option>';
$result = mysqli_query($con," SELECT * FROM course c ");
while($row = mysqli_fetch_array($result))
{
echo "<option value='".$row['IDNum']."' ".$select.">" . $row['Title'] . "</option>";
}
echo '</select>';
echo '<input name="CourseSubmit" type="submit"/></form>';
Upon clicking the button the page is submitted then by using $_POST['CourseSelect'] i can get the value of the select.
However when I try replacing the functionality of the submit button with onchange="this.form.submit()" inside of my select the form does not appear to be submitted
I know I can call js functions from php for example
echo "<select onchange="myjsFunction()">";
there a way using jquery to submit the form in the exact same manor as using <input type="submit"/> ?
You could do something like:
$('select[name=CourseSelect]').change(function(){
$(this).closest('form').submit();
});
And ignore the onchange attribute entirely for the HTML element.
Here's a recursive example:
http://jsfiddle.net/erXxd/1/

Categories