Multiple dynamic textfields into mysql db - javascript

Can someone fix my problem here pls. im trying to insert into database from these form below but I cant get it to work
heres the complete form sir:
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title></title>
<script type='text/javascript' src="jquery/jquery-1.8.3.js"></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"> </script>
<link rel="stylesheet" type="text/css" href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css">
<link rel="stylesheet" type="text/css" href="/css/result-light.css">
<style type='text/css'>
.dynatable {
border: solid 1px #000;
border-collapse: collapse;
}
.dynatable th,
.dynatable td {
border: solid 1px #000;
padding: 2px 10px;
width: 170px;
text-align: center;
}
.dynatable .prototype {
display: none;
}
</style>
<script type='text/javascript'>//<![CDATA[
$(function(){
$(document).ready(function () {
var id = 0;
// Add button functionality
$("table.dynatable button.add").click(function () {
id++;
var master = $(this).closest("table.dynatable");
// Get a new row based on the prototype row
var prot = master.find("tr.prototype").clone();
prot.attr("class", "")
prot.find(".id").attr("value", id);
master.find("tbody").append(prot);
});
// Remove button functionality
$("table.dynatable button.remove").live("click", function () {
$(this).parents("tr").remove();
});
$("table.dynatable button.addColumn").click(function () {
var $this = $(this), $table = $this.closest('table')
var columnName = window.prompt("Enter Column name", "");
$('<th>' + columnName +'</th>').insertBefore($table.find('tr').first().find('th:last'))
var idx = $(this).closest('td').index() + 1;
$('<td><input type="text" name="col' + idx + '[]" value="" /</td>').insertBefore($table.find('tr:gt(0)').find('td:last'))
});
});
});//]]>
</script>
</head>
<body>
<table class="dynatable">
<thead>
<tr>
<th><button class="add">Add</button></th>
<form method="post" action="blah.php">
<th>Career Service/RA 1080(BOARD/BAR)</br>
Under Special Laws/CES/CSEE</th>
<th>Rating</th>
<th>Date of Examination/</br>
Conferment</th>
<th>Place of Examination/ Conferment</th>
</tr>
</thead>
<tbody>
<tr class="prototype">
<td><button class="remove">Remove</button></td>
<td><input type="text" name="name[]" value="" /></td>
<td><input type="text" name="rating[]" value="" /></td>
<td><input type="date" name="date[]" value="" /></td>
<td><input type="text" name="place[]" value="" /></td>
</tr>
</tbody>
</table>
<table width="972">
<tr align="center" >
<td width="71" colspan="5"><input type="submit" name="submit"/></td>
</tr>
</form>
</table>
</body>
</html>
Here's my php code it doesn't seem to work correctly. It inserts a blank data except for the id which has the value but the rest is blank data.
PHP CODE:
<?php
$host = 'Localhost';
$username= 'root';
$password= '';
$db_name = 'bfp';
$con = mysql_connect($host,$username,$password) or die ("Cant Connect");
mysql_select_db($db_name) or die ("Cant Select DataBase");
$k=2;//this is for the id value
$name = $_POST['name'];
foreach($name as $names) :
$values=mysql_real_escape_string($names);
$sql="INSERT INTO bfp_personnel_eligibility (id, eligibility_name, rating, doe, poe) VALUES ('{$k}','{$values}', '{$_POST['rating']}', '{$_POST['date']}', '{$_POST['place']}')";
if (!mysql_query($sql,$con)){
die('Error: ' . mysql_error());
}
endforeach;
?>

try this code:
$i = 0;
foreach($name as $names) :
$values=mysql_real_escape_string($names);
$sql="INSERT INTO bfp_personnel_eligibility (id, eligibility_name, rating, doe, poe) VALUES ('{$k}','{$values}', '{$_POST['rating'][$i]}', '{$_POST['date'][$i]}', '{$_POST['place'][$i]}')";
$i++;
if (!mysql_query($sql,$con)){
die('Error: ' . mysql_error());
}
endforeach;
Note: you have to apply mysql_real_escape_string for all values you are passing to query.
Edit:
place your form like this
<body>
<form method="post" action="blah.php">
<table class="dynatable">
.
.
.
.
</table>
</form>
</body>

