ajax is not working inside for loop - javascript

i am creating an dynamic invoice stystem... if i select itemcode then it displays item brand of that item code in my brand input id..if i add new item
then i click on plus button to add new item then i again select a new item code2 then it displays item brand2 of that item code2...so this loop is going on agiain and agian.
my ajax call is not working or some error in ajax code....i cant find the error..if i dint use ajax call only display data of selected var itemp then it displays selected data itemp in brand but using ajax call and find brand of selected data itemp it didn't works.. please anyone can help me.
here is my javascript ajax call...
function getprods(val) {
for (j = 1; j <= count; j++) {
var itemp = $('#item_code' + j).val();
$.ajax({
url: 'ajax_getitems.php',
type: 'POST',
data: 'state_id=' + itemp,
dataType: 'json',
success: function (data) {
var len = data.length;
if (len > 0) {
var id = data[0]['id'];
var brand = data[0]['brand'];
document.getElementById('brand' + j).value = brand;
}
}
});
}
}
And here is my ajax_getitems.php file
<?php
include('conn.php');
$model = $_POST['state_id'];
$sql = "SELECT * FROM product WHERE code='$model'";
$result = mysqli_query($conn, $sql);
$users_arr = array();
while ($row = mysqli_fetch_array($result)) {
$id = $row['id'];
$brand = $row['brand'];
$users_arr[] = array("id" => $id,
"brand" => $brand
);
}
// encoding array to json format
echo json_encode($users_arr);
exit;
?>
here is my full html code
<!DOCTYPE html>
<html lang="en">
<head>
<title></title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="robots" content="noindex, nofollow">
<link rel="stylesheet" href="css2/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="quotation/jquery-ui.min.css">
<script src="js2/jquery.min.js"></script>
<script src="js2/bootstrap.min.js"></script>
<script src="quotation/js/jquery-ui.js"></script>
<script src="js2/jquery.dataTables.min.js"></script>
<script src="js2/dataTables.bootstrap.min.js"></script>
<link rel="stylesheet" href="css2/dataTables.bootstrap.min.css">
<style>
/* Remove the navbar's default margin-bottom and rounded borders */
.navbar {
margin-bottom: 4px;
border-radius: 0;
}
/* Add a gray background color and some padding to the footer */
footer {
background-color: #f2f2f2;
padding: 25px;
}
.carousel-inner img {
width: 100%; /* Set width to 100% */
margin: auto;
min-height:200px;
}
.navbar-brand
{
padding:5px 40px;
}
.navbar-brand:hover
{
background-color:#ffffff;
}
/* Hide the carousel text when the screen is less than 600 pixels wide */
#media (max-width: 600px) {
.carousel-caption {
display: none;
}
}
</style>
</head>
<body>
<style>
.box
{
width: 100%;
max-width: 1390px;
border-radius: 5px;
border:1px solid #ccc;
padding: 15px;
margin: 0 auto;
margin-top:50px;
box-sizing:border-box;
}
</style>
<link rel="stylesheet" href="css2/datepicker.css">
<script src="js2/bootstrap-datepicker1.js"></script>
<script>
$(document).ready(function(){
$('#order_date').datepicker({
format: "yyyy-mm-dd",
autoclose: true
});
});
</script>
<script>
$(document).ready(function(){
$(document).on('keydown', '.name', function() {
var id = this.id;
var splitid = id.split('_');
var index = splitid[1];
$( '#'+id ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "getDetails.php",
type: 'post',
dataType: "json",
data: {
search: request.term,request:1
},
success: function( data ) {
response( data );
}
});
},
select: function (event, ui) {
$(this).val(ui.item.label); // display the selected text
var userid = ui.item.value; // selected id to input
// AJAX
$.ajax({
url: 'getDetails.php',
type: 'post',
data: {userid:userid,request:2},
dataType: 'json',
success:function(response){
var len = response.length;
if(len > 0){
var id = response[0]['id'];
var phone = response[0]['phone'];
var email = response[0]['email'];
var address = response[0]['address'];
var gst = response[0]['gst'];
document.getElementById('phone').value = phone;
document.getElementById('email').value = email;
document.getElementById('address').value = address;
document.getElementById('gst').value = gst;
}
}
});
return false;
}
});
});
});
function getproduct(val) {
$.ajax({
url: 'ajax_getproduct.php',
type: 'POST',
data: 'state_id='+val,
dataType: 'json',
success:function(data){
var len = data.length;
if(len > 0){
var id = data[0]['id'];
var item = data[0]['item'];
var subcat = data[0]['subcat'];
var brand = data[0]['brand'];
var model = data[0]['model'];
var specification = data[0]['specification'];
var unitrate = data[0]['unitrate'];
var unitmesure = data[0]['unitmesure'];
document.getElementById('item').value = item;
document.getElementById('subcat').value = subcat;
document.getElementById('brand').value = brand;
document.getElementById('model').value = model;
document.getElementById('Specification').value = specification;
document.getElementById('unitrate1').value = unitrate;
document.getElementById('unitmesure').value = unitmesure;
}
}
});
}
</script>
<div class="container-fluid">
<form method="post" id="invoice_form">
<div class="table-responsive">
<table class="table table-bordered">
<tr>
<td colspan="2" align="center"><h2 style="margin-top:10.5px">Create Quotation</h2></td>
</tr>
<tr>
<td colspan="2">
<div class="row">
<div class="col-md-8">
To,<br />
<b>RECEIVER (BILL TO)</b><br />
<input type="text" name="name" id="name" class="form-control name" placeholder="Enter Receiver Name" />
<textarea name="address" id="address" class="form-control" placeholder="Enter Billing Address"></textarea>
</div>
<div class="col-md-4">
<br />
<input type="text" name="phone" id="phone" class="form-control input-sm" placeholder="Phone No." />
<input type="text" name="email" id="email" class="form-control input-sm" placeholder="Email" />
<input type="text" name="gst" id="gst" class="form-control input-sm" placeholder="GST" />
</div>
</div>
<br />
<table id="invoice-item-table" class="table table-bordered">
<tr>
<th>Sr No.</th>
<th>Item Code</th>
<th>Brand</th>
<th>Model</th>
<th>Specification</th>
<th>Unit Rate</th>
<th>Quantity</th>
<th>Actual Amt.</th>
<th colspan="2">Discount (%)</th>
<th rowspan="2">Total</th>
<th rowspan="2"></th>
</tr>
<tr>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th>Rate</th>
<th></th>
<th>Amt.</th>
</tr>
<tr>
<td><span id="sr_no">1</span></td>
<td><select type="text" name="item_code[]" id="item_code" class="form-control input-sm" onChange="getproduct(this.value);" >
<option value=""></option>
<?php
include "conn.php";
$sql = "SELECT * FROM `product`";
$run = mysqli_query($conn,$sql);
while($row=mysqli_fetch_array($run))
{
?>
<option><?php echo $row['code']; ?></option>
<?php } ?>
</select>
<input type="hidden" name="item[]" id="item">
<input type="hidden" name="subcat[]" id="subcat">
</td>
<td>
<input type="text" name="brand[]" id="brand" class="form-control input-sm" readonly>
</td>
<td>
<input type="text" name="model[]" id="model" class="form-control input-sm" readonly>
</td>
<td>
<textarea name="Specification[]" id="Specification" class="form-control" readonly></textarea>
</td>
<td><input type="text" name="unitrate[]" id="unitrate1" data-srno="1" class="form-control input-sm unitrate" />
<input type="hidden" name="unitmesure" id="unitmesure">
</td>
<td><input type="text" name="qty[]" id="qty1" data-srno="1" class="form-control input-sm number_only qty" /></td>
<td><input type="text" name="order_item_actual_amount[]" id="order_item_actual_amount1" data-srno="1" class="form-control input-sm order_item_actual_amount" readonly /></td>
<td><input type="text" name="order_item_tax1_rate[]" id="order_item_tax1_rate1" data-srno="1" class="form-control input-sm number_only order_item_tax1_rate" /></td>
<td><input type="text" name="order_item_tax1_amount[]" id="order_item_tax1_amount1" data-srno="1" readonly class="form-control input-sm order_item_tax1_amount" /></td>
<td><input type="text" name="order_item_final_amount[]" id="order_item_final_amount1" data-srno="1" readonly class="form-control input-sm order_item_final_amount" /></td>
<td></td>
</tr>
</table>
<div align="right">
<button type="button" name="add_row" id="add_row" class="btn btn-success btn-xs">+</button>
</div>
</td>
</tr>
<tr>
<td align="right"><b>Total</td>
<td align="right"><b><span id="final_total_amt"></span></b></td>
</tr>
<tr>
<td colspan="2"></td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="hidden" name="total_item" id="total_item" value="1" />
<input type="submit" name="create_invoice" id="create_invoice" class="btn btn-info" value="Create" />
</td>
</tr>
<tr>
</tr>
</table>
</div>
</form>
<script>
$(document).ready(function(){
var final_total_amt = $('#final_total_amt').text();
var count = 1;
$(document).on('click', '#add_row', function(){
count++;
$('#total_item').val(count);
var html_code = '';
html_code += '<tr id="row_id_'+count+'">';
html_code += '<td><span id="sr_no">'+count+'</span></td>';
html_code += '<td><select name="item_code[]" id="item_code'+count+'" class="form-control input-sm item_code"><option></option><?php $sql='Select * from product'; $run=mysqli_query($conn,$sql); while($row=mysqli_fetch_array($run)){ echo '<option>'.$row['code'].'</option>'; } ?></select><input type="hidden" name="item[]" id="item'+count+'"><input type="hidden" name="subcat[]" id="subcat'+count+'"></td>';
html_code += '<td><input type="text" name="brand[]" id="brand'+count+'" class="form-control input-sm" readonly></td>';
html_code += '<td><input type="text" name="model[]" id="model'+count+'" class="form-control input-sm" readonly></td>';
html_code += '<td><textarea name="Specification[]" id="Specification'+count+'" class="form-control" readonly></textarea></td>';
html_code += '<td><input type="text" name="unitrate[]" id="unitrate'+count+'" data-srno="'+count+'" class="form-control input-sm number_only unitrate" /><input type="hidden" name="unitmesure[]" id="unitmesure'+count+'"></td>';
html_code += '<td><input type="text" name="qty[]" id="qty'+count+'" data-srno="'+count+'" class="form-control input-sm number_only qty" /></td>';
html_code += '<td><input type="text" name="order_item_actual_amount[]" id="order_item_actual_amount'+count+'" data-srno="'+count+'" class="form-control input-sm order_item_actual_amount" readonly /></td>';
html_code += '<td><input type="text" name="order_item_tax1_rate[]" id="order_item_tax1_rate'+count+'" data-srno="'+count+'" class="form-control input-sm number_only order_item_tax1_rate" /></td>';
html_code += '<td><input type="text" name="order_item_tax1_amount[]" id="order_item_tax1_amount'+count+'" data-srno="'+count+'" readonly class="form-control input-sm order_item_tax1_amount" /></td>';
html_code += '<td><input type="text" name="order_item_final_amount[]" id="order_item_final_amount'+count+'" data-srno="'+count+'" readonly class="form-control input-sm order_item_final_amount" /></td>';
html_code += '<td><button type="button" name="remove_row" id="'+count+'" class="btn btn-danger btn-xs remove_row">X</button></td>';
html_code += '</tr>';
$('#invoice-item-table').append(html_code);
});
$(document).on('click', '.remove_row', function(){
var row_id = $(this).attr("id");
var total_item_amount = $('#order_item_final_amount'+row_id).val();
var final_amount = $('#final_total_amt').text();
var result_amount = parseFloat(final_amount) - parseFloat(total_item_amount);
$('#final_total_amt').text(result_amount);
$('#row_id_'+row_id).remove();
count--;
$('#total_item').val(count);
});
function cal_final_total(count)
{
var final_item_total = 0;
for(j=1; j<=count; j++)
{
var quantity = 0;
var price = 0;
var actual_amount = 0;
var tax1_rate = 0;
var tax1_amount = 0;
var tax2_rate = 0;
var tax2_amount = 0;
var tax3_rate = 0;
var tax3_amount = 0;
var item_total = 0;
quantity = $('#unitrate'+j).val();
if(quantity > 0)
{
price = $('#qty'+j).val();
if(price > 0)
{
actual_amount = parseFloat(quantity) * parseFloat(price);
$('#order_item_actual_amount'+j).val(actual_amount);
tax1_rate = $('#order_item_tax1_rate'+j).val();
if(tax1_rate > 0)
{
tax1_amount = -(parseFloat(actual_amount)*parseFloat(tax1_rate)/100);
$('#order_item_tax1_amount'+j).val(tax1_amount);
}
item_total = parseFloat(actual_amount) + parseFloat(tax1_amount) + parseFloat(tax2_amount) + parseFloat(tax3_amount);
final_item_total = parseFloat(final_item_total) + parseFloat(item_total);
$('#order_item_final_amount'+j).val(item_total);
}
}
}
$('#final_total_amt').text(final_item_total);
}
function getprods()
{
for(j=1; j<=count; j++)
{
var itemp = $('#item_code'+j).val();
$.ajax({
url: 'ajax_getitems.php',
type: 'POST',
data: 'state_id='+itemp,
dataType: 'json',
success:function(data){
var len = data.length;
if(len > 0){
var id = data[0]['id'];
var brand = data[0]['brand'];
document.getElementById('brand'+j).value = brand;
}
}
});
}
}
$(document).on('blur', '.qty', function(){
cal_final_total(count);
});
$(document).on('blur', '.order_item_tax1_rate', function(){
cal_final_total(count);
});
$(document).on('change', '.item_code', function(){
getprods(this.value);
});
$('#create_invoice').click(function(){
if($.trim($('#order_receiver_name').val()).length == 0)
{
alert("Please Enter Reciever Name");
return false;
}
if($.trim($('#order_no').val()).length == 0)
{
alert("Please Enter Invoice Number");
return false;
}
if($.trim($('#order_date').val()).length == 0)
{
alert("Please Select Invoice Date");
return false;
}
for(var no=1; no<=count; no++)
{
if($.trim($('#item_name'+no).val()).length == 0)
{
alert("Please Enter Item Name");
$('#item_name'+no).focus();
return false;
}
if($.trim($('#unitrate'+no).val()).length == 0)
{
alert("Please Enter Quantity");
$('#unitrate'+no).focus();
return false;
}
if($.trim($('#qty'+no).val()).length == 0)
{
alert("Please Enter Price");
$('#qty'+no).focus();
return false;
}
}
$('#invoice_form').submit();
});
});
</script>
<script>
$(document).ready(function(){
$('.number_only').keypress(function(e){
return isNumbers(e, this);
});
function isNumbers(evt, element)
{
var charCode = (evt.which) ? evt.which : event.keyCode;
if (
(charCode != 46 || $(element).val().indexOf('.') != -1) && // “.” CHECK DOT, AND ONLY ONE.
(charCode < 48 || charCode > 57))
return false;
return true;
}
});
</script>
</body>
</html>
<?php
include('conn2.php');
if(isset($_POST['create_invoice']))
{
$order_receiver_name=$_POST['order_receiver_name'];
$order_receiver_address=$_POST['order_receiver_address'];
$order_no=$_POST['order_no'];
$order_date=$_POST['order_date'];
$order_total_before_tax = 0;
$order_total_tax1 = 0;
$order_total_tax2 = 0;
$order_total_tax3 = 0;
$order_total_tax = 0;
$order_total_after_tax = 0;
date_default_timezone_set('Asia/Kolkata');
$current = date('d-m-Y H:i:s');
$sql = "INSERT INTO `tbl_order`(`order_no`, `order_date`, `order_receiver_name`, `order_receiver_address`, `order_total_before_tax`, `order_total_tax1`, `order_total_tax2`, `order_total_tax3`, `order_total_tax`, `order_total_after_tax`, `order_datetime`) VALUES ('$order_no','$order_date','$order_receiver_name','$order_receiver_address','$order_total_before_tax','$order_total_tax1','$order_total_tax2','$order_total_tax3','$order_total_tax','$order_total_after_tax','$current')";
$run = mysqli_query($conn, $sql);
if($run)
{
echo "<script>alert('Inserted Successfully')</script>";
}
else{
echo("Error description: " . mysqli_error($conn));
}
$last_id = mysqli_insert_id($conn);
for($count=0; $count<$_POST["total_item"]; $count++)
{
$item_name = $_POST['item_name'][$count];
$unitrate = $_POST['unitrate'][$count];
$qty = $_POST['qty'][$count];
$order_item_actual_amount = $_POST['order_item_actual_amount'][$count];
$order_item_tax1_rate = $_POST['order_item_tax1_rate'][$count];
$order_item_tax1_amount = $_POST['order_item_tax1_amount'][$count];
$order_item_tax2_rate = $_POST['order_item_tax2_rate'][$count];
$order_item_tax2_amount = $_POST['order_item_tax2_amount'][$count];
$order_item_tax3_rate = $_POST['order_item_tax3_rate'][$count];
$order_item_tax3_amount = $_POST['order_item_tax3_amount'][$count];
$order_item_final_amount = $_POST['order_item_final_amount'][$count];
$sql2 = "INSERT INTO `tbl_order_item`(`order_id`, `item_name`, `order_item_quantity`, `order_item_price`, `order_item_actual_amount`, `order_item_tax1_rate`, `order_item_tax1_amount`, `order_item_tax2_rate`, `order_item_tax2_amount`, `order_item_tax3_rate`, `order_item_tax3_amount`, `order_item_final_amount`) VALUES ('$last_id','$item_name','$order_item_quantity','$order_item_price','$order_item_actual_amount','$order_item_tax1_rate','$order_item_tax1_amount','$order_item_tax2_rate','$order_item_tax2_amount','$order_item_tax3_rate','$order_item_tax3_amount','$order_item_final_amount')";
$run2 = mysqli_query($conn, $sql2);
if($run2)
{
echo "<script>alert('inserted successfully')</script>";
}
else{
echo("Error description: " . mysqli_error($conn));
}
$order_total_before_tax = $order_total_before_tax + floatval(trim($_POST["order_item_actual_amount"][$count]));
$order_total_tax1 = $order_total_tax1 + floatval(trim($_POST["order_item_tax1_amount"][$count]));
$order_total_tax2 = $order_total_tax2 + floatval(trim($_POST["order_item_tax2_amount"][$count]));
$order_total_tax3 = $order_total_tax3 + floatval(trim($_POST["order_item_tax3_amount"][$count]));
$order_total_after_tax = $order_total_after_tax + floatval(trim($_POST["order_item_final_amount"][$count]));
}
$order_total_tax = $order_total_tax1 + $order_total_tax2 + $order_total_tax3;
$sql3 = "UPDATE `tbl_order` SET `order_total_before_tax`='$order_total_before_tax',`order_total_tax1`='$order_total_tax1',`order_total_tax2`='$order_total_tax2',`order_total_tax3`='$order_total_tax3',`order_total_tax`='$order_total_tax',`order_total_after_tax`='$order_total_after_tax' WHERE `order_id`='$last_id'";
$run3 = mysqli_query($conn, $sql3);
if($run3)
{
echo "<script>alert('inserted successfully')</script>";
}
else{
echo("Error description: " . mysqli_error($conn));
}
}
?>

