Post Javascript Form into mysql - php

I'm working on an invoicing system. I'm using javascript to add line items as needed however the added line items are not posting when I click submit. I'm thinking it is probably an issue with div somewhere but I cannot seem to find it or get it to work. I'm posting my code for help. Thanks.
Here is my form.
<?php
include $_SERVER['DOCUMENT_ROOT']."/connect.php";
include $_SERVER['DOCUMENT_ROOT']."/includes/header.php";
$result = mysql_query("SELECT company, first, last FROM customer") or die (mysql_error());
?>
<script type="text/javascript">
var counter = 1;
function addInput(div){
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
var newdiv = document.createElement('div');
newdiv.innerHTML = " Entry " + (++counter) + " <br /><table><tr><td>Item: <select name='item[]'>" + xmlhttp.responseText + "</select></td><td>Qty: <input name='quantity[]' type='text' size='5' /></td></tr></table><br />";
}
document.getElementById(div).appendChild(newdiv);
}
xmlhttp.open("GET", "dropdownquery.php", false);
xmlhttp.send();
}
</script>
<form id="createInvoice" method="post" action="docreateinvoice.php">
<table>
<tr><td>Customer</td><td><select name="company">
<?php while($row = mysql_fetch_array($result)) {
echo "<option value=\"".$row['company']."\">".$row['company']." (".$row['first']." ".$row['last'].")</option>";
}
?>
</select></td></tr>
</table>
</div>
</div>
<div id="container">
<div class="content">
<div id="dynamicInput">
Entry 1<br /><table><tr><td>Item: <select name="item[]"><?php $result = mysql_query("SELECT * FROM salesitem"); while($row = mysql_fetch_array($result)) { echo "<option value=\"".$row['name']."\">".$row['name']."</option>";} ?></select></td><td>Qty: <input name="quantity[]" type="text" size="5" /></td></tr></table><br />
</div>
<br /><input type="button" value="Add Line Item" onClick="addInput('dynamicInput');">
</div>
</div>
<div id="container">
<div class="content">
<input type="submit" name="submit" value="Create Invoice" />
</form>
<?php
include $_SERVER['DOCUMENT_ROOT']."/includes/footer.php";
?>
This next piece of code is dropdownquery.php. This is what gets the dropdown box data in the javascript. Big thanks to #NickSlash for figuring this out in the javascript.
<?php
include $_SERVER['DOCUMENT_ROOT']."/connect.php";
$result = mysql_query("SELECT * FROM salesitem");
while($row = mysql_fetch_array($result)) {
echo "<option value=\"".$row['name']."\">".$row['name']."</option>";
}
?>
And finally, this is my docreateinvoice.php which I post to.
<?php
include $_SERVER['DOCUMENT_ROOT']."/connect.php";
$company = mysql_real_escape_string($_POST['company']);
foreach($_POST['item'] as $i => $item)
{
$item = mysql_real_escape_string($item);
$quantity = mysql_real_escape_string($_POST['quantity'][$i]);
//mysql_query("INSERT INTO invoice (company, item, quantity) VALUES ('$company', '".$item."', '".$quantity."') ") or die(mysql_error());
print_r ($company);
print_r ($item);
print_r ($quantity);
}
//echo "<br><font color=\"green\"><b>Invoice added</b></font>";
?>
You might notice in the form that the first entry is not javascript. This does indeed post, just not any additional line items generated from the javascript function.
Thanks for any help.

As I had said in the comments, it seems having divs for display formatting purposes has a negative effect when used within forms utilizing javascript.

Related

Using AJAX and PHP, created form submits wrong the wrong value

