change and delete selected items from list - PHP - php

I have built a website which has lots of lists/tables (based on php). I am trying to make a Change All and Delete All system for the lists. I have already added checkbox to all individual list items. I also have one checkbox to select all those items with one click. Now I am stuck at how to execute the change and delete option. It's been 3 days...
I have done the Change All code right. But I can't figure out Delete All part.
I don't know to pass the $targetpage variable to make it redirect after that.
Here is the code:
<!DOCTYPE html>
<html>
<title>List 1</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://www.w3schools.com/lib/w3.css">
<link rel="stylesheet" href="http://www.w3schools.com/lib/w3-theme-purple.css">
<?php include('dbcon.php');?>
<style>a {text-decoration: none;}</style>
<!--Select All-->
<script>
function checkAll(ele) {
var checkboxes = document.getElementsByTagName('input');
if (ele.checked) {
for (var i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].type == 'checkbox') {
checkboxes[i].checked = true;
}
}
} else {
for (var i = 0; i < checkboxes.length; i++) {
console.log(i)
if (checkboxes[i].type == 'checkbox') {
checkboxes[i].checked = false;
}
}
}
}
</script>
<body>
<!--?php include ('header.php');?-->
<form name="form1" enctype="multipart/form-data" action="ajaxAction.php" method="post">
<div class="w3-container">
<div class="w3-padding-32 w3-center">
<input class="w3-btn w3-green" type="submit" name="chkbox" value="Change All" />
<input class="w3-btn w3-red" type="submit" value="Delete All">
</div>
<center>
<table class="w3-table-all" style="width: auto;">
<tr class="w3-theme">
<th><input class="w3-check" type="checkbox" onchange="checkAll(this)" name="chk[]" /></th>
<th>Data</th>
</tr>
<tr>
<td>
<input class="w3-check" type="checkbox" name="chkbox[]" />
</td>
<td class="w3-small" >
The data is displayed here.
</td>
</tr>
</table>
</center>
</div>
</form>
<br>
<!--?php include ('footer.php');?-->
</body>
</html>
Here is the ajaxAction.php code:
<!--Change-->
<?php
if ($_REQUEST['chkbox']) {
$targetpage = $_REQUEST['targetpage'];
$change = array ();
$change = $_REQUEST['chkbox'];
for($c=0;$c<count($change); $c++){
$sql_all = "update `table` set `value`='123' WHERE `id` = '$change[$c]'";
mysql_query($sql_all) or die(mysql_error());
}
?>
<script>
var targetpage = "<?php echo $targetpage ?>";
location.href=targetpage+"?done";
</script>
<?php } ?>
<!--Delete-->
<?php ?>
<script>
var targetpage = "<?php echo $targetpage ?>";
location.href=targetpage+"?done";
</script>
With my current code, I am only able to use the selected array chkbox[] for one processing i.e. Change All. I don't know how to use the same array for Delete All button.

After using the trial and error method and trying for two weeks, I finally got the solution ON MY OWN and I have a serious gripe because no one from this forum cared to show me the solution.
It was simple. All I had to do was to use $_POST instead of $_REQUEST and use different names both the buttons like this:
<input class="w3-btn w3-green" type="submit" name="submit1" value="Change All">
<input class="w3-btn w3-red" type="submit" name="submit2" value="Delete All">
So, I changed ajaxAction.php to:
<?php
//Change All
if(isset($_POST['submit1'])){
if(!empty($_POST['chkbox'])){
$targetpage = $_REQUEST['targetpage'];
foreach($_POST['chkbox'] as $selected){
$sql_all = "update `table` set value='123' WHERE `id` = '$selected'";
mysql_query($sql_all) or die(mysql_error());
}
}
?>
<script>
location.href="tables.php?done";
</script>
<?php } ?>
<?php
//Delete All
if(isset($_POST['submit2'])){
if(!empty($_POST['chkbox'])){
foreach($_POST['chkbox'] as $selected){
$sql_all = "DELETE FROM `table` WHERE `id` = '$selected'";
mysql_query($sql_all) or die(mysql_error());
}
}
?>
<script>
location.href="tables.php?done";
</script>
<?php } ?>
All you had to do was tell me that I should use $_POST. No one from Stack Overflow helped me.

Related

How to use a dropdown to assign a value to a certain row (out of rows that are being inserted in same form) using PHP