Related

multiple login to access data for each department only

I have requests table that have fields (id, name, date, department, answer) and (req_res1.php) that display all records from the table, I tried to create multiple login to access this form for each department only. I mean in a login form there are username and password and department name and when user choose user, pass and dept., the form display results for only this department. I tried different things but nothing works.
req_res1.php
<?php
$connect = mysqli_connect('localhost', 'root', '', 'test')or die ( mysqli_error($connect) );
$sSQL= 'SET CHARACTER SET utf8';
mysqli_query($connect,$sSQL)
or die ('Can\'t charset in DataBase');
$query = "SELECT * FROM requests ORDER BY id DESC";
$result = mysqli_query($connect, $query);
?>
<html>
<head>
<title>update and delete records</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="jquery.tabledit.min.js"></script>
<style>
thead, tr {
color:black;
font-size: 14px;
font-weight: bold;
border-collapse: collapse;
border: 1.5px solid black;
}
th {
background-color: #66CCFF;
color: white;
border: 2px solid black;
}
</style>
</head>
<body dir="rtl">
<br />
<div id="header" align="center">
<img id="image1" src="img/egate4.png">
<br />
</div>
<div class="container" style="width:1200px;">
<br />
<div class="table-responsive">
<h3 align="center">requests display</h3><br />
<table id="editable_table" class="table table-bordered table-striped">
<thead>
<tr>
<th>request no</th>
<th>name</th>
<th>date of request</th>
<th>department</th>
<th>status</th>
</tr>
</thead>
<tbody>
<?php
while($row = mysqli_fetch_array($result))
{
echo '
<tr>
<td>'.$row["no"].'</td>
<td>'.$row["name"].'</td>
<td>'.$row["reqdate"].'</td>
<td>'.$row["dept"].'</td>
<td>'.$row["answer"].'</td>
</tr>
';
}
?>
</tbody>
</table>
</div>
</div>
</div>
</body>
</html>
<script>
$(document).ready(function(){
$('#editable_table').Tabledit({
url:'req_res2.php',
columns:{
identifier:[0, "no"],
editable:[[1, 'name'], [2, 'reqdate'], [3, 'dept'],[4, 'answer']]
},
restoreButton:false,
onSuccess:function(data, textStatus, jqXHR)
{
if(data.req_res2 == 'delete')
{
$('#'+data.id).remove();
}
}
});
});
</script>
req_res2.php
<?php
header ('Content-Type: text/html; charset=UTF-8');
$connect = mysqli_connect('localhost', 'root', '', 'test')or die ( mysqli_error($connect) );
$sSQL= 'SET CHARACTER SET utf8';
mysqli_query($connect,$sSQL)
or die ('Can\'t charset in DataBase');
$input = filter_input_array(INPUT_POST);
$name = mysqli_real_escape_string($connect, $input["name"]);
$no = mysqli_real_escape_string($connect, $input["no"]);
$reqdate = mysqli_real_escape_string($connect, $input["reqdate"]);
$answer = mysqli_real_escape_string($connect, $input["answer"]);
if($input["action"] === 'edit')
{
$query = "
UPDATE requests
SET name = '".$name."',
answer = '".$answer."'
WHERE id = '".$input["id"]."'
";
mysqli_query($connect, $query);
}
if($input["action"] === 'delete')
{
$query = "
DELETE FROM requests
WHERE id = '".$input["id"]."'
";
mysqli_query($connect, $query);
}
echo json_encode($input);
?>

multiple buttons on jquery html

