Get all input value in a array from a jquery dynamic table - php

I have created a dynamic table using jquery as follows:
$.ajax({
data : data,
type : "get",
url : url,
dataType : "json",
error : function(resp){
alert("Error !!");
},
success : function(resp){
table = '';
$.each(resp,function(indx,obj){
table += '<tr>';
table += '<td>'+parseInt(indx+1)+'</td>';
table += '<td>'+'<input type="text" value="'+obj.ServiceDetail.service_code+'">'+'</td>';
table += '<td>'+'<input type="text" value="'+obj.ServiceDetail.name+'">'+'</td>';
table += '<td>'+'<input type="text" value="'+obj.ServicePrice.discount_price+'">'+'</td>';
table += '</tr>';
});
$("tbody#sevice_table_body").append(table);
}
});
and a button :
<input type="button" class = "btn btn-success btn-sm" value="submit" >
now i want to get all input value in a array by click submit button so that can be inserted in a database table using jquery ajax.

You can use this code for cycling the input and add them to an array
var arrayOfVar = []
$.each($("input[type='text']"),function(indx,obj){
arrayOfVar.push($(obj).val());
});

You can use .serializeArray() it Encode elements as an array of names and values.
Find below fiddle for more info
$(function() {
var data = $("#tbl2 :input").serializeArray(); // For converting it to array
//If needed below code is converting it to object
var obj = {};
for (var i = 0, l = data.length; i < l; i++) {
obj[data[i].name] = data[i].value;
}
console.log(data); // Print Array in Console
console.log(obj);// Print Object in Console
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="tbl2">
<tr>
<td>
<input type="text" name="tb3" value="1" />
</td>
</tr>
<tr>
<td>
<input type="text" name="tb4" value="2" />
</td>
</tr>
<tr>
<td>
<input type="text" name="tb5" value="3" />
</td>
</tr>
<tr>
<td>
<input type="text" name="tb6" value="4" />
</td>
</tr>
</table>

Add attribute name with name and array .
$.ajax({
data : data,
type : "get",
url : url,
dataType : "json",
error : function(resp){
alert("Error !!");
},
success : function(resp){
table = '';
$.each(resp,function(indx,obj){
table += '<tr>';
table += '<td>'+parseInt(indx+1)+'</td>';
table += '<td>'+'<input type="text" name="service_code[]" value="'+obj.ServiceDetail.service_code+'">'+'</td>';
table += '<td>'+'<input type="text" name="name[]" value="'+obj.ServiceDetail.name+'">'+'</td>';
table += '<td>'+'<input type="text" name="discount_price[]" value="'+obj.ServicePrice.discount_price+'">'+'</td>';
table += '</tr>';
});
$("tbody#sevice_table_body").append(table);
}
});

Here you go with a solution
var inputData = [];
$('button[value="submit"]').click(function(){
$('input[type="text"]).each(function(){
inputData.push($(this).val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Hope this will help you.

In your table section, add name attribute like this:
$.each(resp,function(indx,obj){
table += '<tr>';
table += '<td>'+parseInt(indx+1)+'</td>';
table += '<td>'+'<input name="services[' + indx + '][code]" type="text" value="'+obj.ServiceDetail.service_code+'">'+'</td>';
table += '<td>'+'<input name="services[' + indx + '][name]" type="text" value="'+obj.ServiceDetail.name+'">'+'</td>';
table += '<td>'+'<input name="services[' + indx + '][price]" type="text" name="service[' + indx + '][price]" value="'+obj.ServicePrice.discount_price+'">'+'</td>';
table += '</tr>';
});
This will produce names like services[0][code], services[0][name], etc.,
Now you can access the input values as an array in PHP:
$services = $_POST['services'];
foreach ($services as $index => $service) {
$code = $service['code'];
$name = $service['name'];
$price = $service['price'];
echo "$index : $code, $name, $price \n";
}

Related

Change specific dynamically created table row html and text from ajax response

From the database, I have a dynamic table like this:
<table>
<?php
$query = ....;
foreach ($query as $row) {
echo '<tr>';
echo '<td>' . ' <span class="bName">' . $row['brand_name'] . '</span>'.
'<input name="product_id" type="number" value="' . $row['product_id'] . '">'.
'<input name="company_id[]" type="number" value="' . $row['company_id'] . '">'.
'<button name="exchange" type="button">Click Me!</button></td>';
echo '</td>';
echo '</tr>';
}
?>
</table>
It returns say 4 rows with brand_name inside the <span> and product_id inside an <input>. The exchange button on click calls an ajax request that query another random brand_name and returns the query as JSON like this:
{product_id: '2206', brand_name: 'New name', company_id: '234' }
The script for ajax is
<script>
$(document).ready(function() {
$('button[name="exchange"]').click(function() {
$.ajax({
url: 'ajaxChangeBrand.php',
type: 'POST',
data: 'keyword=' + $(this).parent().find('input[name="product_id"]').val(),
success: function(response) {
var data = JSON.parse(response);
$('.bName').html(data.brand_name); // Problem is here
$('.company_id').html(data.company_id); // and here
console.log(data);
},
});
});
});
</script>
My target is to change the brand_name inside class bName and company_id value with the new values from ajax response for that specific row. But my problem is it changes all the spans with bName class and all the inputs with class company_id. What should be the best approach to change the specific row of that table from the ajax data?
Store a reference to the cell that the button that was actually clicked exists in so you can find within that cell the specific elements.
Also note that the company_id value is in an input thaat you ned to use val() on and you need to give it a class name
$('button[name="exchange"]').click(function() {
// cell this button instance is in
const $cell = $(this).closest('td');
$.ajax({
url: 'ajaxChangeBrand.php',
type: 'POST',
data: 'keyword=' + $(this).parent().find('input[name="product_id"]').val(),
success: function(response) {
var data = JSON.parse(response);
$cell.find('.bName').html(data.brand_name); // Problem is here
$cell.find('.company_id').val(data.company_id); // and here
console.log(data);
},
});
});
Unable to test using AJAX but perhaps this might help. Use the event of the click function to find the parentNode and from that use querySelector to target the particular elements in the table row.
$(document).ready(function() {
$('button[name="exchange"]').click(function(e) {
let tr=e.target.parentNode;
let span=tr.querySelector('span.bName');
let pid=tr.querySelector('input[name="product_id"]');
let cid=tr.querySelector('input[name="company_id[]"]');
console.info( span.textContent, cid.value, pid.value)
$.ajax({
url: 'ajaxChangeBrand.php',
type: 'POST',
data: 'keyword=' + $(this).parent().find('input[name="product_id"]').val(),
success: function(response) {
var data = JSON.parse(response);
span.textContent=data.brand_name;
cid.value=data.company_id;
pid.value=data.product_id;
},
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td>
<span class="bName">Womble</span>
<input name="product_id" type="number" value="23">
<input name="company_id[]" type="number" value="88">
<button name="exchange" type="button">Click Me!</button>
</td>
</tr>
<tr>
<td>
<span class="bName">Bagpuss</span>
<input name="product_id" type="number" value="39">
<input name="company_id[]" type="number" value="12">
<button name="exchange" type="button">Click Me!</button>
</td>
</tr>
<tr>
<td>
<span class="bName">Clanger</span>
<input name="product_id" type="number" value="47">
<input name="company_id[]" type="number" value="91">
<button name="exchange" type="button">Click Me!</button>
</td>
</tr>
</table>

Showing search results with ajax

Please help,
I have the data that I loaded with ajax, but I am confused, how when I enter the item code, the data generated in json form, into the table
view
<div class="form-group col-md-4">
<label for="field-1" class="control-label">KODE RUNSHEET</label>
<input name="kd_runsheet[]" class="form-control" id="kode" type="text" placeholder="Masukan Kode Runsheet" style="" required="">
<input name="id_runsheet" id="id_runsheet" class="form-control" type="hidden" style="">
</div>
after searching I want to enter the json results in the table
<table class="table table-bordered" style="width: 100%; cellspacing: 0;">
<thead>
<tr>
<th>Kode Outbound</th>
<th>Kode Resi</th>
</tr>
</thead>
<tbody id="isinya">
</tbody>
</table>
// search by ajax
$(document).ready(function(){
$('#kode').on('input',function(){
var kode=$(this).val();
$.ajax({
type : "POST",
url : "<?php echo base_url('backend/history_status/caris')?>",
dataType : "JSON",
data : {kd_runsheet: kode},
cache:false,
success: function(data) {
jmlData = data.length;
tampung = "";
for (a = 0; a < jmlData; a++) {
tampung += "<tr>" +
"<td>" + (a + 1) + "</td>" +
"<td>" + data[a]["kd_runsheet"] + "</td>" +
"<tr/>";
}
$("tbody")[0].innerHTML += tampung;
}
});
return false;
});
});
Result Json
[
{"id_runsheet":"6","kd_runsheet":"RUNSHEET-0000-0003"},
{"id_runsheet":"6","kd_runsheet":"RUNSHEET-0000-0003"}
]
Model
public function caridb($kode){
$query = $this->db->query("SELECT runsheet.id_runsheet,kd_runsheet FROM runsheet
INNER JOIN runsheet_detail ON runsheet.id_runsheet=runsheet_detail.id_runsheet WHERE kd_runsheet ='$kode'");
return $query->result();
}
Controller
public function caris(){
$id=$this->input->post('kd_runsheet');
$data=$this->M_history_status->caridb($id);
echo json_encode($data);
}
Try something like this. Your markup should be inside a loop.
success: function(data){
var markup = "<tr>
<td><input type='text'></td>
</tr>";
$("#isinya").append(markup);
}
You are getting JSON Object's array
Seperate each JSON Object using loop and add it to table:
success: function(data){
for(i=0;i<data.length;i++){
var row="<tr><td>"+data[i].id_runsheet+"</td><td>"+data[i].kd_runsheet+"</td></tr>";
$("#isinya").append(row); //Adding rows in <tbody>
}
}

How make an array only selected input text values and send array via ajax?

i want to add values in array and want to send on click
i want to store value in array only those user input text i have click not all values store in array.
when i store all value in array its tacking time to update
so i want to update only those value on which user have click or change in usert input text
This is my html code. When I click in one input text then it shows only that value and then I click on another input text then it store first input text value and second input text value.
Meaning, I want an array which can store input text value in an array() whenever I try to store value in array it shows undefined of array
Now I want this array to send via ajax. How can I do this so that all array data goes via ajax
I know array is a collection of similar datatype. So I want to store id in which all ids, reps_value of array store all reps_value and reps_percent of array store all reps_percent value
And I want to submit my form using submit button on click
this is not working on click using seralizeArray() its giving me all input values when i click only two user input text
$(document).on('Click', '.submit_prescription,input', function (e) {
var x = $(this).parent().find("input").serializeArray();
var val[] = $(this).val();
var g[] = $(this).attr("name");
var id[] = $(this).attr("id");
//i am trying to store data in an array i using each loop but its not working properly how to set this loop to sore in array
/* alert(g);
alert(val);
alert(id);
*/
// $.each(x, function(key, values) {
// console.log(key, values.value);
// alert(key, values.value);
// });
// }
// var val = $("input:id").val();
// var val = $("input").val();
var g = $(this).attr("name");
//alert(g);
if (g == 'reps_value') {
// alert('reps_valwwue');
var f = $(this).attr("id");
var d = $(this).val();
var g = $(this).attr("name");
var data2 = "id=" + f + "&reps_value=" + d + "&type=" + g;
$.ajax({
type: "POST",
url: "prescriptionUpdate1",
data: data2,
cache: false,
success: function (data) {
$("#message").html(data);
$("p").addClass("alert alert-success");
},
error: function (err) {
// //alert(err);
}
});
} else {
// alert('reps_percentage');
var f = $(this).attr("id");
var d = $(this).val();
//var data : { reps_percent : d, id : f },
var data2 = "id=" + f + "&reps_percent=" + d + "&type=" + g;
$.ajax({
type: "POST",
url: "prescriptionUpdate1",
data: data2,
cache: false,
success: function (data) {
$("#message").html(data);
$("p").addClass("alert alert-success");
},
error: function (err) {
//alert(err);
}
});
}
});
============================================================
public function prescriptionUpdateData1($data) {
#$id = $data['id'];
#$reps_percent = $data['reps_percent'];
#$reps_value = $data['reps_value'];
$type = $data['type'];
if ($data['type'] == 'reps_value') {
$result = $this - > db - > query("UPDATE dev_prescription SET `reps_value`= '".$reps_value.
"'
WHERE id = '".$id."'
");
}
else {
$result = $this - > db - > query("UPDATE dev_prescription SET `reps_percent`= '".$reps_percent.
"'
WHERE id = '".$id."'
");
}
if ($result) {
return TRUE;
} else {
return $this - > db - > _error_message();
}
}
<td align="center" valign="middle" bgcolor="#F2F2F2" sdval="20" sdnum="1033;"> <font face="Agency-Roman" color="#000000">
<input style="width:90%" type="text" name="reps_value" id="<?php echo $location[2] ?>" value="<?php echo $location[0] ?>" class="" /> </font></td>
<td align="center" valign="middle" bgcolor="#F2F2F2" sdnum="1033;0;0.0%">
<font face="Agency-Roman" size="1" color="#FF0000"> <input style="width:38px" type="text" name="reps_percent" id="<?php echo $location[2] ?>" value="<?php echo $location[1] ?> "class="" /><input style="width:38px" type="hidden" name="id" id="id" value="<?php echo $location[2] ?>" class="" /> </font>
</td> <td align="left" valign="bottom" bgcolor="#FFFFFF"><font color="#000000"><br></font></td>
<td align="center" valign="middle" bgcolor="#F2F2F2" sdval="20" sdnum="1033;">
<font face="Agency-Roman" color="#000000">
<input style="width:90%" type="text" name="reps_value" id="<?php echo $location[5] ?>" value="<?php echo $location[3] ?>"
class="" />
</font>
</td>
<td align="center" valign="middle" bgcolor="#F2F2F2" sdnum="1033;0;0.0%">
<font face="Agency-Roman" size="1" color="#FF0000">
<input style="width:38px" type="text" name="reps_percent" id="<?php echo $location[5] ?>" value="<?php echo $location[4] ?>"
class="" />
<input style="width:38px" type="hidden" name="id" id="id" value="<?php echo $location[5] ?>" class="" />
</font>
</td>
<td align="left" valign="bottom" bgcolor="#FFFFFF">
<font color="#000000"><br></font>
</td>

JQuery Table post Calculate sum in PHP

I have a table that contains Input text that calculate the sum of rows and the sum of coumns in JQuery.
Its posible to send the table in AJAX post to PHP and do the calc of rows and columns there?
This is my table:
<table id="sum_table">
<tr>
<td><input value="0" class="sum1" /></td>
<td><input value="0" class="sum2"/></td>
<td><input value="0" class="sum3"/></td>
<td class="total">0</td>
</tr>
<tr>
<td><input value="0" class="sum1"/></td>
<td><input value="0" class="sum2"/></td>
<td><input value="0" class="sum3"/></td>
<td class="total">0</td>
</tr>
<tr>
<td><input value="0" class="sum1"/></td>
<td><input value="0" class="sum2"/></td>
<td><input value="0" class="sum3"/></td>
<td class="total">0</td>
</tr>
<tr class ="totalCol">
<td>0</td>
<td>0</td>
<td>0</td>
</tr>
</table>
<button id="tabla">+</button>
<button id="moes">Hide/Show</button>
This is How I sum the columns:
//Mostramos y ocultamos la tabla
$("#moes").click(function(){
$("table").toggle();
});
//Sumamos las columnas
$(document).on('keyup change','#sum_table tr:not(.totalCol) input:text',function() {
var $table = $(this).closest('table');
var total = 0;
var thisNumber = $(this).attr('class').match(/(\d+)/)[1];
$table.find('tr:not(.totalCol) .sum'+thisNumber).each(function() {
total += parseInt(this.value);
});
FULL CODE HERE
Thank you in Advance :)
yes, it is.
$(document).ready(function() {
$('#tabla').click(function() {
var col1 = [];
var col2 = [];
var col3 = [];
// collect all data from table col1
$.each($('table td input.sum1'), function(k, v){
col1.push($(v).val());
});
// collect all data from table col2
$.each($('table td input.sum2'), function(k, v){
col2.push($(v).val());
});
// collect all data from table col3
$.each($('table td input.sum3'), function(k, v){
col3.push($(v).val());
});
// send data to server
$.ajax({
url: 'calc.php',
type: 'post',
data: {'col1': col1, 'col2': col2, 'col3': col3,},
dataType: 'json',
success: function(data){
// insert your server-calculated data to dom
$('.totalCol td:nth-child(1)').text(data.SumCol1);
$('.totalCol td:nth-child(2)').text(data.SumCol2);
$('.totalCol td:nth-child(3)').text(data.SumCol3);
}
});
});
});
You can sum up your posts on server in e.g. calc.php:
$SumCol1 = _sumUp($_POST['col1']);
$SumCol2 = _sumUp($_POST['col2']);
$SumCol3 = _sumUp($_POST['col3']);
echo json_encode(array(
"SumCol1" => $SumCol1,
"SumCol2" => $SumCol2,
"SumCol3" => $SumCol3
));
function _sumUp($data)
{
$sum = 0;
foreach($data as $k => $v)
{
$sum += $v;
}
return $sum;
}
NOTE: not tested. Only a basic structure.

jquery multidimensional

I am cloning the last row in table but i need unique multidimensional name for each input...
<tr>
<td><input type="text" name='input[1][Name]'></input></td>
<td><input type="text" name='input[1][address]'></input></td>
<td><input type="text" name='input[1][contactInfo]'></input></td>
</tr>
next row should be
<tr>
<td><input type="text" name='input[2][Name]'></input></td>
<td><input type="text" name='input[2][address]'></input></td>
<td><input type="text" name='input[2][contactInfo]'></input></td>
</tr>
...........
jquery
$(".alternativeRow").click(function(){
i=2;
$("table tr:last").clone().find("input").each(function() {
$(this).attr({
'id': function(_, id) { return id + i },
'name': function(_, name) { return name + i },
'value': ''
});
}).end().appendTo("table");
i++;
});
For multidimensional name no need to give explicit index to the names. directly you can write like this.
<input type="text" name='input[][Name]'></input>
This will automatically take the index no when you receive the form data on server side.
$(".alternativeRow").click(function(){
i=2;
$("table tr:last").clone().find("input").each(function() {
this.name = this.name.replace(/\[(\d+)\]/, function(){
return '[' + i +']';
});
})
.end().appendTo("table");
i++;
});

Categories