I am creating a quiz builder using SQL, HTML and PHP, whereby the user can insert their question and four answer choices for that question (A, B, C or D).
In the same form they can then choose what choice will be the correct answer from a dropdown. This should then assign the 'is correct' boolean value of that certain answer row to 1 in the database.
[my database structure and what my form should look like is attached]
<?php
include ("nav.php");
include("connect.php");
$quiz_id = htmlentities($_GET["quizid"]);
$quiz = "SELECT * FROM `q_quiz` WHERE q_quiz.id ='$quiz_id'";
$quizresult= $conn->query($quiz);
if(!$quizresult){
echo $conn->error;
}
?>
<html>
<head>
<title></title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" href="ui/styles.css">
<!-- UIkit CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/uikit/3.0.3/css/uikit.min.css" />
<!-- UIkit JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/uikit/3.0.3/js/uikit.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/uikit/3.0.3/js/uikit-icons.min.js"></script>
</head>
<body>
<div class ='uk-container'>
<?php
if (isset($_POST['submit'])) {
include("connect.php");
$newquest = $conn->real_escape_string($_POST['question']);
$insertquest = "INSERT INTO q_questions(quiz_id, question)
VALUES ('$quiz_id', '$newquest')";
$resultquest = $conn->query($insertquest);
$quest_id = $conn -> insert_id;
if (!$resultquest) {
echo $conn->error;
}
foreach ($_POST['ans'] as $ans) {
$answers = $conn->real_escape_string($ans);
$insertans = "INSERT INTO q_answers (question_id, answer) VALUES ('$quest_id', '$answers')";
$resultans = $conn ->query($insertans);
if (!$resultans) {
echo $conn->error;
} else {
header("Location: managequiz.php?quizid=$quiz_id");
}
} //END OF FOREACH LOOP
}
?>
<?php
while ($row = $quizresult->fetch_assoc()) {
$titledata = $row["title"];
}
?>
<div uk-grid>
<form class="uk-form-horizontal" method='POST' action='#'>
<input type='hidden' name='questionid' value=''>
<fieldset class="uk-fieldset">
<legend class="uk-legend">New question for quiz: <?php echo $titledata?></legend>
<div class="uk-margin">
<label class="uk-form-label">Question</label>
<div class="uk-form-controls">
<textarea class="uk-textarea" rows="5" placeholder="Enter your question here..." name='question' required></textarea>
</div>
</div>
<div class="uk-margin">
<div class="uk-form-label">A</div>
<div class="uk-form-controls uk-form-controls-text">
<input class="uk-input" id="form-horizontal-text" type="text" name='ans[]'>
</div>
<div class="uk-form-label">B</div>
<div class="uk-form-controls uk-form-controls-text">
<input class="uk-input" id="form-horizontal-text" type="text" name='ans[]'>
</div>
<div class="uk-form-label">C</div>
<div class="uk-form-controls uk-form-controls-text">
<input class="uk-input" id="form-horizontal-text" type="text" name='ans[]'>
</div>
<div class="uk-form-label">D</div>
<div class="uk-form-controls uk-form-controls-text">
<input class="uk-input" id="form-horizontal-text" type="text" name='ans[]'>
</div>
<div class="uk-form-label">Correct Answer:</div>
<div class="uk-form-controls">
<select class="uk-select" id="form-stacked-select">
<option value=''>A</option>
<option value=''>B</option>
<option value=''>C</option>
<option value=''>D</option>
</select>
</div>
<div uk-form-custom>
<input class="uk-button uk-button-default" type="submit" name='submit' tabindex="-1" value='Save & Continue'>
</div>
</div>
</fieldset>
</form>
</div>
</body>
</html>
as kiks73 mentioned, you can assign values to the option of the Select and POST the selected one to your database as correct answer ID.
<html>
<select class="uk-select" id="form-stacked-select" name="correctAnswer">
<option value='1'>A</option>
<option value='2'>B</option>
<option value='3'>C</option>
<option value='4'>D</option>
</select>
</html>
If you select A, the value "1" would be sent to your database as correct answer (as long as you correct the SQL part in your php.
EDIT:
I got your question a bit late, sorry.
you need to POST the select aswell in order to get the nessecary information about the correct answer. You could try something like that:
<?php
//just a counter
$i = 1;
//correct boolean 1 or 0
$bool = 0;
if (isset($_POST['submit'])) {
include("connect.php");
$newquest = $conn->real_escape_string($_POST['question']);
$insertquest = "INSERT INTO q_questions(quiz_id, question)
VALUES ('$quiz_id', '$newquest')";
$resultquest = $conn->query($insertquest);
$quest_id = $conn -> insert_id;
if (!$resultquest) {
echo $conn->error;
}
foreach ($_POST['ans'] as $ans) {
//get the value of the selected answer
$correctAnswer = $_POST['correctAnswer'];
//check if the selected one matches with our counter
if($i == $correctAnswer)
{
$bool = 1;
}
else
{
$bool = 0;
}
$answers = $conn->real_escape_string($ans);
$insertans = "INSERT INTO q_answers (question_id, answer, correct) VALUES ('$quest_id', '$answers', $bool)";
$resultans = $conn ->query($insertans);
if (!$resultans) {
echo $conn->error;
} else {
header("Location: managequiz.php?quizid=$quiz_id");
}
$i ++;
} //END OF FOREACH LOOP
}
?>
If you POST the whole form, you can use anything in it. i made an ugly loop, which checks each time you instert an answer to your SQL DB, if this one is selected.

Dynamic input and add it into a database

Hello everybody, likle my title tells I'm making a dynamic input but I have errors and I'm going to cry haha. Seriously I have difficulties to make it. I want to add dynamic input and add value in my database. Here is my code :
<?php
// Connect to the DB
$link = mysqli_connect("localhost","root","","testlp") or die("Error " . mysqli_error($link));
// store in the DB
if(!empty($_POST['ok'])) {
// first delete the records marked for deletion. Why? Because we don't want to process them in the code below
if( !empty($_POST['delete_ids']) and is_array($_POST['delete_ids'])) {
// you can optimize below into a single query, but let's keep it simple and clear for now:
foreach($_POST['delete_ids'] as $id) {
$sql = "DELETE FROM recherche WHERE id=$id";
$link->query($sql);
}
}
// adding new recherche
if(!empty($_POST['name'])) {
// ( $i = 0; $i < count($_POST['name']); $i++)
{
$sql = "INSERT INTO recherche (name) VALUES ".$_POST['name'][$i];
$link->query($sql);
}
}
}
// select existing recherche here
$sql="SELECT * FROM recherche ORDER BY id";
$result = $link->query($sql);
?>
<html>
<head>
<title>Simple example of dynamically adding rows with jQuery</title>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.js"></script>
</head>
<body>
<div style="width:90%;margin:auto;">
<h1>Simple example of dynamically adding rows with jQuery</h1>
<form method="post">
<div id="itemRows">
Item name: <input type="text" name="add_name" /> <input onclick="addRow(this.form);" type="button" value="Add row" /> (This row will not be saved unless you click on "Add row" first)
<?php
// let's assume you have the product data from the DB in variable called $recherche
while($product = mysqli_fetch_array($result)): ?>
<p id="oldRow<?=$product['id']?>"> Item name: <input type="text" name="name<?=$product['id']?>" value="<?=$product['name']?>" /> <input type="checkbox" name="delete_ids[]" value="<?=$product['id']?>"> Mark to delete</p>
<?php endwhile;?>
</div>
<p><input type="submit" name="ok" value="Save Changes"></p>
</form>
</div>
<script type="text/javascript">
var rowNum = 0;
function addRow(frm) {
rowNum ++;
var row = '<p id="rowNum'+rowNum+'">Item name: <input type="text" name="name[]" value="'+frm.add_name.value+'"> <input type="button" value="Remove" onclick="removeRow('+rowNum+');"></p>';
jQuery('#itemRows').append(row);
frm.add_qty.value = '';
frm.add_name.value = '';
}
function removeRow(rnum) {
jQuery('#rowNum'+rnum).remove();
}
</script>
</body>
</html>
I've problem in my loop and I get this error :
Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result,
boolean given in C:\wamp\www\testing\dynamic-form-fields.html.php on
line 51 This is the line 51 in the previous code
while($product = mysqli_fetch_array($result)): ?>
<p id="oldRow<?=$product['id']?>"> Item name: <input type="text" name="name<?=$product['id']?>" value="<?=$product['name']?>" /> <input type="checkbox" name="delete_ids[]" value="<?=$product['id']?>"> Mark to delete</p>
<?php endwhile;?>
Thanks for support!
EDIT
Here the new part of the code you guys helped me with : but nothing happens when I submit to the database. I checked in phpmyadmin of my database.
<?php
// Connect to the DB
$link = mysqli_connect("localhost","root","","testlp") or die("Error " . mysqli_error($link));
// store in the DB
if(!empty($_POST['ok'])) {
// first delete the records marked for deletion. Why? Because we don't want to process them in the code below
if( !empty($_POST['delete_ids']) and is_array($_POST['delete_ids'])) {
foreach($_POST['delete_ids'] as $id) {
$sql = "DELETE FROM recherche WHERE id=$id";
$link->query($sql);
}
}
// adding new recherche
if(!empty($_POST['name'])) {
foreach($_POST['name'] as $name)
{
//escape special characters from inputed "name" to prevent SQL injection.
$sql = "INSERT INTO recherche (name) VALUES ".mysqli_real_escape_string($link,$name);
$link->query($sql);
}
}
}
// select existing recherche here
$sql="SELECT * FROM recherche ORDER BY id";
$result = $link->query($sql);
?>
<html>
<head>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.js"></script>
</head>
<body>
<div style="width:90%;margin:auto;">
<form method="post">
<div id="itemRows">
Item name: <input type="text" name="add_name" /> <input onclick="addRow(this.form);" type="button" value="Add row" /> (This row will not be saved unless you click on "Add row" first)
<?php
if($result!=false && mysqli_num_rows($result)>0){
while($product = mysqli_fetch_array($result)): ?>
<p id="oldRow<?=$product['id']?>"> Item name: <input type="text" name="name<?=$product['id']?>" value="<?=$product['name']?>" /> <input type="checkbox" name="delete_ids[]" value="<?=$product['id']?>"> Mark to delete</p>
<?php endwhile;
}
?>
</div>
<p><input type="submit" name="ok" value="Save Changes"></p>
</form>
</div>
<script type="text/javascript">
var rowNum = 0;
function addRow(frm) {
rowNum ++;
var row = '<p id="rowNum'+rowNum+'">Item name: <input type="text" name="name[]" value="'+frm.add_name.value+'"> <input type="button" value="Remove" onclick="removeRow('+rowNum+');"></p>';
jQuery('#itemRows').append(row);
frm.add_qty.value = '';
frm.add_name.value = '';
}
function removeRow(rnum) {
jQuery('#rowNum'+rnum).remove();
}
</script>
</body>
</html>
Here finaly are the result with great guys in this forum !
Feel free to edit or make whatever you want with this code!
<?php
// Connect to the DB
$link = mysqli_connect("localhost","root","","testlp") or die("Error " . mysqli_error($link));
// store in the DB
if(!empty($_POST['ok'])) {
// first delete the records marked for deletion. Why? Because we don't want to process them in the code below
if( !empty($_POST['delete_ids']) and is_array($_POST['delete_ids'])) {
foreach($_POST['delete_ids'] as $id) {
$sql = "DELETE FROM recherche WHERE id=$id";
$link->query($sql);
}
}
// adding new recherche
if(!empty($_POST['name'])) {
foreach($_POST['name'] as $name)
{
//escape special characters from inputed "name" to prevent SQL injection.
$sql = "INSERT INTO recherche (name) VALUES ('".mysqli_real_escape_string($link,$name)."')";
$link->query($sql);
}
}
}
// select existing recherche here
$sql="SELECT * FROM recherche ORDER BY id";
$result = $link->query($sql);
?>
<html>
<head>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.js"></script>
</head>
<body>
<div style="width:90%;margin:auto;">
<form method="post">
<div id="itemRows">
Item name: <input type="text" name="add_name" /> <input onclick="addRow(this.form);" type="button" value="Add row" /> (This row will not be saved unless you click on "Add row" first)
<?php
if($result!=false && mysqli_num_rows($result)>0){
while($product = mysqli_fetch_array($result)): ?>
<p id="oldRow<?=$product['id']?>"> Item name: <input type="text" name="name<?=$product['id']?>" value="<?=$product['name']?>" /> <input type="checkbox" name="delete_ids[]" value="<?=$product['id']?>"> Mark to delete</p>
<?php endwhile;
}
?>
</div>
<p><input type="submit" name="ok" value="Save Changes"></p>
</form>
</div>
<script type="text/javascript">
var rowNum = 0;
function addRow(frm) {
rowNum ++;
var row = '<p id="rowNum'+rowNum+'">Item name: <input type="text" name="name[]" value="'+frm.add_name.value+'"> <input type="button" value="Remove" onclick="removeRow('+rowNum+');"></p>';
jQuery('#itemRows').append(row);
frm.add_qty.value = '';
frm.add_name.value = '';
}
function removeRow(rnum) {
jQuery('#rowNum'+rnum).remove();
}
</script>
</body>
</html>
Don't ever assume you have data in $result.test it before processing it.
<?php
if($result!=false && mysqli_num_rows($result)>0){
while($product = mysqli_fetch_array($result)): ?>
<p id="oldRow<?=$product['id']?>"> Item name: <input type="text" name="name<?=$product['id']?>" value="<?=$product['name']?>" /> <input type="checkbox" name="delete_ids[]" value="<?=$product['id']?>"> Mark to delete</p>
<?php endwhile;
}
?>
EDIT
FIX THIS PART IN YOUR CODE, to insert multiple rows of form submit
// adding new recherche
if(!empty($_POST['name'])) {
foreach($_POST['name'] as $name)
{
//escape special characters from inputed "name" to prevent SQL injection.
$sql = "INSERT INTO recherche (name) VALUES ('".mysqli_real_escape_string($link,$name)."')";
$link->query($sql);
}
}

submit button doesnt work

I have this piece of code that i cant get the submit button to work properly
please help me. I have prepared 3 buttons which i havent worked on the action yet. But the button doesnt work even when i Just want to echo something
<?php
require_once '../dbinfo.inc.php';
session_start();
// CHECK IF THE USER IS LOGGED ON ACCORDING
// TO THE APPLICATION AUTHENTICATION
if(!isset($_SESSION['username'])){
echo <<< EOD
<h1>You are UNAUTHORIZED !</h1>
<p>INVALID usernames/passwords<p>
<p>LOGIN PAGE<p>
EOD;
exit;
}
// GENERATE THE APPLICATION PAGE
$conn = oci_pconnect(ORA_CON_UN, ORA_CON_PW, ORA_CON_DB);
// 1. SET THE CLIENT IDENTIFIER AFTER EVERY CALL
// 2. USING UNIQUE VALUE FOR BACK END USER
oci_set_client_identifier($conn, $_SESSION['username']);
$username = htmlentities($_SESSION['username'], ENT_QUOTES);
if (isset($_POST["ajax"]) && $_POST["ajax"] == 1){
$sql = "SELECT QTY FROM FABRICATION WHERE HEAD_MARK = '{$_POST["hm"]}'";
$cutting_sql = "SELECT CUTTING FROM FABRICATION WHERE HEAD_MARK = '{$_POST["hm"]}'";
$assembly_sql = "SELECT ASSEMBLY FROM FABRICATION WHERE HEAD_MARK = '{$_POST["hm"]}'";
$welding_sql = "SELECT WELDING FROM FABRICATION WHERE HEAD_MARK = '{$_POST["hm"]}'";
$drilling_sql = "SELECT DRILLING FROM FABRICATION WHERE HEAD_MARK = '{$_POST["hm"]}'";
$finishing_sql = "SELECT FINISHING FROM FABRICATION WHERE HEAD_MARK = '{$_POST["hm"]}'";
$stid = oci_parse($conn, $sql);
$stid_cutting = oci_parse($conn, $cutting_sql);
$stid_assembly = oci_parse($conn, $assembly_sql);
$stid_welding = oci_parse($conn, $welding_sql);
$stid_drilling = oci_parse($conn, $drilling_sql);
$stid_finishing = oci_parse($conn, $finishing_sql);
// The defines MUST be done before executing
oci_define_by_name($stid, 'QTY', $qty);
oci_execute($stid);
oci_define_by_name($stid_cutting, 'CUTTING', $cutting);
oci_execute($stid_cutting);
oci_define_by_name($stid_assembly, 'ASSEMBLY', $assembly);
oci_execute($stid_assembly);
oci_define_by_name($stid_welding, 'WELDING', $welding);
oci_execute($stid_welding);
oci_define_by_name($stid_drilling, 'DRILLING', $drilling);
oci_execute($stid_drilling);
oci_define_by_name($stid_finishing, 'FINISHING', $finishing);
oci_execute($stid_finishing);
// Each fetch populates the previously defined variables with the next row's data
oci_fetch($stid);
oci_fetch($stid_cutting);
oci_fetch($stid_assembly);
oci_fetch($stid_welding);
oci_fetch($stid_drilling);
oci_fetch($stid_finishing);
//echo quantity to the screen
echo "<b><font size='10'>".$qty."</font></b></br>";
if ($cutting == $qty){
echo "<p><b><font color='#FF8566' size='5'>CUTTING COMPLETED</font></b></p>";
} else {
$maxcutting = $qty - $cutting;
echo "<input id='cutting' name='cutting' type='number' min = '0' max = '$maxcutting' placeholder='CUTTING PROGRESS TODAY' class='input'/>";
}
if ($assembly == $qty){
echo "<p><b><font color='#FF8566' size='5'>ASSEMBLY COMPLETED</font></b></p>";
} else {
$maxassembly = $qty - $assembly;
echo "<input id='assembly' name='assembly' type='number' min = '0' max = '$maxassembly' placeholder='ASSEMBLY PROGRESS TODAY' class='input'/>";
}
if ($welding == $qty){
echo "<p><b><font color='#FF8566' size='5'>WELDING COMPLETED</font></b></p>";
} else {
$maxwelding = $qty - $welding;
echo "<input id='welding' name='welding' type='number' min = '0' max = '$maxwelding' placeholder='WELDING PROGRESS TODAY' class='input'/>";
}
if ($drilling == $qty){
echo "<p><b><font color='#FF8566' size='5'>DRILLING COMPLETED</font></b></p>";
} else {
$maxdrilling = $qty - $drilling;
echo "<input id='drilling' name='drilling' type='number' min = '0' max = '$maxdrilling' placeholder='DRILLING PROGRESS TODAY' class='input'/>";
}
if ($finishing == $qty){
echo "<p><b><font color='#FF8566' size='5'>FINISHING COMPLETED</font></b></p>";
} else {
$maxfinishing = $qty - $finishing;
echo "<input id='finishing' name='finishing' type='number' min = '0' max = '$maxfinishing' placeholder='FINISHING PROGRESS TODAY' class='input'/>";
}
echo '<section></br></br></br>';
echo ' <input type="submit" value="SUBMIT PROGRESS" class="button red" />';
echo ' <input type="reset" value="RESET FIELDS" class="button" /></br>';
echo ' <input type="submit" value="GO TO PAINTING" name="paint" class="button green" /></section>';
die;}
if (isset($_POST['submit'])){
echo $cutting;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<title> Update Fabrication Progress</title>
<link type="text/css" rel="stylesheet" href="../css/goldenform/golden-forms.css"/>
<link type="text/css" rel="stylesheet" href="../css/goldenform/font-awesome.min.css"/>
<script type="text/javascript">
function OnSelectionChange (select) {
var selectedOption = select.options[select.selectedIndex];
//some ajax checkpoint
//alert ("The selected option is " + selectedOption.value);
jQuery.ajax({
url: location.href,
data: {'hm':selectedOption.value, 'ajax':1},
type: "POST",
success: function( data ) {
jQuery("#lbl_qty").html(data);//PRINT QTY TO THE SCREEN
}
});
//some ajax checkpoint
//alert('after ajax');
}
</script>
<script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
</head>
<body class="bg-wooden">
<div class="gforms">
<div class="golden-forms wrapper">
<form>
<div class="form-title">
<h2>FABRICATION UPDATE</h2>
</div><!-- end .form-title section -->
<div class="form-enclose">
<div class="form-section">
<fieldset>
<legend>&nbsp Select HEADMARK and the details will be shown <span class="bubble blue">1</span></legend>
<section>
<div class="row">
<div class="col4 first">
<label for="headmark" class="lbl-text tleft">HEADMARK :</label>
</div><!-- end .col4 section -->
<div class="col8 last">
<!-- POPULATED DROPDOWN LIST FROM THE DB -->
<label for="headmark" class="lbl-ui select">
<?php
$sql_hm_comp = 'SELECT HEAD_MARK FROM FABRICATION';
$result = oci_parse($conn, $sql_hm_comp);
oci_execute($result);
echo '<SELECT name="headmark" id="headmark" onchange="OnSelectionChange(this)">'.'<br>';
echo '<OPTION VALUE=" ">'."".'</OPTION>';
while($row = oci_fetch_array($result,OCI_ASSOC)){
$HM = $row ['HEAD_MARK'];
echo "<OPTION VALUE='$HM'>$HM</OPTION>";
}
echo '</SELECT>';
?>
</label>
</div>
</div>
</section><!-- END OF DROPDOWN LIST -->
<section>
<div class="row">
<div class="col4 first">
<label for="lnames" class="lbl-text tleft">Total Quantity:</label>
</div>
<div class="col8 last">
<!-- VALUE PASSED FROM AJAX PROCESSING -->
<label id='lbl_qty' class='lbl-ui'><font size='3'> </font></label>
</div>
</div>
</section>
</div><!-- end .form-section section -->
</div><!-- end .form-enclose section -->
<div class="form-buttons">
</div><!-- end .form-buttons section -->
</form>
</div><!-- end .golden-forms section -->
</div><!-- end .gforms section -->
<div></div><!-- end section -->
<div></div><!-- end section -->
</body>
</html>
Welcome to SO!
I found two small errors, I think it will do the trick:
Add post method to the form: <form method="post">
Add name attribute at least to one submit button:
<input type="submit" name="submit" value="SUBMIT PROGRESS" class="button red" />
Additionally it is recommended to use JS to determine which submit button has been clicked. For example you can add a hidden element, and modify its value:
echo '<input type="submit" value="GO TO PAINTING" ... onclick="$(\'[name=submit_clicked]\').val(\'no\');" />...';
...
<form method="post">
<input type="hidden" name="submit_clicked" value="yes" />
...
</form>

insert option in a listbox loaded from mysql

Hi guys i have made a listbox with data from a mysql database and now i want to give the user the possibility to insert an option that don't exists. Can anyone tell me how to do that? I want to create a form or another thing that allows the user to introduce a value for a new option and then it appears in listbox and forward get the value to save in mysql database.
Best regards.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="keywords" content="jquery,ui,easy,easyui,web">
<meta name="description" content="easyui help you build your web page easily!">
<link rel="stylesheet" type="text/css" href="jeasyui_src/themes/default/easyui.css">
<link rel="stylesheet" type="text/css" href="jeasyui_src/themes/icon.css">
<link rel="stylesheet" type="text/css" href="jeasyui_src/demo/demo.css">
<script type="text/javascript" src="jeasyui_src/jquery.min.js"></script>
<script type="text/javascript" src="jeasyui_src/jquery.easyui.min.js"></script>
</head>
<body>
<script language='Javascript' type='text/javascript'>
function edit_file()
{
$("#button_file").css("visibility" , "hidden");
$("#file_new").css("visibility" , "visible");
}
</script>
<h3>Coloque aqui a sua revisao tecnica:</h3></br>
<?php
include_once 'acess_db.php';
$query = "select * from faqs_treeview where level=1 order by category_title";
$result = mysql_query($query);
?>
<table border='0'>
<tr>
<td>
<form method="POST" name="form1" id="t1" style="visibility: visible;">
<select name="cat_1" style="visibility: visible;">
<option>Selecione a categoria</option>
<?php
while($row = mysql_fetch_array($result))
{
$id = $row["id_category"];
$name = $row["category_title"];
echo "<option value='$id'>".$name."</option>";
}
?>
</select>
<input type="submit" name="submit1" onclick="open2();">
</form>
<?php
if(isset($_POST["cat_1"]))
{
// echo $_POST["cat_1"];
$id2 = $_POST["cat_1"];
$query1 = "select * from faqs_treeview where high_level=$id2";
$result1 = mysql_query($query1);
$form_visible = "visible";
}
else
{
$form_visible = "hidden";
}
?>
</td>
<td>
<form method="POST" name="myform2" id="t2" style="visibility: <?= $form_visible ?>">
<select name="cat_2" >
<option>Selecione a sub-categoria</option>
<?php
while($row1 = mysql_fetch_array($result1))
{
$id = $row1["id_category"];
$name = $row1["category_title"];
echo "<option value='$id'>".$name."</option>";
}
?>
</select>
<input type="submit" name="submit2" onclick="open3();">
<input type="hidden" name="cat_1" value="<?= $_POST["cat_1"]?>">
</form>
</td>
<?php
//echo $_POST["cat_2"];
if(isset($_POST["cat_2"]) )
{
$id3 = $_POST["cat_2"];
$query2 = "select * from faqs_treeview where high_level=$id3";
$result2 = mysql_query($query2);
$form_visible = "visible";
}
else
{
$form_visible = "hidden";
}
?>
<td>
<form method="POST" name="myform3" id="t3" style="visibility: <?= $form_visible ?>">
<select name="cat_3" >
<option>Selecione a sub-sub-categoria</option>
<?php
while($row2 = mysql_fetch_array($result2))
{
$id = $row2["id_category"];
$name = $row2["category_title"];
echo "<option value='$id'>".$name."</option>";
}
?>
</select>
<input type="submit" name="submit3" onclick="closeall();">
<input type="hidden" name="cat_1" value="<?= $_POST["cat_1"]?>">
<input type="hidden" name="cat_2" value="<?= $_POST["cat_2"]?>">
</form>
</td>
</tr>
</table>
You could use AJAX for it. I see you use jQuery, so a simple get or post-request should do the trick.
Here: jQuery .get you will find some examples on how to do this. After the item has been added to the database you can use jQuery to add it to your select-box.

javascript to reference input IDs in php loop and pass values back to same input ID

I have a form which is essentially an autocomplete input box. I can get this to work perfectly for a single text box. What I need to do is create unique input boxes by using a php for loop. This will use the counter $i to give each input box a unique name and id.
The problem is that the unique value of the input box needs to be passed to the javascript. this will then pass the inputted data to the external php page and return the mysql results.
As mentioned I have this working for a single input box but need assistance with passing the correct values to the javascript and returning it to correct input box.
existing code for working solution (first row works only, all other rows update first row input box)
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
function lookup(inputString) {
if(inputString.length == 0) {
// Hide the suggestion box.
$('#suggestions').hide();
} else {
$.post("autocompleteperson.php", {queryString: ""+inputString+""}, function(data){
if(data.length >0) {
$('#suggestions').show();
$('#autoSuggestionsList').html(data);
}
});
}
} // lookup
function fill(thisValue) {
$('#inputString').val(thisValue);
setTimeout("$('#suggestions').hide();", 200);
}
</script>
</head>
<body>
<form name="form1" id="form1" action="addepartment.php" method="post">
<table>
<? for ( $i = 1; $i <=10; $i++ ) { ?>
<tr>
<td> <? echo $i; ?></td>
<td>
<div>
<input type="text" size="30" value="" id="inputString" onkeyup="lookup(this.value);" onblur="fill();" />
</div>
<div class="suggestionsBox" id="suggestions" style="display: none;">
<img src="upArrow.png" style="position: relative; top: -12px; left: 20px;" alt="upArrow" />
<div class="suggestionList" id="autoSuggestionsList">
</div>
</div>
</td>
</tr>
<? } ?>
</table>
</body>
</html>
code for autocompleteperson.php is:
$query = $db->query("SELECT fullname FROM Persons WHERE fullname LIKE '$queryString%' LIMIT 10");
if($query) {
while ($result = $query ->fetch_object()) {
echo '<li onClick="fill(\''.$result->fullname.'\');">'.$result->fullname.'</li>';
}
}
in order to get it to work for all rows, I include the counter $i in each of the file names as below:
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
function lookup(inputString<? echo $i; ?>) {
if(inputString<? echo $i; ?>.length == 0) {
// Hide the suggestion box.
$('#suggestions<? echo $i; ?>').hide();
} else {
$.post("autocompleteperson.php", {queryString: ""+inputString<? echo $i; ?>+""}, function(data){
if(data.length >0) {
$('#suggestions<? echo $i; ?>').show();
$('#autoSuggestionsList<? echo $i; ?>').html(data);
}
});
}
} // lookup
function fill(thisValue) {
$('#inputString<? echo $i; ?>').val(thisValue);
setTimeout("$('#suggestions<? echo $i; ?>').hide();", 200);
}
</script>
</head>
<body>
<form name="form1" id="form1" action="addepartment.php" method="post">
<table>
<? for ( $i = 1; $i <=10; $i++ ) { ?>
<tr>
<td> <? echo $i; ?></td>
<td>
<div>
<input type="text" size="30" value="" id="inputString<? echo $i; ?>" onkeyup="lookup(this.value);" onblur="fill();" />
</div>
<div class="suggestionsBox" id="suggestions<? echo $i; ?>" style="display: none;">
<img src="upArrow.png" style="position: relative; top: -12px; left: 20px;" alt="upArrow" />
<div class="suggestionList" id="autoSuggestionsList<? echo $i; ?>">
</div>
</div>
</td>
</tr>
<? } ?>
</table>
</body>
</html>
The autocomplete suggestion works (although always shown on first row) but when selecting the data always returns to row 1, even if input was on row 5. I have a feeling this has to do with the fill() but not sure? is it due the the autocomplete page code? or does the fill referencing ThisValue have something to do with it.
example of this page (as above) can be found here
Thanks for the assistance, much appreciated.
UPDATE - LOLO
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
function lookup(i, inputString) {
if(inputValue.length == 0) {
// Hide the suggestion box.
$('#suggestions' + i).hide();
} else {
$.post("autocompleteperson.php", {queryString: ""+inputString+""}, function(data){
if(data.length >0) {
$('#suggestions' + i).show();
$('#autoSuggestionsList' + i).html(data);
}
});
}
} // lookup
function fill(i, thisValue) {
$('#inputString' + i).val(thisValue);
setTimeout("$('#suggestions' + i).hide();", 200);
}
</script>
</head>
<body>
<form name="form1" id="form1" action="addepartment.php" method="post">
<table>
<? for ( $i = 1; $i <=10; $i++ ) { ?>
<tr>
<td> <? echo $i; ?></td>
<td>
<div>
<input type="text" size="30" value="" id="inputString<?php echo $i; ?>" onkeyup="lookup(this.value);" onblur="fill();" />
</div>
<div class="suggestionsBox" id="suggestions<? echo $i; ?>" style="display: none;">
<img src="upArrow.png" style="position: relative; top: -12px; left: 20px;" alt="upArrow" />
<div class="suggestionList" id="autoSuggestionsList<? echo $i; ?>">
</div>
</div>
</td>
</tr>
<? } ?>
</table>
</body>
</html>
google chrome catched the following errors:
first line on input, second line on loosing focus
You cannot mix JS with PHP. PHP is a server-side language, you can render dynamic JS with that, but after it's rendered you cannot use PHP with JS. First of all you should change your JS functions, I suggest to add parameter like i which will contain input number:
<script type="text/javascript">
function lookup(i, inputString) {
if(inputString.length == 0) {
// Hide the suggestion box.
$('#suggestions' + i).hide();
} else {
$.post("autocompleteperson.php", {queryString: ""+inputString+""}, function(data){
if(data.length >0) {
$('#suggestions' + i).show();
$('#autoSuggestionsList' + i).html(data);
}
});
}
} // lookup
function fill(i, thisValue) {
$('#inputString' + i).val(thisValue);
setTimeout("$('#suggestions" + i + "').hide();", 200);
}
</script>
Then change invokation of this functions and provide number:
<input type="text" size="30" value="" id="inputString<? echo $i; ?>" onkeyup="lookup(<? echo $i; ?>, this.value);" onblur="fill(<? echo $i; ?>);" />
That should be enough.
The problem is with your code is you having same ID for all textbox and each DIV within for loop
<input type="text" size="30" value="" id="inputString" onkeyup="lookup(this.value);" onblur="fill();" />
It should be unique, like this edit.
<input type="text" size="30" value="" id="inputString<?php echo $i; ?>" onkeyup="lookup(this.value);" onblur="fill();" />

Categories