There is a problem with the below code. The second button show it does not work. It doesn't open anything.
The problem is for sure the Show ..if I changed it to class , both do not work.
And I would like in each row the text to be left without any margin , but I couldn't fixed it
<!DOCTYPE html>
<html>
<body>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Cafeteria Orders Management System</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<style>
label,
input {
display: block;
}
input.text {
margin-bottom: 12px;
width: 95%;
padding: .4em;
}
fieldset {
padding: 0;
border: 0;
margin-top: 25px;
}
td {
max-width: 120px;
white-space: nowrap;
}
h1 {
font-size: 1.2em;
margin: .6em 0;
}
div#users-contain {
width: 300px;
margin: 20px 0;
}
div#users-contain table {
margin: 1em 0;
border-collapse: collapse;
width: 100%;
}
div#users-contain table td,
div#users-contain table th {
border: 9px solid #eee;
padding: .6em 120px;
text-align: left;
}
.ui-dialog .ui-state-error {
padding: .3em;
}
.validateTips {
border: 1px solid transparent;
padding: 0.3em;
}
</style>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$(function() {
var dialog, form,
// From http://www.whatwg.org/specs/web-apps/current-work/multipage/states-of-the-type-attribute.html#e-mail-state-%28type=email%29
emailRegex = /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+#[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,
name = $("#name"),
email = $("#email"),
password = $("#password"),
allFields = $([]).add(name).add(email).add(password),
tips = $(".validateTips");
function updateTips(t) {
tips
.text(t)
.addClass("ui-state-highlight");
setTimeout(function() {
tips.removeClass("ui-state-highlight", 1500);
}, 500);
}
function checkLength(o, n, min, max) {
if (o.val().length > max || o.val().length < min) {
o.addClass("ui-state-error");
updateTips("Length of " + n + " must be between " +
min + " and " + max + ".");
return false;
} else {
return true;
}
}
function checkRegexp(o, regexp, n) {
if (!(regexp.test(o.val()))) {
o.addClass("ui-state-error");
updateTips(n);
return false;
} else {
return true;
}
}
function addUser() {
var valid = true;
allFields.removeClass("ui-state-error");
valid = valid && checkLength(name, "username", 3, 16);
valid = valid && checkLength(email, "email", 6, 80);
valid = valid && checkLength(password, "password", 5, 16);
valid = valid && checkRegexp(name, /^[a-z]([0-9a-z_\s])+$/i, "Username may consist of a-z, 0-9, underscores, spaces and must begin with a letter.");
valid = valid && checkRegexp(email, emailRegex, "eg. ui#jquery.com");
valid = valid && checkRegexp(password, /^([0-9a-zA-Z])+$/, "Password field only allow : a-z 0-9");
if (valid) {
$("#users tbody").append("<tr>" +
"<td>" + name.val() + "</td>" +
"<td>" + email.val() + "</td>" +
"<td>" + password.val() + "</td>" +
"</tr>");
dialog.dialog("close");
}
return valid;
}
dialog = $("#dialog-form").dialog({
autoOpen: false,
height: 400,
width: 350,
modal: true,
buttons: {
Ok: function() {
dialog.dialog("close");
}
},
close: function() {
form[0].reset();
allFields.removeClass("ui-state-error");
}
});
form = dialog.find("form").on("submit", function(event) {
event.preventDefault();
addUser();
});
$("#create-user").button().on("click", function() {
dialog.dialog("open");
});
});
</script>
</head>
<body>
<div id="dialog-form" title="Order Details">
<p class="validateTips">Spicy Sandwitch</p>
<p class="validateTips">More</p>
<form>
<fieldset>
<label for="name">More Comments</label>
<p class="validateTips">Sandwitch only lettuce</p>
<!-- Allow form submission with keyboard without duplicating the dialog button -->
<input type="submit" tabindex="-1" style="position:absolute; top:-1000px">
</fieldset>
</form>
</div>
<div id="users-contain" class="ui-widget">
<h1>Order List:</h1>
<table id="users" class="ui-widget ui-widget-content">
<thead>
<tr class="ui-widget-header ">
<th>Name/Surname</th>
<th>Address</th>
<th>Telephone</th>
<th>Time/Date</th>
<th>Order Details</th>
<th>Done</th>
</tr>
</thead>
<tbody>
<tr>
</td>
<td>John Doe</td>
<td>Lykavitou 12, 2109 Aglantzia</td>
<td>99123456</td>
<td>21:00 21/11/16</td>
<td>
<button id="create-user">Show</button>
</td>
<td align="center">
<input type="checkbox" class="case" name="case" value="1" />
</tr>
<tr>
</td>
<td>Andreas Georgiou</td>
<td>Grigori Auxentiou 12, 2109 Aglantzia</td>
<td>99654789</td>
<td>20:00 21/11/16</td>
<td>
<button id="create-user">Show</button>
</td>
<td align="center">
<input type="checkbox" class="case" name="case" value="1" />
</tr>
</tbody>
</table>
</div>
</body>
</html>
change in the button attribute id, u cant use more than one id with the same name on your website, you can use class instead of. For example
<button class="create-user">Show</button>
and in the js u must call to the class
$(".create-user")
As was suggested, you will want to use the class attribute and selector.
Working example: https://jsfiddle.net/Twisty/5n2h03nL/
HTML
<div id="users-contain" class="ui-widget">
<h1>Order List:</h1>
<table id="users" class="ui-widget ui-widget-content">
<thead>
<tr class="ui-widget-header ">
<th>Name/Surname</th>
<th>Address</th>
<th>Telephone</th>
<th>Time/Date</th>
<th>Order Details</th>
<th>Done</th>
</tr>
</thead>
<tbody>
<tr>
<td>John Doe</td>
<td>Lykavitou 12, 2109 Aglantzia</td>
<td>99123456</td>
<td>21:00 21/11/16</td>
<td>
<button id="create-user-1" class="showDialog">Show</button>
</td>
<td align="center">
<input type="checkbox" class="case" name="case" value="1" />
</tr>
<tr>
<td>Andreas Georgiou</td>
<td>Grigori Auxentiou 12, 2109 Aglantzia</td>
<td>99654789</td>
<td>20:00 21/11/16</td>
<td>
<button id="create-user-2" class="showDialog">Show</button>
</td>
<td align="center">
<input type="checkbox" class="case" name="case" value="1" />
</tr>
</tbody>
</table>
</div>
jQuery
$(".showDialog").button().on("click", function() {
dialog.dialog("open");
});
In regards to your other comment, you will need to provide more info. If you want the "Show" button to launch the dialog with custom details each time, those details need to be provided from some place. You can make use of data attributes on the row, like <tr data-comments=""> or make an AJAX call to a database. We can't just write that for you, you need to figure out where you want to store those details and how you want to collect them when the button is clicked.
In regards to this question, I suspect you've got the answer. So I would mark one as a answer, take a stab at your next issue, and if needed create a new question.