***UPDATE
I've done away with table elements as suggested and am using CSS. I've also seen that there's a "form" attribute, I've tried that, too. When I submit, it is still acting as it did before - sending the wrong value because it was sending the whole table. I've updated the below with the updated HTML output and the PHP code. It looks correct, this is my latest attempt. What am I missing?
I am using PHP to create a form for each row of data. I call to PHP via AJAX. The form builds correctly. Each row correctly lists its values and is in its own form. In this example, there are three rows, thus three forms. When I submit a username on the first row, the ID being sent is from the third row. Not sure what is going on.
AJAX call to PHP FORM - Home Page
<script>
window.onload = function signupForm() {
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if(xmlHttp.readyState == 4 && xmlHttp.status == 200) {
document.getElementById("signupForm").innerHTML = this.responseText;
}
}
xmlHttp.open("GET", "ajaxInput.php", true);
xmlHttp.send();
}
</script>
PHP FORM - signupForm.php
<?php
$con=mysqli_connect("localhost","xxxxxx","xxxxxxx","xxxxxxxx");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT id, DATE_FORMAT(startTime, '%b-%d-%Y') as eventDate, endTime FROM events
WHERE now() < endTime");
echo "
<style>
.table { display: table; }
.table>* { display: table-row; }
.table>*>* { display: table-cell; padding: 5px; border-style: inset;}
</style>
<div class='table'>
<div>
<div><b>Event Id</b></div>
<div><b>Date</b></div>
<div><b>#username</b></div>
<div><b>Sign Up!</b></div>
</div>";
while($row = mysqli_fetch_array($result))
{
//echo "<form action='ajaxSignup.php' method='post'>";
echo "<div>";
echo "<div>" . $row['id'] . "</div>";
echo "<div>" . $row['eventDate'] . "</div>";
echo "<div><form id='form" .$row['id']. "' method='post'><input class='formSignup' type='text' name='pi_username' id='pi_username' maxlength='20' placeholder='#username' form='form" .$row['id']. "'></div>";
echo "<div><input class='formSignup' type='hidden' name='event_id' id='event_id' value='" . $row['id'] . "' form='form" .$row['id']. "'>
<input name='submit". $row['id'] . "' type='submit' value='Sign up!' onclick='signup(); return false;'></form></div>";
echo "</div>";
}
//echo "</div>";
echo "</div>";
mysqli_close($con);
?>
The table draws correctly. I've put form tag in various places as well. Below, I'm using the form attribute in the input tags. The table is being drawn with CSS instead of the table elements.
<html>
<head></head>
<body>
<p>Something here</p>
<div id="signupForm">
<style>
.table { display: table; }
.table>* { display: table-row; }
.table>*>* { display: table-cell; padding: 5px; border-style: inset;}
</style>
<div class="table">
<div>
<div><b>Event Id</b></div>
<div><b>Date</b></div>
<div><b>#username</b></div>
<div><b>Sign Up!</b></div>
</div>
<div>
<div>11</div>
<div>Feb-25-2021</div>
<div><input class="formSignup" type="text" name="pi_username" id="pi_username" maxlength="20" placeholder="#username" form="form11"></div>
<div>
<input class="formSignup" type="hidden" name="event_id" id="event_id" value="11" form="form11">
<form id="form11" method="post"><input name="submit11" type="submit" value="Sign up!" onclick="signup(); return false;"></form>
</div>
</div>
<div>
<div>12</div>
<div>Feb-26-2021</div>
<div><input class="formSignup" type="text" name="pi_username" id="pi_username" maxlength="20" placeholder="#username" form="form12"></div>
<div>
<input class="formSignup" type="hidden" name="event_id" id="event_id" value="12" form="form12">
<form id="form12" method="post"><input name="submit12" type="submit" value="Sign up!" onclick="signup(); return false;"></form>
</div>
</div>
<div>
<div>13</div>
<div>Feb-27-2021</div>
<div><input class="formSignup" type="text" name="pi_username" id="pi_username" maxlength="20" placeholder="#username" form="form13"></div>
<div>
<input class="formSignup" type="hidden" name="event_id" id="event_id" value="13" form="form13">
<form id="form13" method="post"><input name="submit13" type="submit" value="Sign up!" onclick="signup(); return false;"></form>
</div>
</div>
</div>
</div>
As can be seen in the PHP, each row is its own form. But looking at the Elements in developer tools, the form is closing early. I think this is related to the issue.
Elements
When I enter a username on row one (top row), the username doesn't seem to make it and the ID that does make it is 13 instead of 11.
AJAX Script to process Submit button onclick (Home page)...
<script>
function signup() {
var elements = document.getElementsByClassName("formSignup");
var formData = new FormData();
for(var i=0; i<elements.length; i++) {
formData.append(elements[i].name, elements[i].value);
}
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if(xmlHttp.readyState == 4 && xmlHttp.status == 200) {
document.getElementById("signupSuccess").innerHTML = this.responseText;
}
}
xmlHttp.open("post", "ajaxSignup.php");
xmlHttp.send(formData);
}
</script>
PHP code on signup page. I have some echos early on that show the id is 13, not 11 and no username is present.
<?php
$pi_username = $high_score = $attempts = $event_id = "";
echo $event_id;
echo $pi_username;
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$pi_username = test_input($_POST["pi_username"]);
$event_id = test_input($_POST["event_id"]);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
echo $event_id;
echo $pi_username;
if($_SERVER["REQUEST_METHOD"] == "POST") {
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "xxxxxxx", "xxxxxxx", "xxxxxx");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
//check if user has already signed up for event
$alreadySignedUp = mysqli_query($link, "SELECT count(*) AS total FROM signup WHERE event_id = $event_id AND pi_username = '$pi_username'");
while ($worm = mysqli_fetch_array($alreadySignedUp)){
//echo $bird['total'];
if($worm['total'] >= 1 ){
echo "You have already signed up for this event.";
echo $event_id;
echo $pi_username;
echo $worm['total'];
mysqli_close($link);
return;
}
}
// Attempt insert query execution
$sql = "INSERT INTO signup (event_id, pi_username) VALUES ('$event_id', '$pi_username')";
if(mysqli_query($link, $sql)){
echo "You have been successfully added to event ".$event_id."!";
mysqli_close($link);
return;
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
}
else {
echo "Don't forget to submit your high scores before you leave!";
}
?>
Where am I going wrong?
The signup() function was looking for elements with the same class (formSignup). All input fields had the same class name and were all being sent to the signup() function. I've updated the class name to be unique for each row. Now only a single row is being sent. The signup() function was updated to:
window.onload = function signupForm(getClass) {
var xmlHttp = new XMLHttpRequest(getClass);
Example of an input field with a unique class name:
<input class='formSignup" .$row['id']. "' type='hidden' name='event_id' id='event_id' value='" . $row['id'] . "' form='form" .$row['id']. "'>
Removed table elements and created a CSS-styled 'table' as suggested. All working now. Question updated with CSS-Styled table.

Dependable select box isn't work

I'm newbie with AJAX, and I found the code solution for my problem in this page, but I can't make it work.
I need that the input #precio changes when I select an option in select #producto.
I have this code:
<form action="actualizarprod_pr.php" method="post">
<input type="text" name="producto" value="" placeholder="Producto" list="productolist" />
<datalist id="productolist">
<select id="productos" style="display: none;">
<?php
$query = "SELECT * FROM lista_precios";
$query_ej = mysqli_query($conexion, $query);
while($registro = mysqli_fetch_array($query_ej)){
echo "<option value='" . $registro['producto'] .
"'</option>";
}
?>
</select>
</datalist>
<input type="text" id="precio" name="precio" placeholder="Precio">
<input type="submit" name="Actualizar" value="Actualizar">
<input type="submit" name="Borrar" value ="Borrar">
</form>
Script:
<script type="text/javascript">
$(document).ready(function(){
$("#productos").change(function(){
var producto=$(this).val();
$.ajax({
type:"post",
url:"cargaselect.php",
data:"producto="+producto,
success:function(data){
$("#precio").val(data);
}
});
});
});
</script>
cargaselect.php:
<?php
session_start();
include("conexion.php");
if(isset($_SESSION["id_usuario"])){
$producto=$_POST["producto"];
$result = mysqli_query($conexion,
"select * FROM lista_precios WHERE producto =". $producto ." ");
echo $result[precio];
} else {
header("location: login.php");
}
?>
This line is not formatted correctly
echo $result[precio];
should be
echo $result['precio'];
What does $result['precio'] return?
If its an array of results you might need to use
$result[0]['precio'] perhaps instead

Create a Chain of drop-down list that base on the input of the previous one form the database in php

i am using database to populate the dorpdown lis. now when i select the option from the first dynamic populated drom down list i want to use it to populate another dropdown list and based on that selection third dromdown list.
Here's the code i am working on,
<html>
<?php
include './config.php';
?>
<head>
<meta charset="UTF-8">
<title></title>
<SCRIPT>
$(".dropdown").hide();
$("#testcasedata").on("change", function() {
$(".dropdown").hide();
var value = $("#testcasedata").val();
$("#dropdown" + value).show();
});
</script>
</head>
<body>
<form method="POST" action="createTestCase.php">
// This is the first dropdown list
// It will return testsuite_id in dropdownlist
<?php
$sqll="SELECT testsuite_id FROM assigned_testsuite_tester Where Tester_name = 'Pritesh'";
echo "<select class='form-control' name='testsuite'>";
echo "<option value=''>Select One</option>";
foreach ($conn->query($sqll) as $row){
echo '<option value="'.$row['testsuite_id'].'">'.$row['testsuite_id'].'</option>';
}
echo "</select>";
?>
<input type="submit" name="submit" />
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
//testsuite_id will be the input variable for the second dropdownlist
// the second dropdown list will populate with testcase_id.
$testsuite = filter_input(INPUT_POST, 'testsuite');
echo $testsuite;
if($testsuite != ''){
$sqll="SELECT Testcase_id FROM assigned_testsuite_testcase Where testsuite_id = '$testsuite'";
echo "<select name='testcasedata' id='testcasedata' >";
echo "<option value=''>Select One</option>";
foreach ($conn->query($sqll) as $row){
echo '<option value="'.$row['Testcase_id'].'">'.$row['Testcase_id'].'</option>';
}
echo "</select>";
}
// with use of test case id i am retrieving the Product_id
$testcase = filter_input(INPUT_POST, 'testcase');
$sqll="SELECT Product_id FROM Testcase_master Where Testcase_id = '$testcase'";
$productid='';
foreach ($conn->query($sqll) as $row){
$productid = $row['Product_id'];
}
//now product id must be the input for the third dropdownlist.
if($productid != ''){
$sqll="SELECT circle.circle_id,circle.Circle_name FROM circle INNER JOIN assigned_circle_product ON assigned_circle_product.`Product_id` = '$productid'";
echo "<select class='dropdown' name='circledata' id='circledata'>";
echo "<option value=''>Select One</option>";
foreach ($conn->query($sqll) as $row){
echo '<option value="'.$row['Circle_id'].'">'.$row['Circle_name'].'</option>';
}
echo "</select>";
}
}
?>
</body>
i was able to populate the first drop-down list and based on that populate the second drop-down list.but having problem for populating third one.
I was browsing through similar questions and find out that i need to use jquery/JavaScript to do that.I don't know that much about jquery but have inserted code for that too but still having problem to populating the third drop down list.
I am stuck at this point.Please give me some guidance.
I have been learning Javascript/Jquery and this is what i have done.
I don't know if it's a correct way or not. please look and tell me if i can do more to improve code.
First i have devided whole program into three seprate PHP files.
1.Main PHP File
<!DOCTYPE html>
<html>
<?php
include 'header.php';
include 'footer.php';
include './config.php';
?>
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript">
function showCircle(str) {
if (str=="") {
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","GetProduct.php?q="+str,true);
xmlhttp.send();
}
function product1(str) {
str1 = document.getElementById("project");
if (str=="") {
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","GetTestcase.php?prod="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="page-wrapper">
<div class="row">
<div class="col-lg-12">
<h1 class="page-header">Add Circle to Product</h1>
</div>
<!-- /.col-lg-12 -->
</div>
<div class="row">
<div class="col-lg-12">
<div class="panel panel-default">
<div class="panel-heading">
Select the circles where you want your product to test:
</div>
<div class="panel-body">
<div class="dataTable_wrapper">
<form action="circlrproduct.php" method="GET">
<div class="col-lg-6">
<div class="form-group">
<label>Project Name</label>
<?php
$sqll="SELECT Project_id,Project_title FROM project_master";
echo "<select class='form-control' name='project' onchange='showCircle(this.value)'>";
echo "<option value=''>Select One</option>";
foreach ($conn->query($sqll) as $row){
echo "<option value=$row[Project_id]>$row[Project_title]</option>";
}
echo "</select>";
?>
</div>
<div class="form-group">
<div id="txtHint"></div>
<!--<div id="txtHint1"></div>-->
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary" name="submit" value="submit">Submit</button>
<button type="reset" class="btn btn-primary">Reset</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
First i select the project from the drop down list and at at the time of selection a ajax call will be made to get the product.
GetProduct.php
if(isset($_GET['q'])){
$q = (string)filter_input(INPUT_GET,'q');
}else{
// header('Location:AddCircleToProduct.php');
}
$sql2="SELECT Product_id,Product_title FROM product_master where Project_id = '$q'";
$support = $q;
$result = $conn -> query($sql2);
echo "<label>Product Name</label>";
echo "<select class='form-control' name='product' onchange='product1(this.value)'>";
echo "<option value=''>Select One</option>";
while ($row = mysqli_fetch_array($result)){
echo "<option value={$row['Product_id']}>{$row['Product_title']}</option>";
}
echo "</select>";
At the time of product selection one another call is made through Ajax to get the test case.
3.GET Test case
if(isset($_GET['prod'])){
$product = filter_input(INPUT_GET, 'prod');
$query = "select * from testcase_master where Product_id = '$product'";
//echo $query;
echo '<div class="panel-body"><div class="dataTable_wrapper"><table class="table table-striped table-bordered table-hover" id="dataTables-example"">';
echo '<thead><tr><th>SELECT</th><th>Testcase Id</th><th>Testcase Title</th><th>Description</th><th>Created by</th><th>Subscriber Type</th><th>Priority</th></tr></thead><tbody>';
if($results = $conn -> query($query) or die(mysqli_errno($conn))){
while ($row = mysqli_fetch_array($results)) {
echo '<tr class="odd gradeX">';
echo "<td><input type=\"checkbox\" name=\"checkbox[]\" id=\"checkbox[]\" value=\"".$row['Testcase_id']."\" class='form-control'/></td>";
echo "<td>{$row['Testcase_id']}</td><td>{$row['Testcase_title']}</td><td>{$row['Testcase_desc']}</td><td>{$row['Created_by']}</td><td>{$row['Subscriber_type']}</td><td>{$row['Priority']}</td>";
echo '</tr>';
}
echo '</tbody></table></div></div>';
} else {
echo 'ss' . mysqli_error($conn);
}
}
else{
echo'Sorry You cant access this page Directly.';
}
?>
After getting the list of test case selection of checkbox is made.
4.circledata.php
<?php
include './config.php';
if(isset($_GET['submit'])){
if(isset($_GET['checkbox'])){
if (is_array($_GET['checkbox'])) {
foreach($_GET['checkbox'] as $value){
$q1 = "INSERT INTO tmtool.assigned_circle_product (`Circle_id`, `Product_id`) VALUES ('.$value.','$_SESSION[prod]')";
if($conn -> query($q1) == TRUE){
echo "Data Entered successfully\n";
} else {
echo 'Error' . mysqli_error($conn);
}
}
} else {
$value = $_GET['checkbox'];
echo $value;
}
}
}
?>
And in the last file all the data are commited into the database.
Please tell me if anything i can do to improve my code.
Thank you.

View customer info on select change

I'm creating a page which will allow an admin to select a user from a drop down list, which populates from a database. When the person is selected, the info associated with that person will then be viewed on the page. I already have a select statement which selects all the info and the drop down menu is populating correctly. However, I'm unsure on how to get that selected user's info to display on the page once selected. Would I need to do an entirely different select statement and query which checks which customer was selected? Or is there another way?
customer.php
<div id="view_form" class="view">
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<fieldset>
<label for="viewCustomer">Select Customer</label>
<?php
echo "<select name='selectCust' id='selectCust'>";
echo "<option></option>";
while($row = mysqli_fetch_assoc($custResult)){
$name = "{$row['fName']} {$row['lName']}";
echo "<option>$name</option>";
}
echo "</select>";
?>
</fieldset>
</form>
</div>
viewUser.php
if(isset($search)){
$select = "SELECT * FROM $cust WHERE acctNum='{$search}'";
$result = mysqli_query($db, $select);
if(mysqli_num_rows($result) > 0){
if($row = mysqli_fetch_assoc($result)){
$acct = "{$row['acctNum']}";
echo $acct;
}
}
}
script.js
$(document).ready(function(){
function searchAjax(){
var search = $('#selectCust').val();
$.post('includes/viewUser.php', {searchUsers: search}, function(data){
$('#view_form').append(data);
})
}
$('#selectCust').on('change', function(ev){
ev.preventDefault();
searchAjax();
})
})
Search.php
<script type="text/javascript "src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script type='text/javascript'>
$(document).ready(function(){
$(".dropdown-users").on("change",function(event){
event.preventDefault();
search_ajax_way();
});
});
function search_ajax_way(){
var search_this=$("dropdown-users").val();
$.post("Ajaxsearch.php", {searchusers : search_this}, function(data){
$(".results").html(data);
})
}
</script>
<div id="view_form" class="view">
<form method="post">
<fieldset>
<label for="viewCustomer">Select Customer</label>
<?php
echo "<select class="dropdown-users">";
echo "<option></option>";
while($row = mysqli_fetch_assoc($custResult)){
$name = "{$row['fName']} {$row['lName']}";
$acct = $row['acctNum'];
echo "<option value="$acct">$name ($acct)</option>";
}
echo "</select>";
?>
</fieldset>
</form>
</div>
<label>Enter</label>
<input type="text" name="search_query" id="search_query" placeholder="What You Are Looking For?" size="50"/>
<input type="<span id="IL_AD1" class="IL_AD">submit</span>" <span id="IL_AD6" class="IL_AD">value</span>="Search" id="button_find" />
<div class="results"></div>
//********************************************************************************************
********************************************************************************************//
Ajaxsearch.php
<?php
$con = mysqli_connect("localhost","my_user","my_password","my_db"); // Enter your information here
$term = $_POST['searchusers']
$term = mysqli_real_escape_string($con, $term);
if($term == "")
echo "Enter Something to search";
else {
$query = mysqli_query($con, "select * from USERDATEBASEHERE where ID = '{$term}' ");
$string = '';
if (mysqli_num_rows($query) > 0) {
if (($row = mysqli_fetch_assoc($query)) !== false) {
$string = "{$row['ID']}";
}
} else {
$string = "This Person does not exist";
}
echo $string;
}
?>
<div id="view_form" class="view">
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<fieldset>
<label for="viewCustomer">Select Customer</label>
<?php
echo "<select name=\"somename\" onchange=\"this.form.submit();\">";
echo "<option value=\"\">Select User</option>";
while($row = mysqli_fetch_assoc($custResult)){
$name = "{$row['fName']} {$row['lName']}";
$acct = $row['acctNum'];
echo '<option value="'.$acct.'">$name ($acct)</option>';
}
echo "</select>";
?>
</fieldset>
</form>
</div>
The options must have some refering value, through which you can retrieve the details of selected user, whenever the value of option is not initiated then the default value of the option will be option's label.

How to make elements of an array appear one at the time after clicking submit button?

I have following code:
<?php
include_once 'init/init.funcs.php';
$pollid=(int) $_GET['pollid'];
$questions = array();
$result = mysql_query('SELECT kysimus FROM kysimused where kysimustik_id="' . $pollid . '"');
while($row = mysql_fetch_assoc($result)) {
$questions[] = $row['kysimus'];
}
$count=count($questions);
$x=0;
while ($x<$count){
echo $questions[$x];
$x+=1;
}
?>
<form method="get">
<input type="submit" value="Submit">
</form>
It takes the questions from the database which have kysimustik_id=poll_id and echos them out. But how could I make it work so questions will appear one at the time and new one appears only after I click "Submit" button?
You can do like the following
<div class="row text-center">
<button type="submit" class="btn btn-lg btn-info">Click Here!</button>
</div>
$(function(){
var values = [
"hi",
"hello",
"nice",
"wonderful"
];
var counter = 0;
$(".btn-lg").on("click", function(){
if(values.length) {
counter = (counter + 1) % values.length;
$('.row.text-center').append(values[counter] + ' ');
}
});
});
In the above example I have used javascript array. you can easily replace it by your php array
<?php
include_once 'init/init.funcs.php';
$pollid=(int) $_GET['pollid'];
if(isset($_POST['QuestionID'])
{
$questionID = $_POST["QuestionID"];
HandleAnswer($pollid,$questionID,$_POST['Answer']);
}
else
{
$questionID = 0;
}
$questions = array();
$result = mysql_query('SELECT kysimus FROM kysimused where kysimustik_id="' . $pollid . '"');
while($row = mysql_fetch_assoc($result)) {
$questions[] = $row['kysimus'];
}
function HandleAnswer(string PollId, string QuestionID, string Answer){
// Implement piece of code that sets the answer in the database,
// I leave this up to you since i have no Idea how your database is structured
}
$questionID++;
$count=count($questions);
if($questionID < $count){
?>
<form method="post" action="mypage?=<?php echo $pollid; ?>">
<?php echo $questions[$questionID]; ?>
<input type="hidden" name="questionID" value="<?php echo $questionID;?>"/>
<input type="text" name="Answer"/>
<input type="submit" value="Submit">
</form>
<?php }else{ ?>
THese were all our questions, thank you for answering!
<?php } ?>
I didn't test the code myself, but I'm pretty sure it works. Note that this is a hightly unsafe way to do this, because you can edit the value of the hidden field with extensions such as firebug.

Categories