So I just got done with figuring out some javascript issues with my form in this topic: How Can I Insert Multiple Rows Into a DB from my HTML Form with Multiple Rows Dynamically?
But since I had such a multi-part question I have been asked to create a new topic. Below is my new code that I am using where I am stuck and wanting to be able to submit my form, which has the capability if adding multiple rows, to my database and add those HTML rows to rows in the SQL database, respectively.
PREVIEW: http://cl.ly/image/0K0Z202O1Q3e/Screen%20Shot%202013-03-14%20at%203.00.19%20PM.png
HTML
<html>
<header>
<link rel="stylesheet" href="style.css" type="text/css">
<script type="text/javascript" language="javascript" src="/jquery/js/jquery-1.9.1.js">
</script>
<script src="http://www.mapquestapi.com/sdk/js/v7.0.s/mqa.toolkit.js?
key=Gmjtd%7Cluua2q6bn9%2C8g%3Do5-lzbsh"></script>
<script type="text/javascript" src="js/scripts.js"></script>
<title>Central Office Company Survey</title>
</header>
<body onload="get_company_name();">
<h1>Central Office Company Survey</h1>
<div id='map' style='width:0px; height:0px; position:absolute'></div>
<input type="hidden" id="co_city" name="co_city">
<input type="hidden" id="co_state" name="co_state">
<input type="hidden" id="co_zipcode" name="co_zipcode">
<table>
<th>Company</th>
<th>CO Name</th>
<th>Get Current Location</th>
<th>Lat</th>
<th>Long</th>
<th>Address</th>
<tr>
<td><select id="company_name" name="company_name" /></select></td>
<td><input name="co_name" type="text"></td>
<td><input type="submit" value="Get GPS" onclick="gpslookup();" /></td>
<td><input id="co_lat" name="co_lat" type="text" /></td>
<td><input id="co_long" name="co_long" type="text" /></td>
<td><input id="co_address" name="co_address" type="text" /></td>
</tr>
</table>
<table id="tabledata">
<thead>
<th>Select</th>
<th>Border Location Name</th>
<th>Cable Location</th>
<th>Direction of Vault Wall</th>
<th>Cable Type</th>
<th>Cable Size (pairs)</th>
<th>Cable Gauge</th>
<th>Vertical(s) appeared on Verticals</th>
<th>Approximate Number of Jumpers</th>
<th>Are Protectors Still In?</th>
<th>Metered Distance</th>
<th class="comments">Central Office Comments</th>
</thead>
<tbody id="input"></tbody>
<tbody id="template">
<tr>
<td><input type="checkbox" /></td>
<td><input name="border_location" type="text" /></td>
<td><input name="cable_location" type="text" /></td>
<td><input name="vault_direction" type="text" /></td>
<td><input name="cable_type" type="text" /></td>
<td><input name="cable_size" type="text" /></td>
<td><input name="cable_gauge" type="text" /></td>
<td><input name="vertical" type="text" /></td>
<td><input name="jumpers" type="text" /></td>
<td><input name="protectors" type="text" /></td>
<td><input name="metered_dist" type="text" /></td>
<td><input name="comments" type="text" /></td>
</tr>
</tbody>
</table>
<button id="ActionAddRow">Add Row</button>
<button onclick="deleteRow(); return false;">Delete Row</button>
<button id="ActionSubmit">Submit</button>
</body>
</html>
scripts.js
//Button Functions
$(function () {
var addInputRow = function () {
$('#input').append($('#template').html());
};
addInputRow();
$('#ActionAddRow').on('click', addInputRow);
$('#ActionSubmit').on('click', function () {
var data = $('#input tr').map(function () {
var values = {};
$('input', $(this)).each(function () {
values[this.name] = this.value;
});
return values;
}).get();
$.post('./php/upload_survey.php', {
json: JSON.stringify(data),
delay: 1
}).done(function (response) {
alert("Thank you. Your form has been submitted.");
console.log(response);
});
});
});
//Delete Selected Rows
function deleteRow() {
try {
var table = document.getElementById("tabledata");
var rowCount = table.rows.length;
for(var i=0; i<rowCount; i++) {
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
if(null != chkbox && true == chkbox.checked) {
if(rowCount <= 3) {
alert("Cannot delete all the rows.");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
}
catch(e) {
alert(e);
}
};
upload_survey.php
//Assign passed parameters
$values = json_decode($_POST['json']);
$stringLogInfo = "INFO: Location: $co_address CO Name = $co_name !!!\n\n";
log_audit($logAuditFile, $logModule, $stringLogInfo);
//Parse and store the ini file, this will return an associative array
ini_set("display_errors", "1");
error_reporting(E_ALL);
//Insert Survey Form Information into the database
$sql="INSERT INTO table_name (company_name,...,...)
VALUES ($values)";
mysql_query($sql) or die ("Unable to Make Query:" . mysql_error());
**So far every time I try to get this working the JS fires successfully, but I get an error in Chrome's Developer Toolbox: Unable to Make Query:Column count doesn't match value count at row 1
This refers to this function in js file: console.log(response);
I think there is no such thing as batch inserts in PHP. There is no equivalent for JAVA's addBatch & executeBatch.
So the right way to do it is simply iteratation over array and insert single row with prepared statement.
Related
I have a HTML table which is editable/dynamic. Please see table below:
<table>
<tr>
<td><input id="txt_row_{{ $records[$i]["row_id"] }}" type="hidden" value="{{$records[$i]["row_id"]}}" /></td>
<td><input type="checkbox" id="is_workingday_row_{{ $records[$i]["row_id"] }}" checked /></td>
</tr>
<tr>
<td><input id="txt_row_{{ $records[$i]["row_id"] }}" type="hidden" value="{{$records[$i]["row_id"]}}" /></td>
<td><input type="checkbox" id="is_workingday_row_{{ $records[$i]["row_id"] }}" checked /></td>
</tr>
</table>
Now, how can I loop thru the entire table to get the values/changes thru jQuery and submit it via AJAX to a PHP script? Can you at least point me in the right direction? Thanks.
Hi #Ronald you can use form instead of table but if you are using table you have to use jquery each function to get all inputs value and create object of these values and after that you can send this through ajax
$(document).ready(function(){
var allInputs = $('table').find('input');
var obj = {};
$(allInputs).each(function(){
var key = $(this).attr('name');
var value = $(this).val();
obj[key] = value
});
console.log(obj);
});
$(document).ready(function(){
var allInputs = $('table').find('input');
var obj = {};
$(allInputs).each(function(){
var key = $(this).attr('name');
var value = $(this).val();
obj[key] = value
});
console.log(obj);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td><input id="txt_row_1" type="hidden" name="txt_row_1" value="record1" /></td>
<td><input type="checkbox" name="is_workingday_row_1" id="is_workingday_row_1" checked /></td>
</tr>
<tr>
<td><input id="txt_row_2" name="txt_row_2" type="hidden" value="record2" /></td>
<td><input type="checkbox" name="is_workingday_row_2" id="is_workingday_row_2" checked /></td>
</tr>
</table>
I'm very new in web programming, especially on Codeigniter. And now I'm looking for how to pass/submit array from view to controller.
This part of my HTML script in view:
<tr class="rowdim"> <!-- ROW 1 -->
<td><input type="text" id="bookid1" name="book_id[]" /></td>
<td><input type="text" id="qty1" name="qty[]" /></td>
<td><input type="text" id="uom1" name="uom_id[]" /></td>
</tr>
<tr class="rowdim"> <!-- ROW 2 -->
<td><input type="text" id="bookid2" name="book_id[]" /></td>
<td><input type="text" id="qty2" name="qty[]" /></td>
<td><input type="text" id="uom2" name="uom_id[]" /></td>
</tr>
<tr class="rowdim"> <!-- ROW 3 -->
<td><input type="text" id="bookid3" name="book_id[]" /></td>
<td><input type="text" id="qty3" name="qty[]" /></td>
<td><input type="text" id="uom3" name="uom_id[]" /></td>
</tr>
My ajax:
var det_book = document.getElementsByName("book_id[]");
var det_qty = document.getElementsByName("qty[]");
var det_uom = document.getElementsByName("uom_id[]");
var vdata = {det_book:det_book,det_qty:det_qty,det_uom:det_uom}
$.ajax({
type:"POST",
url:"<?php echo base_url(); ?>trans/StockIn/saveData",
data:vdata,
success:function(returnmsg){
if (returnmsg=='""'){
window.alert(msg);
} else {
window.alert(returnmsg);
}
});
Controller:
$det_book=$_POST["det_book"];
$det_qty=$_POST["det_qty"];
$det_uom=$_POST["det_uom"];
$details = array();
$index=0;
foreach ($det_book as $baris){
array_push($details,array(
'book_id'=>$baris,
'quantity'=>$det_qty[$index],
'uom_id'=>$det_uom[$index]
));
$index++; }
$error="";
if (!$this->db->insert_batch('trx_inbound_detail',$details))
{
$error = $this->db->error();
}
Any miss or something wrong with my code?
Already search in community but still no luck.
Appreciate if you also suggest other ways.
Thanks
Your first mistake is get the textbox value in multiple fields:
var det_book = $('input[name^=book_id]').map(function(idx, elem) {
return $(elem).val();
}).get();
var det_qty = $('input[name^=qty]').map(function(idx, elem) {
return $(elem).val();
}).get();
var det_uom = $('input[name^=uom_id]').map(function(idx, elem) {
return $(elem).val();
}).get();
In php you didnot mention the index in foreach:
foreach ($det_book as $index => $baris) {
array_push($details,array(
'book_id'=>$baris,
'quantity'=>$det_qty[$index],
'uom_id'=>$det_uom[$index]
));
}
print_r($details);
exit();
Yes, you missed something.
Element with name book_id[] doesn't exist. Also you have three inputs with same name.
Check this link to see how to pass array with ajax.
I'm building a dynamically generated table where every row is a form with some inputs and selects and has its own submit.
Here is my code so far:
<script>
$(function () {
$('form').on('submit', function (e) {
var princ = $('#principal').val();
window.princ = princ;
e.preventDefault();
$.ajax({
url: 'post.php',
method: 'GET',
data: {"princ":princ},
success: function (response) {
alert("success");
} }); }); });
</script>
<table id="assets_table">
<thead style=" cursor: pointer;">
<tr style="text-align: left; color: #fff;">
<th>Lender </th>
<th>Principal </th>
<th>Int. % </th>
<th>Term (mo.) </th>
<th>Collateral </th>
<th></th>
</tr>
</thead>
<tbody>
<?php
$competitions_id = $uscom['id'];
$users_query = mysqli_query($con, "SELECT * FROM competitions WHERE competition='$compe'");
$users_query_r = mysqli_fetch_array($users_query);
foreach($users_query as $users_query_r) {
$usn = $users_query_r['Name'];
$usn_query = mysqli_query($con, "SELECT * FROM users WHERE username='$usn'");
$usn_query_r = mysqli_fetch_array($usn_query);
?>
<form>
<tr>
<td> <img src="<?= $punch_query_r['profile_pic'] ?>" alt="user"> <?= $users_query_r['Name'] ?></td>
<td><input id="principal" type="text" value="0" ></td>
<td><input id="rate" type="text" value="0" ></td>
<td><input id="term" class = "term_input" type="text" value="0" ></td>
<td><input id="collateral" type="text" value="0">
<select id="colselect" >
<option selected disabled>Select asset</option>
</select></td>
<td> <input type="submit"></td>
</tr>
<?php
} ?>
</tbody>
</table>
</form>
However I cannot make it work properly because when I click on submit it does not really submit the corresponding row's form but the first one that was submitted.
I've also tried rewritting variables with input paste keyup but it does not solve the problem either because it just gets the last input whch was filled regardless of the row.
Any idea on how to solve it? Many thanks in advance.
this code is to create dynamic number of fields and to send data.. this is doing it's work...
but then i try to back.php(where form sends the data ) i don't know hoe to get the exact number of rows... id = 0_1 .... 3_1 there are many options.. but what is the exact number to counting to make a loop...
please help me on this asap ...
<html>
<head>
<title>Infinite Form Rows</title>
<script
type="text/javascript"
src="http://cachefile.net/scripts/jquery/1.2.3/jquery-1.2.3.min.js">
</script>
<script type="text/javascript">
$(function(){
var newRowNum = 0;
$('#addnew').click(function(){
newRowNum += 1;
var addRow = $(this).parent().parent();
var newRow = addRow.clone();
$('input', addRow).val('');
$('td:first-child', newRow).html(newRowNum);
$('input', newRow).each(function(i){
var newID = newRowNum + '_' + i;
$(this).attr('id',newID).attr('name',newID);
});
addRow.before(newRow);
$('a.remove', newRow).click(function(){
$(this).parent().parent().remove();
return false;
});
return false;
});
});
</script>
</head>
<body>
<form action="back.php" method="get" >
<table id="tabdata">
<thead>
<tr>
<th>Row</th>
<th>Cell 1</th>
<th>Cell 2</th>
<th>Cell 3</th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td><a id="addnew" href="">Add</a></td>
<td><input id="n0_1" name="n0_1" type="text" /></td>
<td><input id="n0_2" name="n0_2" type="text" /></td>
<td><input id="n0_3" name="n0_3" type="text" /></td>
<td></td>
</tr>
<tr>
</tr>
</tbody>
</table>
<input id="go" name="go" type="submit" value=" Save " />
</form>
</body>
</html>
You can maintain a hidden input that contains the current number of rows. Set the value on the click event handler for #go.
$('#go').click(function() {
var numRows =$('#tabdata tbody tr').length;
$('#myHiddenInput').val(numRows);
});
I have a PHP page that populates HTML tables from MySQL. It outputs two seperate tables with the IDs 'headTable' and 'visits'. I am trying to sum the values from the 'visit' table and output the sum to the corresponding 'headTable'. There is also a checkbox that populates the input field and I am also having trouble getting the correct sum when checking all of the check boxes. The sum is correct if I manually type in the values. Thanks in advance.
Here is an Example on Fiddle
<table id="headTable">
<tr>
<th>First Table</th>
<th><span id="appliedTotal"></span></th>
</tr>
</table>
<table id="visits">
<tr>
<td>Jane</td>
<td>18.45</td>
<td><input type="checkbox"></td>
<td><input class="amount" type="text" size="20" value=""></td>
</tr>
<tr>
<td>Peter</td>
<td>100</td>
<td><input type="checkbox"></td>
<td><input class="amount" type="text" size="20" value=""></td>
</tr>
</table>
<table id="headTable">
<tr>
<th>Second Table</th>
<th><span id="appliedTotal"></span></th>
</tr>
</table>
<table id="visits">
<tr>
<td>Ronald</td>
<td>100</td>
<td><input type="checkbox"></td>
<td><input class="amount" type="text" size="20" value=""></td>
</tr>
<tr>
<td>John</td>
<td>100</td>
<td><input type="checkbox"></td>
<td><input class="amount" type="text" size="20" value=""></td>
</tr>
</table>
and for my Jquery
<script>
$(document).ready(function(){
$(function() {
$('table input[type="checkbox"]').change(function() {
var input = $(this).closest('td').next('td').find('input');
if ($(this).is(':checked')) {
var amount = $(this).closest('td').prev('td').text();
var sum = 0;
$.each($('table#visits'), function() {
$('.amount').each(function() {
sum += Number($(this).val());
$('#appliedTotal').html('$'+sum.toFixed(2));
});
});
input.val(amount);
} else {
input.val('0.00');
var sum = 0;
$('.amount').each(function() {
sum += Number($(this).val());
$('#appliedTotal').html('$'+sum.toFixed(2));
});
}
});
});
$.each($('table#visits'), function() {
$(".amount").keyup(function() {
var sum = 0;
$('.amount').each(function() {
sum += Number($(this).val());
$('#appliedTotal').html(sum);
});
});
});
});
</script>
This is what I was looking to do.
JSFiddle Example
is it about how to make numbers from dollars? I prefer opposite, but for you case add substring(1) to .val() before passing it to Number()
and a
sum = '$' + sum
before assign to the appliedTotal of course
you can't have two tables or any other tags with the same 'id' at one page.