how to reload javascript function without reloading the whole page

Previously i found the solution for div here Stackoverflow link
this page talks about reloading a div but my problem is different
here is my index page
<?php
$message = "";
$minutes = "";
$limit = 2;
$effect = "";
$start = "";
$end = "";
require_once('db.php');
$query = mysql_query("SELECT message FROM kioskmessage where recNo = 1");
$row = mysql_fetch_assoc($query);
$message = $row['message'];
?>
<?php
$query = mysql_query("SELECT effect FROM kioskmessage where recNo = 1");
$row = mysql_fetch_assoc($query);
$effect = $row['effect'];
if($effect == "blink")
{
$start = '<p class="blink_text">';
$end = "</p>";
}
elseif($effect == "scrolling")
{
$start = "<marquee>";
$end = "</marquee>";
}
else
{
$start = '<p class="normalmessage">';
$end = "</p>";
}
?>
<?php
$query = mysql_query("select minutes from getminutes where id = 1");
$row = mysql_fetch_assoc($query);
$minutes = $row['minutes'];
?>
<html>
<header>
<div class="img"> <img src="images/logo.png">
</div>
<div class="container" id="nav">
<p id="time"></p>
</div>
</header>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>TT</title>
<link href="css/bootstrap.css" rel="stylesheet">
<link href="style/style.css" rel="stylesheet" type="text/css">
<script>
document.body.style.zoom="95%"
</script>
<script>
function ins()
{
nextDepartures(<?=$minutes?>, <?=$limit?>);
nextDeparturesTrains(120);
nextDeparturesTrams(60);
startTime();
}
</script>
<script>
$(document).ready(
function() {
setInterval(ins(), 5000);
});
</script>
<script src="data.js"></script>
<script src="sprintf.js"></script>
<script type="text/javascript" src="2.0.0-crypto-sha1.js"></script>
<script type="text/javascript" src="2.0.0-hmac-min.js"></script>
</head>
<body onload="ins()">
<table class="table table-bordered table-stripped table-hover" id="depart" style="float:left; border: 1px solid black; width:30%;">
<thead>
<tr>
<td colspan="4" class="danger" style="text-align: center; font-weight: bold;">Buses Departing from this Stop</td>
<tr>
<tr>
<th>Bus No. & Name</th>
<th>Time</th>
<th>Remaining Mins</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<!-- This table for train information-->
<table class="table table-bordered table-stripped table-hover" id="departTrains" style="float:left; border: 1px solid black; width:30%;">
<thead>
<tr>
<td colspan="4" class="danger" style="text-align: center; font-weight: bold;">Trains Departing from varios stations</td>
<tr>
<tr>
<th>Station</th>
<th>Destination</th>
<th>Time</th>
<th>Remaining Mins</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<!-- This table for tram information-->
<table class="table table-bordered table-stripped table-hover" id="departTrams" style="float:left; border: 1px solid black; width:30%;">
<thead>
<tr>
<td colspan="4" class="danger" style="text-align: center; font-weight: bold;">Tram Departing from plenty road</td>
<tr>
<tr>
<th>Tram Name</th>
<th>Time</th>
<th>Remaining Mins</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<footer id="footer">
<?=$start?><?=$message?><?$end?>
</footer>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="js/bootstrap.js"></script>
</body>
</html>
Now i have a javascript function ins() which further have stored functions in it which sends data to the tables defined in the page with relevant information.
Also, i have a script defined in the page which i think could be the possible solution, but its not working
here is that script
<script>
$(document).ready(
function() {
setInterval(ins(), 5000);
});
</script>
this is the sample data which function ins() is pushing into tables on load the page
If you want to load the JavaScript function without reloading the Entire page you can follow up the AJAX structure and you can make the changes as per the requirement you need.
Since loading up of the JavaScript without reloading the page will perform good only if it is done in AJAX. If the process is done in AJAX it will load the particular div where you want to display the JS output as required.
You can use the ins() function in Ajax and you can reload the page as the success function so that it will load the content under the DIV what you have provided as the success div.

