How to submit via AJAX multiple values/array? - php

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>

Related

Can't Send while looped input field data from ajax to php

I have two input fields with same class name and the same data.
Here is my while loop generated input field
<tr>
<td>
<input onchange="mySubmit(this.form)" class="ot_value" name="ot_value" type="text" value="10">
<input type="hidden" name="ot_id" class="ot_id" value="1">
</td>
</tr>
<tr>
<td>
<input onchange="mySubmit(this.form)" class="ot_value" name="ot_value" type="text" value="11">
<input type="hidden" name="ot_id" class="ot_id" value="2">
</td>
</tr>
I was trying to send data from ajax to php when user change any value.
Here is my jquery
function mySubmit(theForm) {
var ot_value= $(".ot_value").val();
var ot_id= $(".ot_id").val();
$.ajax({
type:"post",
url:"../apis/update_ot.php",
data: "ot_value=" + ot_value+ "&ot_id=" + ot_id,
success:function(data){
alert(data);
}
});
}
I was able to send data when user is changing any input field data. But the problem is that, it's taking only the 1st row data.
How can I get the exact data, that what user are changing in input field.
You have jQuery, use it
remove onchange="mySubmit(this.form)" from the field and do
$(function() {
$(".ot_value").on("change", function() {
const ot_value = $(this).val();
const ot_id = $(this).next(".ot_id").val();
console.log("about to submit",ot_value,ot_id)
$.ajax({
type: "post",
url: "../apis/update_ot.php",
data: "ot_value=" + ot_value + "&ot_id=" + ot_id,
success: function(data) {
alert(data);
}
});
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tbody>
<tr>
<td>
<input class="ot_value" name="ot_value" type="text" value="10">
<input type="hidden" name="ot_id" class="ot_id" value="1">
</td>
</tr>
<tr>
<td>
<input class="ot_value" name="ot_value" type="text" value="11">
<input type="hidden" name="ot_id" class="ot_id" value="2">
</td>
</tr>
</tbody>
</table>

Submit Array from view to controller using ajax (Codeigniter)

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.

Need HTML Form to Submit Multiple Rows into SQL Database

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.

Jquery sum form inputs in multiple tables

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.

jquery post - update db - multiple rows

I'm not sure if what I'm trying to do is simple or not but here it is:
I have rows of data in a table. The last 3 fields are text fields that take user input. Each row has it's own UPDATE button.
I'm using the following code to try and do a jQuery .ajax post but I'm seeing my issue - I'm assigning IDs to my input fields and you can only have one ID declared per page so I'm sure that's one issue.
I'm trying to make it so that when you click the UPDATE button, it passes the variables from that row in the INPUT boxes and the hidden INPUT field for the rowID, and calls a .php file that updates the DB.
$(function() {
$(".submit").click(function() {
var status = $("#status").val();
var ly = $("#ly").val();
var rt = $("#rt").val();
var offerout = $("#offerout").val();
var lineid = $("#lineid").val();
var dataString = 'status='+ status + '&ly=' + ly + '&rt=' + rt + '&offerout=' + offerout + '&lineid=' + lineid;
$.ajax({
type: "POST",
url: "post/updatedata.php",
data: dataString,
success: function(){
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
return false;
});
});
and on line of my form (each line is the same but with a different hidden ID variable):
<form method="POST" name="form">
<td>This one</td><td>Los Angeles</td>
<td>CA</td><td>94591</td>
<td>220000</td>
<td>20000</td><td>24500</td>
<td>-5500</td><td>12</td>
<td>0</td><td>0.167</td><td>4</td>
<td>1</td><td>1898</td>
<td></td><td>1</td><td>211335190</td>
<td><input size="6" type="text" id="status" name="status"></td>
<td><input size="6" type="text" id="ly" name="ly"></td>
<td><input size="6" type="text" id="rt" name="rt"></td>
<td><select id="offerout" name="offerout"><option value="No">No</option><option value="Yes">Yes</option></select></td>
<input type="hidden" name="lineid" id="lineid" value="97">
<td><input type="submit" class="submit" value="Update"></td>
</form>
Thanks in advance, been working for days on this!
Duplicating id attributes will cause problems. When you say $("#ly"), you'll probably get the first one on the page and that's usually not the one you want. That's easy to solve:
Drop the id attributes in favor of class attributes. You could also use attribute selectors.
Adjust your jQuery selectors to go up to an ancestor and come back down to the thing you want.
First the HTML:
<td><input size="6" type="text" class="status" name="status"></td>
<td><input size="6" type="text" class="ly" name="ly"></td>
<td><input size="6" type="text" class="rt" name="rt"></td>
<td><select class="offerout" name="offerout"><option value="No">No</option><option value="Yes">Yes</option></select></td>
<input type="hidden" name="lineid" class="lineid" value="97">
Then your jQuery:
var $form = $(this).closest('form');
var status = $form.find(".status").val();
var ly = $form.find(".ly").val();
var rt = $form.find(".rt").val();
var offerout = $form.find(".offerout").val();
var lineid = $form.find(".lineid").val();
Also, since you are doing a POST request, you should just hand jQuery an object and let it worry about serializing it:
var data = {
status: status,
ly: ly,
rt: rt,
offerout: offerout,
lineid: lineid
};
$.ajax({
type: "POST",
url: "post/updatedata.php",
data: data,
success: function() {
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
That should take care of your client-side issues.
You could store a row number data variable in each submit and use that to determine which row was clicked and thus which inputs you need to pull values from.
$(function() {
$(".submit").each(function () {
var rowNum = $(this).attr('data-rownum');
$(this).click(function () {
var status = $("#status" + rowNum).val();
var ly = $("#ly" + rowNum).val();
var rt = $("#rt" + rowNum).val();
....
});
});
});
<form method="POST" name="form">
....
<td><input size="6" type="text" id="status1" name="status"></td>
<td><input size="6" type="text" id="ly1" name="ly"></td>
<td><input size="6" type="text" id="rt1" name="rt"></td>
<input type="hidden" name="lineid" id="lineid1" value="97">
<td><input type="submit" class="submit" value="Update" data-rownum="1"></td>
</form>
I remove hidden field and assign database id to update button as button will click get that id and corespondent data.
<table width="100%" border="1" cellspacing="0" cellpadding="0">
<tr>
<form method="POST" name="form">
<td>CA</td><td>94591</td>
<td>220000</td>
<td>20000</td><td>24500</td>
<td>-5500</td><td>12</td>
<td>0</td><td>0.167</td><td>4</td>
<td>1</td><td>1898</td>
<td></td><td>1</td><td>211335190</td>
<td><input size="6" type="text" id="status_97" name="status"></td>
<td><input size="6" type="text" id="ly_97" name="ly"></td>
<td><input size="6" type="text" id="rt_97" name="rt"></td>
<td><select name="offerout" id="offerout_97"><option value="No">No</option><option value="Yes">Yes</option></select></td>
<td><input type="submit" class="submit" value="Update" name="97"></td>
</form>
</tr>
<tr>
<form method="POST" name="form">
<td>CA</td><td>94591</td>
<td>220000</td>
<td>20000</td><td>24500</td>
<td>-5500</td><td>12</td>
<td>0</td><td>0.167</td><td>4</td>
<td>1</td><td>1898</td>
<td></td><td>1</td><td>211335190</td>
<td><input size="6" type="text" id="status_96" name="status"></td>
<td><input size="6" type="text" id="ly_96" name="ly"></td>
<td><input size="6" type="text" id="rt_96" name="rt"></td>
<td><select name="offerout" id="offerout_96"><option value="No">No</option><option value="Yes">Yes</option></select></td>
<input type="hidden" name="lineid" id="lineid_96" value="96">
<td><input type="submit" class="submit" value="Update" name="96"></td>
</form>
</tr>
</table>
java script code
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script>
$(function() {
$(".submit").click(function() {
var rowToUpdate = $(this).attr('name');
var status = $("#status_"+rowToUpdate).val();
var ly = $("#ly_"+rowToUpdate).val();
var rt = $("#rt_"+rowToUpdate).val();
var offerout = $("#offerout_"+rowToUpdate).val();
var dataString = 'status='+ status + '&ly=' + ly + '&rt=' + rt + '&offerout=' + offerout + '&rowToUpdate='+ rowToUpdate;
$.ajax({
type: "POST",
url: "post/updatedata.php",
data: dataString,
success: function(){
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
return false;
});
});
</script>
I hope this will help you..

Categories