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.
Related
I have html form that allowed to insert multiple input. I am able to insert only first input. How to insert multiple value in php passing through ajax, My HTML form is as below.
<tr>
<th>ID</th>
<td><input type="number" id="navid"></td>
</tr>
<tr>
<th>Menu IN</th>
<td><input type="text" name="menuin"></input></td>
</tr>
<tr>
<th>Menu ENG</th>
<td><input type="text" name="menueng"></input>
</td>
</tr>
User can add input field dynamically(dynamic add has be done by jquery)
It is not problem to pass if only one input group. But I want to pass multiple input if user add more than one.
And I've passed value as
$("#submit").click(function(){
var navid = $("#navid").val();
var menuin = $("input[name='menuin']").val();
var menueng = $("input[name='menueng']").val();
$.ajax({
url: 'insert_nav.php',
type: 'post',
data: {navid:navid,menuin:menuin,menueng:menueng},
success: function(data){
alert(data);
$('#nav')[0].reset();
}
});
});
I've inserted input values passed by ajax as below
if (isset($_POST["navid"]) && !empty($_POST["navid"])) {
$query1 =$con->prepare("INSERT INTO menu(cid, title, en_title) VALUES (:navid, :menuin, :menueng)");
$query1->bindParam(':menuin',$_POST["menuin"]);
$query1->bindParam(':menueng',$_POST["menueng"]);
$query1->bindParam(':navid', $_POST["navid"]);
$query1->execute();
$msg1 = 'Menu has inserted';
}
Now I want to insert multiple values. How to do ?
You have to apply array in input field for multiple input element. And pass array through ajax and insert to database using foreach loop.
HTML
<tr>
<th>ID</th>
<input type="number" name="navid[]" id="navid">
</tr>
<tr>
<th>Menu IN</th>
<td><input type="text" name="menuin[]"></input></td>
</tr>
<tr>
<th>Menu ENG</th>
<td><input type="text" name="menueng[]"></input>
</td>
</tr>
Ajax
$("#submit").click(function(){
var navid = [];
$('input[name="navid[]"]').each( function() {
navid.push(this.value);
});
var menuin = [];
$('input[name="menuin[]"]').each( function() {
menuin.push(this.value);
});
var menueng = [];
$('input[name="menueng[]"]').each( function() {
menueng.push(this.value);
});
$.ajax({
url: 'insert_nav.php',
type: 'post',
data: {navid:navid,menuin:menuin,menueng:menueng},
success: function(data){
alert(data);
$('#nav')[0].reset();
}
});
});
PHP
foreach ($_POST["navid"] AS $key => $item){
$query1 =$con->prepare("INSERT INTO menu(cid, title, en_title) VALUES (:navid, :menuin, :menueng)");
$query1->bindParam(':menuin',$_POST["menuin"][$key]);
$query1->bindParam(':menueng',$_POST["menueng"][$key]);
$query1->bindParam(':navid',$item);
$query1->execute();
$msg1 = 'Menu has inserted';
}
HTML:
<form id="the_form">
<tr>
<th>ID</th>
<td><input type="number" name="navid[]" id="navid"></td>
</tr>
<tr>
<th>Menu IN</th>
<td><input type="text" name="menuin[]"></input></td>
</tr>
<tr>
<th>Menu ENG</th>
<td><input type="text" name="menueng[]"></input>
</td>
</tr>
<input type="submit" value="Submit Form" id="submit"/>
</form>
I added a name for your ID so that it will be included when you submit the form, I just added a form tag since it was not present in your question.
JS:
Read about serialize
(https://stackoverflow.com/questions/15173965/serializing-and-submitting-a-form-with-jquery-post-and-php)
$("#submit").click(function(){
var form_data = $("#the_form").serialize();
$.ajax({
url: 'insert_nav.php',
type: 'post',
data: {form_data:form_data},
success: function(data){
alert(data);
$('#nav')[0].reset();
}
});
});
PHP
//Since the submitted data is now a collection of an array you'll have to loop through it to save them in the database as you cannot save an array directly in a DB.
if (!empty($_POST["navid"])) {
for($counter = 0; $counter < sizeof($_POST["navid"]); $counter++){
$query1 =$con->prepare("INSERT INTO menu(cid, title, en_title) VALUES (:navid, :menuin, :menueng)");
$query1->bindParam(':menuin',$_POST["menuin"][$counter]);
$query1->bindParam(':menueng',$_POST["menueng"][$counter]);
$query1->bindParam(':navid', $_POST["navid"][$counter]);
$query1->execute();
$msg1 = 'Menu has inserted';
}
}
I have a form where I am selecting a product. On the basis of the selected product, I want to update the rest of the fields in the form.
The Form display with select option
On selecting the product name, I want rest of the details of the form to fill up from the database using php.
Here is the code for the table created.
<table id="productTable" class="table-c">
<tr>
<th class="text-center" style="width: 5%;">SR No.</th>
<th class="text-center" style="width: 45%">DESCRIPTION</th>
<th class="text-center" style="width: 10%">HSN/SAC</th>
<th class="text-center" style="width: 10%">QTY IN-HAND</th>
<th class="text-center" style="width: 10%">ENTER OUTWARD QTY</th>
<th class="text-center" style="width: 5%">Delete</th>
</tr>
<tr style="text-align: center;" id="products">
<?php $j=0; $j++; ?>
<td><?php echo $j; ?></td>
<td><select class="form-control" name="code" id="productID" style="width: 429px;">
<?php
$sql = "SELECT * FROM `product`";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<option id='".$row['code']."' value='".$row['pname']."'>".$row['pname']."</option>";
}
} else {
echo "0 results";
}
?>
</select>
</td>
<td><input type="number" name="hsnNo" id="hsnNo" readonly></td>
<td><input type="number" name="qty" id="qty" readonly></td>
<td class="coljoin"><input type="number" format="2" name="amount"></td>
<td>
<span class="fa fa-trash"></span>
</td>
</tr>
</table>
How should I do this?
This is PHP Code:-
<form>
<select name="customer" id="customer_id">
<option value="">-- Select customer Name -- </option>
<option value="1">John</option>
<option value="2">Smith</option>
</select>
Address: <input name="add" type="text" value="">
Mobile: <input name="mobile" type="text" value="">
EMail-Id:<input name="email" type="text" value="">
</form>
This is JS Code:-
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#customer_id").change(function() {
var id = $(this).val();
var dataString = 'cid='+id;
//alert(dataString);
$.ajax({
url: 'dataAjax.php',
type: 'post',
data: dataString,
success: function(response) {
// Parse the jSON that is returned
var Vals = JSON.stringify(response);
// These are the inputs that will populate
$("input[name='add']").val(Vals.add);
$("input[name='mobile']").val(Vals.mobile);
$("input[name='email']").val(Vals.email);
}
});
});
});
</script>
This is other PHP File Code:-
<?php
// This is where you would do any database call
if(!empty($_POST)) {
// Send back a jSON array via echo
echo json_encode(array("add"=>'India',"mobile"=>'1234567890','email'=>'demo#demo.com'));
}
?>
using product id use ajax & call the get_product_details(id) & in get product convert response array in json & echo it .in ajax, response data you have to parse in json... then set you required field.. (add require js)
**Ajax Call :**
$(document).on('change','your_dropdown_filed_id',function()
{
var product_id = $(this).val();
//Ajax call
$.ajax({
method: "POST",
url: "/get_product_details", //your php file function path
data: { product_id: product_id}
}).done(function( response ) {
alert( "Data Saved: " + response );
var obj = JSON.parse(response);
//obj hold all values
alert(obj.qty);
alert(obj.hsn);
$('#hsn_id').val(obj.hsn);
$('#qty_id').val(obj.qty);
});
});
**product.php**
function get_product_details(product_id)
{
//Get product details in associative array format
echo json_encode($product_details);
}
Once the product is selected execute ajax request and get data from the database with respective of the selected product.
JAVASCRIPT CODE :
$('#products').change(function(){
$.ajax({
url: 'your php code page name which returns product details.php?product_id'+$('#products').val(),
type: 'post',
success: function(response) {
var obj = JSON.parse(response);
$("#hsn_sac").val(obj.hsn_sac); // hsn or sac values
$("#qty_in_hand").val(obj.qty_in_hand); // qty_in_hand values
}
}});
});
PHP CODE :
<?php
// first connect database and then fire the query to get product details
$connection = mysql_connect("your database host name","database username","database password","database name");
$result = mysql_query("your query");
while ($row = mysql_fetch_array($result)) {
// get data and store in array
}
mysql_close($connection); // close connection
echo json_encode(database result); // encode database result so that it will available to ajax request and assign back to view
exit;
?>
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";
}
<a class="checkModelButton" href="check.php">Check</a>
<div id="model_list"></div>
include jquery and function deleteRow():
jQuery('.checkModelButton').click(function(event){
event.preventDefault();
var url = jQuery(this).attr('href');
jQuery.ajax({
type: 'get',
cache: false,
url: url,
success: function(html){
jQuery('#model_list').html(html);
}
});
});
function deleteRow(id) {
try {
var table = document.getElementById('model_list');
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) {
table.deleteRow(i);
rowCount--;
i--;
}
}
jQuery("input[type=checkbox]:checked").each(function() {
jQuery(this).parents("tr").remove();
});
} catch(e) {
alert(e);
}
}
in check.php return html is:
<input type="button" value="Delete Row" onclick="deleteRow('model_list')" />
<table id="model_list">
<thead>
<tr>
<th>#</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="checkbox" value="1" name="model_id[]" class="item"></td>
<td>Nokia N71</td>
</tr>
</tbody>
</table>
After loadding ajax, I checked on form input and click button Delete Row, but error can't delete this row And error is alert(Table model_list is empty), how to fix it ?
jQuery has really simplified the selection process for us and also provided a lot of fail-safes that JavaScript doesn't offer without a try/catch block.
Since you're already using jQuery, you can really simplify your deleteRow() function by doing the following:
function deleteRow(id) { // the id variable is unnecessary and can be removed
// Grab all the rows in the table (the > sign targets the elements directly inside the current one (not cascading)
var rows = jQuery("#model_list > tbody > tr");
// Iterate through the rows
jQuery(rows).each(function(key, value) {
// Look inside each row for a checked checkbox
if (jQuery(this).find("input:checkbox[checked='checked']").length > 0) {
// If one is found, then remove the whole row (jQuery(this) refers to the current row
jQuery(this).remove();
}
});
}
To make the example above work, I created a temporary table in the same file. Since you are dynamically loading the table rows with data, this should function similar to the static sample below:
<input type="button" value="Delete Row" onclick="deleteRow('model_list')" />
<table id="model_list">
<thead>
<tr>
<th>#</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="checkbox" value="1" name="model_id[]" class="item"></td>
<td>Nokia N71</td>
</tr>
<tr>
<td><input type="checkbox" value="2" name="model_id[]" class="item"></td>
<td>Nokia N72</td>
</tr>
<tr>
<td><input type="checkbox" value="3" name="model_id[]" class="item"></td>
<td>Nokia N73</td>
</tr>
</tbody>
</table>
Please let me know if this is helpful or if you have any other questions. :)
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.