How do I run onchange event when rows can be added at any time

I want to do what I did in the snippet but as an array. What do I mean by this. Lets say a user wants to add another row to the example in the snippet. The code should run both and calculate the total from both rows. There can be new rows added that is why im saying im trying to do this as an array. I'm trying to do something like excel does with cells that add the data depending on the change of a cell but in a much simpler manner just addition and only specified cells.
How would I do this?
this is the code that I have that I want to add this functionality to:
index.php
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
</head>
<body>
<div class="container">
<br />
<br />
<br />
<div class="table-responsive">
<div id="live_data"></div>
</div>
</div>
</body>
</html>
<script>
$(document).ready(function(){
function fetch_data()
{
$.ajax({
url:"select.php",
method:"POST",
success:function(data){
$('#live_data').html(data);
}
});
}
fetch_data();
$(document).on('click', '#btn_add', function(){
/* this function would also add the prices to the table*/
var first_name = $('#first_name').text();
var last_name = $('#last_name').text();
if(first_name == '')
{
alert("Enter First Name");
return false;
}
if(last_name == '')
{
alert("Enter Last Name");
return false;
}
$.ajax({
url:"insert.php",
method:"POST",
data:{first_name:first_name, last_name:last_name},
dataType:"text",
success:function(data)
{
alert(data);
fetch_data();
}
})
});
});
</script>
select.php
<?php
$connect = mysqli_connect("localhost", "root", "", "test_db");
$output = '';
$sql = "SELECT * FROM tbl_sample ORDER BY id DESC";
$result = mysqli_query($connect, $sql);
$output .= '
<div class="table-responsive">
<table class="table table-bordered">
<tr>
<th width="10%">Id</th>
<th width="40%">First Name</th>
<th width="40%">Last Name</th>
<th width="10%">Delete</th>
</tr>';
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
$output .= '
<tr>
<td>'.$row["id"].'</td>
<td class="first_name" data-id1="'.$row["id"].'" contenteditable>'.$row["first_name"].'</td>
<td class="last_name" data-id2="'.$row["id"].'" contenteditable>'.$row["last_name"].'</td>
<td><button type="button" name="delete_btn" data-id3="'.$row["id"].'" class="btn btn-xs btn-danger btn_delete">x</button></td>
</tr>
';
}
$output .= '
<tr>
<td></td>
<td id="first_name" contenteditable></td>
<td id="last_name" contenteditable></td>
<td><button type="button" name="btn_add" id="btn_add" class="btn btn-xs btn-success">+</button></td>
</tr>
';
}
else
{
$output .= '<tr>
<td colspan="4">Data not Found</td>
</tr>';
}
$output .= '</table>
</div>';
echo $output;
?>
$(document).ready(function() {
// functions assigned to onchange properties
document.getElementById('price').onchange = function() {
// access form and value properties via this (keyword)
var form = this.form;
var total = parseFloat(this.value) + parseFloat(form.elements['aditional_price'].value);
form.elements['total'].value = formatDecimal(total);
};
document.getElementById('aditional_price').onchange = function() {
// access form and value properties via this (keyword)
var form = this.form;
var total = parseFloat(this.value) + parseFloat(form.elements['price'].value);
form.elements['total'].value = formatDecimal(total);
};
// format val to n number of decimal places
function formatDecimal(val, n) {
n = n || 2;
var str = "" + Math.round(parseFloat(val) * Math.pow(10, n));
while (str.length <= n) {
str = "0" + str;
}
var pt = str.length - n;
return str.slice(0, pt) + "." + str.slice(pt);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#" method="post" id="form1" class="form1" name="form1">
<fieldset>
<p>
Price
<input name="price" id="price" size="4" value="0" />+ Aditional Price
<input name="aditional_price" id="aditional_price" value="0" size="4" />
<br/>
<!-- new row added
<br/>
Price
<input name="price" id="price" size="4" value="0" />+ Aditional Price
<input name="aditional_price" id="aditional_price" value="0" size="4"/>
<br/>
-->
<br/>
<label>Total: $
<input type="text" class="num" name="total" value="0.00" readonly="readonly" />
</label>
</p>
</fieldset>
</form>

Display the return of an ajax in the corresponding row

I needed to add runtime rows on a table and then send data to database. I managed to do most of it however I am stuck on 2 parts of the program.
I am using Ajax to check the available quantity from a drop down, which I wish to display in the corresponding row, but cant, I have been able to alert the correct value so far).
The php post is sending me one parameter less than is available on the form if I fill any row, but send me the correct amount of parameters if I add rows and don’t fill any information. ( ie if I add 3 blank rows and click on submit it submits 4 values, -> because one row is hidden however if I fill any of the 3 rows in the screen it sends as parameter only 3 post for $name)
function getSpQty(strURL) {
var xmlhttp;
console.log(this)
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) {
if (xmlhttp.status == 200) {
alert(xmlhttp.responseText);
document.getElementById('sp').value = xmlhttp.responseText;
} else {
alert("There was a problem while using XMLHTTP:\n" + xmlhttp.statusText);
}
}
}
xmlhttp.open("GET", strURL, true);
xmlhttp.send(null);
}
<?php include_once( "dbConn-SP.php"); $sqlSP="select * from dbo.SparepartManagement" ; $stmtSP=s qlsrv_query($connIgms, $sqlSP); ?>
<html>
<head>
<script src="js/jquery1.7.js"></script>
<script>
$(document).ready(function() {
var id = 0;
// Add button functionality
$("table.dynatable button.add").click(function() {
id++;
var master = $(this).parents("table.dynatable");
// Get a new row based on the prototype row
var prot = master.find(".prototype").clone();
prot.attr("class", "")
prot.find(".id").attr("value", id);
master.find("tbody").append(prot);
});
// Remove button functionality
$("table.dynatable button.remove").live("click", function() {
$(this).parents("tr").remove();
});
});
</script>
<style>
.dynatable {
border: solid 1px #000;
border-collapse: collapse;
}
.dynatable th,
.dynatable td {
border: solid 1px #000;
padding: 2px 10px;
width: 170px;
text-align: center;
}
.dynatable .prototype {
display: none;
}
</style>
<script type="text/javascript" language="JavaScript1.2" src="spQty.js"></script>
</head>
<body>
<form action="test.php" method="post" name="frm">
<table width="100%" class="dynatable">
<thead>
<tr>
<th width="144">ID</th>
<th width="144">Spareparts</th>
<th width="144">Quanitity</th>
<th width="144">Issued Quantity</th>
<th width="140">
<button type="button" class="add">Add</button>
</th>
</tr>
</thead>
<tbody>
<tr class="prototype">
<td>
<input type="text" name="id[]" value="0" class="id" />
</td>
<td>
<select style="width:200px" name="name[]" id="sp" onChange="getSpQty('SPName.php?spareparts='+this.value)">
<option value="error">Select Spare Parts</option>
<?php while($viewAllSP=s qlsrv_fetch_array($stmtSP,SQLSRV_FETCH_ASSOC)) { echo "<option value='$viewAllSP[GeneralItemDescription]'>$viewAllSP[GeneralItemDescription]</option>\n"; }; ?>
</select>
</td>
<td>
<input type="text" name="col4[]" value="" />
</td>
<td>
<input type="text" name="col3[]" value="" />
</td>
<td>
<button class="remove">Remove</button>
</td>
</tr>
</table>
<input type="submit" value='send' />
</form>
</body>
</html>
this is the SPName.php
include_once("dbConn-SP.php");
$spareparts=$_REQUEST['spareparts'];
$tsqls = "select InitialQty from SparepartManagement where GeneralItemDescription ='$spareparts'";
$params = array();
$options = array("Scrollable" => SQLSRV_CURSOR_KEYSET );
$stmt = sqlsrv_query($connIgms, $tsqls , $params, $options);
$row_count = sqlsrv_num_rows($stmt);
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
$test = $row['InitialQty'];
}
echo $test;
?>
here is test.php
<?PHP
error_reporting(0);
include_once("dbConn-SP.php");
$Qty = $_POST["col4"];
$IssuedQty = $_POST["col3"];
$name= $_POST["name"];
//Step 3: Insert statment
print_r($name);
for ($i = 1; $i < sizeof($Qty); $i++) {
$j=$i-1;
$Insert = "INSERT INTO SparepartTransaction (SPDesc,InitialQty,QtyIssued) Values ".
" ('$name[$j]','$Qty[$i]','$IssuedQty[$i]')";
$stmt = sqlsrv_query($connIgms,$Insert);
}
sqlsrv_close($connIgms);
?>
unfortunately i do not have enough reputation to post a image here so here is a link with the actual display on my screen
http://prntscr.com/749n4n
what i want is that instead of having an alert as -> alert(xmlhttp.responseText);
i wish this value to be displayed on the cell beside the drop down. any help will be appreciated.

Categories