Edit your php file as below.
<?php
include('conn.php');
$model = $_POST['state_id'];
$sql = "SELECT * FROM product WHERE code='$model'";
$result = mysqli_query($conn, $sql);
// encoding array to json format
echo json_encode($result);
exit;
?>
Then edit your ajax part like below,
function getprods(itemp) {
$.ajax({
url: 'ajax_getitems.php',
type: 'POST',
data: { 'state_id':itemp },
cache: false,
success: function (data) {
var json = $.parseJSON(data);
$.each(json, function (index, item) {
var id = item.id;
var brand = item.brand;
document.getElementById('brand' + index).value = brand;
}
}
});
}

adding property async: false inside ajax may solve this issue.
$.ajax({
url:"get_response_filter.php",
method: "POST",
dataType: 'json',
async: false,

j <= count;
But where is 'count' var?

Related

Calculate gst for receipt

This is actually for a shop receipt but i need to regenerate it into a school receipt. ie, i need the tax1 value auto generate as 5% and tax2 auto genetrate as 6% and calculate it
and also no quantity needed.
<script>
$(document).ready(function(){
var final_total_amt = $('#final_total_amt').text();
var count = 1;
$(document).on('click', '#add_row', function(){
count++;
$('#total_item').val(count);
var html_code = '';
html_code += '<tr id="row_id_'+count+'">';
html_code += '<td><span id="sr_no">'+count+'</span></td>';
html_code += '<td><input type="text" name="item_name[]" id="item_name'+count+'" class="form-control input-sm" /></td>';
html_code += '<td><input type="text" name="order_item_quantity[]" id="order_item_quantity'+count+'" data-srno="'+count+'" class="form-control input-sm number_only order_item_quantity" /></td>';
html_code += '<td><input type="text" name="order_item_price[]" id="order_item_price'+count+'" data-srno="'+count+'" class="form-control input-sm number_only order_item_price" /></td>';
html_code += '<td><input type="text" name="order_item_actual_amount[]" id="order_item_actual_amount'+count+'" data-srno="'+count+'" class="form-control input-sm order_item_actual_amount" readonly /></td>';
html_code += '<td><input type="text" name="order_item_tax1_rate[]" id="order_item_tax1_rate'+count+'" data-srno="'+count+'" class="form-control input-sm number_only order_item_tax1_rate" /></td>';
html_code += '<td><input type="text" name="order_item_tax1_amount[]" id="order_item_tax1_amount'+count+'" data-srno="'+count+'" readonly class="form-control input-sm order_item_tax1_amount" /></td>';
html_code += '<td><input type="text" name="order_item_tax2_rate[]" id="order_item_tax2_rate'+count+'" data-srno="'+count+'" class="form-control input-sm number_only order_item_tax2_rate" /></td>';
html_code += '<td><input type="text" name="order_item_tax2_amount[]" id="order_item_tax2_amount'+count+'" data-srno="'+count+'" readonly class="form-control input-sm order_item_tax2_amount" /></td>';
html_code += '<td><input type="text" name="order_item_tax3_rate[]" id="order_item_tax3_rate'+count+'" data-srno="'+count+'" class="form-control input-sm number_only order_item_tax3_rate" /></td>';
html_code += '<td><input type="text" name="order_item_tax3_amount[]" id="order_item_tax3_amount'+count+'" data-srno="'+count+'" readonly class="form-control input-sm order_item_tax3_amount" /></td>';
html_code += '<td><input type="text" name="order_item_final_amount[]" id="order_item_final_amount'+count+'" data-srno="'+count+'" readonly class="form-control input-sm order_item_final_amount" /></td>';
html_code += '<td><button type="button" name="remove_row" id="'+count+'" class="btn btn-danger btn-xs remove_row">X</button></td>';
html_code += '</tr>';
$('#invoice-item-table').append(html_code);
});
$(document).on('click', '.remove_row', function(){
var row_id = $(this).attr("id");
var total_item_amount = $('#order_item_final_amount'+row_id).val();
var final_amount = $('#final_total_amt').text();
var result_amount = parseFloat(final_amount) - parseFloat(total_item_amount);
$('#final_total_amt').text(result_amount);
$('#row_id_'+row_id).remove();
count--;
$('#total_item').val(count);
});
function cal_final_total(count)
{
var final_item_total = 0;
for(j=1; j<=count; j++)
{
var quantity = 0;
var price = 0;
var actual_amount = 0;
var tax1_rate = 0;
var tax1_amount = 0;
var tax2_rate = 0;
var tax2_amount = 0;
var tax3_rate = 0;
var tax3_amount = 0;
var item_total = 0;
quantity = $('#order_item_quantity'+j).val();
if(quantity > 0)
{
price = $('#order_item_price'+j).val();
if(price > 0)
{
actual_amount = parseFloat(quantity) * parseFloat(price);
$('#order_item_actual_amount'+j).val(actual_amount);
tax1_rate = $('#order_item_tax1_rate'+j).val();
if(tax1_rate > 0)
{
tax1_amount = parseFloat(actual_amount)*parseFloat(tax1_rate)/100;
$('#order_item_tax1_amount'+j).val(tax1_amount);
}
tax2_rate = $('#order_item_tax2_rate'+j).val();
if(tax2_rate > 0)
{
tax2_amount = parseFloat(actual_amount)*parseFloat(tax2_rate)/100;
$('#order_item_tax2_amount'+j).val(tax2_amount);
}
tax3_rate = $('#order_item_tax3_rate'+j).val();
if(tax3_rate > 0)
{
tax3_amount = parseFloat(actual_amount)*parseFloat(tax3_rate)/100;
$('#order_item_tax3_amount'+j).val(tax3_amount);
}
item_total = parseFloat(actual_amount) + parseFloat(tax1_amount) + parseFloat(tax2_amount) + parseFloat(tax3_amount);
final_item_total = parseFloat(final_item_total) + parseFloat(item_total);
$('#order_item_final_amount'+j).val(item_total);
}
}
}
$('#final_total_amt').text(final_item_total);
}
$(document).on('blur', '.order_item_price', function(){
cal_final_total(count);
});
$(document).on('blur', '.order_item_tax1_rate', function(){
cal_final_total(count);
});
$(document).on('blur', '.order_item_tax2_rate', function(){
cal_final_total(count);
});
$(document).on('blur', '.order_item_tax3_rate', function(){
cal_final_total(count);
});
$('#create_invoice').click(function(){
if($.trim($('#order_receiver_name').val()).length == 0)
{
alert("Please Enter Reciever Name");
return false;
}
if($.trim($('#order_no').val()).length == 0)
{
alert("Please Enter Invoice Number");
return false;
}
if($.trim($('#order_date').val()).length == 0)
{
alert("Please Select Invoice Date");
return false;
}
for(var no=1; no<=count; no++)
{
if($.trim($('#item_name'+no).val()).length == 0)
{
alert("Please Enter Item Name");
$('#item_name'+no).focus();
return false;
}
if($.trim($('#order_item_quantity'+no).val()).length == 0)
{
alert("Please Enter Quantity");
$('#order_item_quantity'+no).focus();
return false;
}
if($.trim($('#order_item_price'+no).val()).length == 0)
{
alert("Please Enter Price");
$('#order_item_price'+no).focus();
return false;
}
}
$('#invoice_form').submit();
});
});
</script>
I dont know how to recode this to a school receipt. please any can recode this with this same values like no quanitity required , tax1 should be having default value as 5% and tax2 with value 6% and calculate it

How To Explain All data with parameter in javascript

Hi guys i have an issue for displaying all data where a column with name header_id having same data. but when it displayed, his result
just one row. actually of data with header_id='100002' having 4 rows.Thanks.
Model:
function getdtHeaderid($header_id = FALSE) {
if ($header_id === FALSE)
{
$query = $this->db1->get('tbltransactiondtl');
return $query->result_array();
}
$query = $this->db1->get_where('tbltransactiondtl', array('header_id' => $header_id));
return $query->row_array();
}
Controller:
function getdtHeaderid() {
$header_id = $this->input->post('header_id');
$data=$this->M_selltransaction->getdtHeaderid($header_id);
echo json_encode($data);
}
View:
<div class="col-md-6">
<label for="header_id" class="col-md-4 control-label" style="text-align:left">Transaction No</label>
<label class="col-md-1 control-label">:</label>
<div class="col-md-6">
<div class="input-group input-group-unstyled">
<input type="text" class="header_id form-control" placeholder="Search" id="header_id" name="header_id"/>
<span class="input-group-addon"><i class="fa fa-search "></i></span>
</div>
</div>
</div>
<table>
<td><input type="text" width="10" class="detail_id form-control"
id="detail_id" name="detail_id[]" value="<?php $a =
set_value('detail_id[0]'); echo $a;?>" required ></td>
<td><input
type="text" width="10" class="item_code form-control" id="item_code"
name="item_code[]" value="<?php $a = set_value('item_code[0]'); echo
$a;?>" required ></td>
<td><input type="text" class="item_name
form-control" id="item_name" name="item_name[]" value=""
readonly></td>
</table>
<script type="text/javascript">
function getdHeaderid(header_id){
var header_id = header_id.val();
$.ajax({
type : "post",
data : {header_id:header_id},
url : "<?php echo base_url();?>index.php/transaction/selltransaction/getdtHeaderid",
dataType:"json",
cache :false,
success: function(data){
console.log(data);
$(".detail_id").val(data.detail_id);
$(".item_code").val(data.item_code);
$(".item_name").val(data.item_name);
}
});
}
$(document).ready(function() {
$('.header_id').on('keyup change', function() {
getdHeaderid($(this));
});
});
function getdtHeaderid($header_id = FALSE) {
if ($header_id === FALSE)
{
$query = $this->db1->get('tbltransactiondtl');
return $query->result_array();
}
$query = $this->db1->get_where('tbltransactiondtl', array('header_id' => $header_id));
return $query->result_array();
}
Here is Your Correct model function you were using row_array() instead of result_array() thats why getting only one result
update
$(".detail_id").val(data.detail_id);
$(".item_code").val(data.item_code);
$(".item_name").val(data.item_name);
to
$(".detail_id").val(data[0].detail_id);
$(".item_code").val(data[0].item_code);
$(".item_name").val(data[0].item_name);

ajax can not send request and return values on dynamic input field except 1 row in codeigniter

Below is my HTML code. I can only get value returned by ajax request in that id="sss" field.
My Problems are listed below with images:-
<form id="dynamic2" action="<?= site_url('product/save') ?>" method="post">
<table class="table">
<tbody id="itemlist2" class="detailss">
<tr>
<td>
<select id="select-product" class="form-control" data-cell="B1" name="product_name[]">
<option value="">
</option>
<?php
foreach ($product as $key ):
?>
<option value="<?php echo $key['id'] ?>">
<?php echo $key['product_name'] ?>
</option>
<?php endforeach; ?>
</select>
</td>
<td>
<input type="text" id="sss" data-cell="C1" name="price[]" class="form-control" value="">
</td>
<td>
<input type="text" data-cell="D1" name="quantity[]" class="form-control">
</td>
<td>
<input type="text" data-cell="E1" name="discount[]" class="form-control">
</td>
<td>
<input type="text" data-cell="F1" name="total[]"
disabled="true" data-formula="(D1*C1)-(D1*C1*E1/100)"
class="form-control">
</td>
</tr>
</tbody>
<input type="submit" value="Submit" class="btn btn-primary">
</table>
</form>
I am not getting value returned by ajax request in dynamically created input fields.
Here is my dynamically created input field jS code.
<script type="text/javascript">
$(function() {
$form = $('#dynamic2').calx();
$('.addrowss').click(function() {
$itemlist = $('#itemlist2');
$counter = 5;
var i = ++$counter;
var tr = '<tr>' +
'<td><select id="select-product" class="form-control" data-cell="B' + i + '" name="product_name[]"><option value=""></option><?php
foreach ($product as $key ):
?><option value="<?php echo $key['product_name'] ?>"><?php echo $key['product_name'] ?></option><?php endforeach; ?></select></td>'+
'<td><input id="sss" type="text" data-cell="C' + i + '" name="price[]" class="form-control" value=""></td>' +
'<td><input type="text" data-cell="D' + i + '" name="quantity[]" class="form-control"></td>' +
'<td><input type="text" data-cell="E' + i + '" name="discount[]" class="form-control"></td>' +
'<td><input type="text" class="form-control" data-cell="F' + i + '" name="total[]" data-formula="(D' + i + '*C' + i + ')-(D' + i + '*C' + i + '*E' + i + '/100)"></td>' +
'<td>Remove</td>' +
'</tr>';
$('.detailss').append(tr);
$form.calx('update');
$form.calx('getCell', 'G1').setFormula('SUM(F1:F' + i + ')');
});
$('body').delegate('.remove', 'click', function() {
var tr = $(this).parent().parent();
var c = confirm("Do you want to remove this ?");
if (c) {
tr.remove();
}
});
});
</script>
Ajax Code
<script type="text/javascript">
$(document).ready(function() {
$("#select-product").change(function() {
var id = $(this).val();
// alert(id);
$.ajax({
type: "GET",
url: "<?php echo site_url('/product/view_data'); ?>",
data: {
"id": id
},
cache: false,
success: function(data) {
var tmp = data.split(",");
$('#sss').val(tmp[6]);
}
});
});
});
</script>
Product.php Controller
public function view_data()
{
if(isset($_GET['id'])){
$this->load->model('Product_model');
$id = $_GET['id'];
$param = $this->Product_model->get_ajax_value($id);
foreach($param as $a)
echo $a.",";
exit;
}
}
I am not exactly sure why it isn't returning all the correct data. But here might be a step to help you debug you problem.
Add a console.log(data); To see what is being returned from the ajax call. Use the console of your browser to see this.
Change your code to:
<script type="text/javascript">
$(document).ready(function () {
$("#select-product").change(function () {
var id = $(this).val();
// alert(id);
$.ajax({
type: "GET",
url: "<?php echo site_url('/product/view_data'); ?>",
data: {"id":id},
cache: false,
success: function(data){
console.log(data); //this will show what is returned.
var tmp = data.split(",");
$('#sss').val(tmp[6]);
}
});
});
});
I understand this isn't the complete answer to your code. But it might put you on the right track to seeing what the server is returning to your client side code.

How to do autocomplete when a value from dropdown is selected?

Hi I am using codeigniter framework. I have a auto fill code like when I enter a id in a text box it retrieves a value from database and fills the remaining text box automatically.
When I type the full id and click somewhere I made to auto-fill with the help of ajax. Now when I select some data from the related data drop down I need to auto fill them. How to do this?
Can someone help me code?
Here is my code where I am got struck.
My controller function
<?php
class Admin_billing extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('billing_model');
$this->load->model('client_model');
$this->load->model('employee_model');
$this->load->model('products_model');
$this->load->model('package_model');
if(!$this->session->userdata('is_logged_in')){
redirect('admin/login');
}
}
public function ticket($id)
{
$id=$this->uri->segment(4);
$data['id']=$this->uri->segment(4);
$data['main_content'] = 'admin/billing/ticket_page';
$this->load->view('includes/template', $data);
}
public function getdetails()
{
$data_to_search=$_POST['val'];
$details=array();
$details['description']=$this->billing_model->get_service_name($data_to_search);
$details['type']=$this->billing_model->get_service_name($data_to_search);
$details['cost']=$this->billing_model->get_service_name($data_to_search);
$details['qty_prch'] = 1;
$details['qty_used'] = 1;
$details['price']=$this->billing_model->get_service_pricevalue($data_to_search);
echo json_encode($details);
}
}?>
This is my controller page admin_billing.php. Here I have a getdetails() that is called when I enter some value in the text box and click somewhere. When I click somewhere or press tab the value is posted from view to this function with help of ajax.
This is my model page.
<?php
class billing_model extends CI_Model {
public function __construct()
{
$this->load->database();
}
public function get_service_name($id)
{
$this->db->select('*');
$this->db->from('service');
$this->db->where('id', $id);
$query = $this->db->get();
$result = $query->result_array();
return $result[0]['name'];
}
public function get_service_pricevalue($id)
{
$this->db->select('*');
$this->db->from('service');
$this->db->where('id', $id);
$query = $this->db->get();
$result = $query->result_array();
return $result[0]['price'];
}
public function get_service_mins($id)
{
$this->db->select('*');
$this->db->from('service');
$this->db->where('id', $id);
$query = $this->db->get();
$result = $query->result_array();
return $result[0]['mins'];
}
public function get_service_price($id)
{
$this->db->select('*');
$this->db->from('service');
$this->db->where('id', $id);
$query = $this->db->get();
$result = $query->result_array();
return $result[0]['price'];
}
public function get_service_id($id)
{
$this->db->select('*');
$this->db->from('service');
$this->db->where('id', $id);
$query = $this->db->get();
$result = $query->result_array();
return $result[0]['id'];
}
}
?>
Here in this model page, billing_model.php I have few function which retrieves the value from database. Here I get the id from the controller search for it and get the related content with the help of id.
Here is my view page.
I have a function that when onchange action happens get the value from my textbox with name pid[] and calls a ajax function getvalues()
I have another function BindControls() for auto-complete action. When I select some value again I need to pass that value to the ajax function getvalues()
<html>
<head>
<link href="<?php echo base_url(); ?>assets/css/demo.css" rel="stylesheet">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script type='text/javascript' src='//code.jquery.com/jquery-compat-git.js'></script>
<link href="http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css" rel="Stylesheet"></link>
<script src="http://code.jquery.com/ui/1.10.2/jquery-ui.js" ></script>
<script type='text/javascript'>
var baseurl='<?php echo base_url(); ?>';
$(function() {
$('#test').on('change', 'input[name="pid[]"]', function() {
var indexOfTheChangedRow = $(this).closest("tr").index();
get_values(this.value, indexOfTheChangedRow);
});
});
function get_values(val,rowIndex)
{
$.ajax({
url: baseurl + 'admin/billing/getdetails',
type: 'post',
data: {
val: val
},
success: function (indexOfTheChangedRow, response) {
if (response != "") {
var json = jQuery.parseJSON(response),
rowToUpdate = $("#test tr:nth-child(" + (indexOfTheChangedRow + 1) + ")");
// add the changed row as the context to restrict the search for the classes to this one row only
$('.description', rowToUpdate).val(json.description);
$('.type', rowToUpdate).val(json.type);
$('.qty_used', rowToUpdate).val(json.qty_used);
$('.qty_prch', rowToUpdate).val(json.qty_prch);
$('.price', rowToUpdate).val(json.price);
}
}.bind(window, rowIndex),
error: function (response) {
alert("error");
}
});
}
function displayResult() {
<?php
$attributes = array('class' => 'form-horizontal', 'id' => '');
$options_employee = array('' => "Select");
foreach ($employee as $row)
{
$options_employee[$row['first_name']] = $row['first_name'];
}
$dropdown = form_dropdown('employee', $options_employee, set_value('employee[]'), 'class="span2"');
?>
var complex = <?php echo json_encode($dropdown); ?>;
var row = document.getElementById("test").insertRow(-1);
row.innerHTML = '<td><div>'+complex+'</div></td><td><input type="text" name="start_time[]" value="" style="width:35px;"/></td><td><input type="text" name="pid[]" style="width:35px;"/></td><td><input type="text" name="description[]" class="description" value="" style="width:145px;"/></td><td><input type="text" class="type" value="" style="width:45px;"/></td><td class="qty_prch"><input type="text" class="qty_prch" value="" style="width:45px;"/></td><td><input type="text" class="qty_used" value="" style="width:45px;"/></td><td class="price"><input type="text" class="price" value="" style="width:70px;"/></td><td><input type="text" value="" class="discount" style="width:70px;"/></td><td><input type="text" value="" class="tax" style="width:70px;"/></td><td class="total"><input type="text" value="" class="total" style="width:70px;"/></td>';
}
</script>
<script>
$(document).ready(function () {
$('#test').on('mousemove', 'input', sumtotal);
function sumtotal() {
var hour = 0;
var rate = 0;
var total = 0;
var subtotal = 0;
$('#test tbody tr').each(function () {
hour = parseNumber($(this).find('.price input').val());
rate = parseNumber($(this).find('.qty_prch input').val());
subtotal = (hour * rate);
$(this).find('.total input').val(subtotal);
total += subtotal;
});
$('.Grandtotal input').val(total);
}
function parseNumber(n) {
var f = parseFloat(n); //Convert to float number.
return isNaN(f) ? 0 : f; //treat invalid input as 0;
}
});
$(document).ready(function() {
BindControls();
});
function BindControls() {
var Countries = ['ARGENTINA',
'AUSTRALIA',
'BRAZIL',
'BELARUS',
'BHUTAN',
'CHILE',
'CAMBODIA',
'CANADA',
'CHILE',
'DENMARK',
'DOMINICA'];
$('#pid').autocomplete({
source: Countries,
autoFocus: true,
minLength: 0,
scroll: true
}).focus(function() {
$(this).autocomplete("search", "");
});
}
</script>
</head>
<?php
$attributes = array('class' => 'form-horizontal', 'id' => '');
$options_employee = array('' => "Select");
foreach ($employee as $row)
{
$options_employee[$row['first_name']] = $row['first_name'];
}
echo form_open('admin/billing/ticket_page');
?>
<table id="test">
<thead>
<tr>
<td style="width:80px;">employee</td>
<td style="width:35px;">start time</td>
<td style="width:35px;">id</td>
<td style="width:145px;">Description</td>
<td style="width:45px;">Type</td>
<td style="width:45px;">Qty prch</td>
<td style="width:45px;">Qty used</td>
<td style="width:70px;">Price</td>
<td style="width:70px;">discount</td>
<td style="width:70px;">Tax</td>
<td style="width:70px;">Total</td>
</tr>
</thead>
<tbody>
<tr>
<td><?php echo form_dropdown('employee', $options_employee, set_value('employee[]'), 'class="span2"');?></td>
<td><input type="text" name="start_time[]" value="" style="width:35px;"/></td>
<td><input type="text" name="pid[]" id="pid" value="" style="width:35px;"/></td>
<td><input type="text" name="description[]" class="description" value="" style="width:145px;"/></td>
<td><input type="text" name="type[]" class="type" style="width:45px;"/></td>
<td class="qty_prch"><input type="text" name="qty_prch[]" class="qty_prch" style="width:45px;"/></td>
<td><input type="text" name="qty_used[]" class="qty_used" style="width:45px;"/></td>
<td class="price"><input type="text" name="price[]" class="price" style="width:70px;"/></td>
<td><input type="text" name="discount[]" class="discount" style="width:70px;"/></td>
<td><input type="text" name="tax[]" class="tax" style="width:70px;"/></td>
<td class="total"><input type="text" name="total[]" class="total" style="width:70px;"/></td>
</tr>
</tbody>
</table>
<div id="add_row">
<button type="button" onClick="displayResult()" class="add_r"></button>
</div>
<?php echo form_close(); ?>
<div id="last_button">
<input type="button" class="Delete"/>
<input type="button" class="Edit"/>
<script src="<?php echo base_url(); ?>assets/js/function.js"></script>
</body>
</html>
Can someone help me code? Please give me some solutions.
When you add a row, the .on('autocompleteselection'... only works on existing html and not anything generated. You need to add delegation, so go from:
$(document).ready(function () {
$('#pid').on('autocompleteselect', function (e, ui) {
var indexOfTheChangedRow = $(this).closest("tr").index();
get_values(ui.item.value, indexOfTheChangedRow);
});
});
to
$(document).ready(function () {
$('#pid').on('autocompleteselect', 'tr',function (e, ui) {
var indexOfTheChangedRow = $(this).closest("tr").index();
get_values(ui.item.value, indexOfTheChangedRow);
});
});
That way you are delegating the .on to also include table rows added later

Represent json from jquery ajax response into a html's table

I create a search form that using ajax as the action. In success ajax, how can I just load some specific div without load all refresh page.
This is my form
<?php
$properties = array('id' => 'form1');
echo form_open("", $properties);
?>
<fieldset>
<div class="controls" id="chekboxes">
<label class="checkbox "><input type="checkbox" name="criteria[]" id="nomorcb"/> Nomor Request </label>
<input type="text" class="input-xlarge focused" id="no" name="no" placeholder="Masukkan No Request..."/>
<label class="checkbox "><input type="checkbox" name="criteria[]" id="namacb"/> Nama User </label>
<input type="text" class="input-xlarge focused" id="nama" name="nama" placeholder="Masukkan Nama User..."/>
<label class="checkbox "><input type="checkbox" name="criteria[]" id="departementcb" /> Departement</label>
<div class="control-group">
<div class="controls">
<select class="input-xlarge" id="selectError" name="dep">
<option value="">-- Pilih departement --</option>
<?php
foreach ($dep as $data) {
echo "<option value='" . $data['nama_departement'] . "'>" . $data['nama_departement'] . "</option>";
}
?>
</select>
</div>
</div>
<label class="checkbox "><input type="checkbox" name="criteria[]" id="rentangcb"/> Rentang waktu</label>
<div class="controls" id="tanggal-rentang">
<input type="text" class="input-small datepicker" id="tanggal" value="" name="tgl_awal"><span> s/d </span>
<input type="text" class="input-small datepicker" id="tanggal2" value="" name="tgl_akhir">
</div>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-primary" id="submit">Cari</button>
<button type="reset" class="btn" id="cancel">Cancel</button>
</div>
</fieldset>
<?php echo form_close(); ?>
this is the action's code for execute the form.
public function search() {
$id_request = $this->input->post('nomor');
$nama_user = $this->input->post('nama');
$departement = $this->input->post('departement');
$awal = $this->input->post('tgl_awal');
if ($awal != "") {
$awal = $this->input->post('tgl_awal');
} else {
$awal = "2014-01-01";
}
$timestamp_awal = strtotime($awal);
$tgl_awal = date("Y-m-d H:i:s", $timestamp_awal);
$akhir = $this->input->post('tgl_akhir');
if ($akhir != "") {
$akhir = $this->input->post('tgl_akhir');
} else {
$akhir = "2020-01-01";
}
$timestamp_akhir = strtotime($akhir);
$tgl_akhir = date("Y-m-d H:i:s", $timestamp_akhir);
$data = $this->model_request->search($id_request, $nama_user, $departement, $tgl_awal, $tgl_akhir);
echo json_encode($data);
}
and this is the Ajax jquery for form above :
$('form').on('submit', function() {
var nomor = $('#no').val();
var nama = $('#nama').val();
var departement = $('#selectError').val();
var tgl_awal = $('#tanggal').val();
var tgl_akhir = $('#tanggal2').val();
$.ajax({
url: '<?php echo base_url() . 'it_team/control_it/search' ?>',
type: 'POST',
data: {nomor: nomor,
nama: nama,
departement: departement,
tgl_awal: tgl_awal,
tgl_akhir: tgl_akhir},
dataType: 'json',
success: function(obj) {
//Please give me an idea
}
});
return false;
For testing, I try seearch and thank God, it gives me a success on json like this:
[{"id_request":"015","nama_user":"Dzil","departement":"IT","waktu_it_terima":"2015-06-19 02:51:05"},
{"id_request":"017","nama_user":"Dzil","departement":"IT","waktu_it_terima":"2015-06-19 13:32:46"}]
My problem is, the result of search form above will be displaying into a table in same page with the form above. You know, in tbody's table will be generate the object on based the return of json. I am newbie using json. The table looked like this
<div class="box-content" id="things_table2">
<table class="table table-bordered table-striped table-condensed" id="table1">
<thead>
<tr>
<th>No. </th>
<th>No Request</th>
<th>Nama user</th>
<th>Departement</th>
<th>Tanggal Request</th>
<th>Action</th>
</tr>
</thead>
<tbody id="hasil-pencarian">
// Result will be showing here
</tbody>
</table>
</div>
Any help it so appriciated.
Try like this (beware there are less fields in your json than in your table):
var data = [
{
'id_request': '015',
'nama_user': 'Dzil',
'departement': 'IT',
'waktu_it_terima': '2015-06-19 02:51:05'
},
{
'id_request': '017',
'nama_user': 'Dzil',
'departement': 'IT',
'waktu_it_terima': '2015-06-19 13:32:46'
}
];
var html = '';
for (var i = 0; i < data.length; i++) {
var td="";
for(var key in data[i]){
td+='<td>'+data[i][key]+'</td>';
}
html+="<tr>"+td+"</tr>";
}
$('#hasil-pencarian').html(html);
There is nothing special about json. Treat it like any js object, ie after parsing it.
Since its just an array of objects, you can iterate over it and do whatever.
var html = '';
$.each(data, function (index, element) {
// build your html
html += '<tr>;'
html += '<td>'+ index + 1 + '</td>';
html += '<td>'+ element.id_request + '</td>';
// same for other elements use `element.<key-name>`
// end tr after all the td's are done
html += '</tr>;'
});
Once you have iterated over all the elements, inject it in the dom.
$('.DOM-ELEMENT').html(html);

Categories