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

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

Related

ajax is not working inside for loop

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?

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.

Multiple checkbox delete javascript

I have this code which delete from database rows.But it removes one by one when pressing delete, checkbox not working.I want to multiple delete by checking checkbox.
function confirmDelete(delUrl) {
if (confirm("Are you sure you want to delete")) {
document.location = delUrl;
}
}
function check() {
document.getElementById("myCheck").checked = true;
}
function uncheck() {
document.getElementById("myCheck").checked = false;
}
HTML
<a href="javascript:confirmDelete('?action=deleteurl&id=<?php echo $row[0]; ?>')">
<input type="checkbox" id="myCheck[]">delete</td>
PHP
<?php
if($_GET['action'] == "deletelink" && !empty($_GET['id']) && is_numeric($_GET['id'])) {
$result = mysql_query("SELECT * FROM books WHERE id='".intval($_GET['id']);
while ($row = mysql_fetch_array ($result) )
unlink("/home/me/public_html/upload/image/{$row['image']}");
}
Your logic is not for multiple delete
this should be html
<input type="checkbox" id="myCheck[]" class="multicheck" name="<?php echo $row[0]; ?>" value="<?php echo $row[0]; ?>">delete</td>
Multiple Delete</td>
and this should be javascript
function confirmMultiDelete() {
if (confirm("Are you sure you want to delete")) {
var str = [];
$.each(".multicheck:checked",function(){
str.push($(this).val());
});
ids = str.join(",");
document.location = '?action=deleteurl&id='+ids;
}
}
here is my approach.
You need some modification to do multiple delete as my approach.
First you have to put value in checkbox so you can get its value to
delete.
Second you have to add another button or action to delete multiple
record.
Your Code ( with Modification ):
HTML + PHP CODE
<a href="javascript:confirmDelete('?action=deleteurl&id=value="<?php echo $row[0]; ?>"')">delete
</a>
<input type="checkbox" class="delCheck" id="myCheck[]" value="<?php echo $row[0]; ?>">
</td>
<!-- This will generate html code like below -->
<!--
<td>
delete
<input type="checkbox" class="delCheck" value="1" id="myCheck[]" class="delCheck">
</td>
<td>delete
<input type="checkbox" class="delCheck" value="2" id="myCheck[]" class="delCheck">
</td>
<td>delete
<input type="checkbox" class="delCheck" value="3" id="myCheck[]" class="delCheck">
</td>
<td>delete
<input type="checkbox" class="delCheck" value="4" id="myCheck[]" class="delCheck">
</td>
<td>
<input type="button" value="Delete" name="delete_value" id="delete_value" class="delCheck">
</td>
-->
<!-- Multiple Delete Button -->
<input type="button" id="delete_value" name="delete_value" value="Delete" />
Javascript + Jquery
function confirmDelete(delUrl) {
if (confirm("Are you sure you want to delete")) {
document.location = delUrl;
}
}
$( document ).ready(function() {
$("#delete_value").on("click", function (e){
var ids = '';
$('.delCheck:checked').each(function(i){
ids += $(this).val() + ',';
});
// go to delete url with action delete_all_ur
confirmDelete('?action=delete_all_url&id='+ids)
});
});
PHP Delete Code:
if( #$_GET['action'] == "delete_all_url" )
{
$all_ids = $_GET['id'];
// Remove trailing ',' from IDs
$all_ids = trim($all_ids, ",");
// Temporary variable to check only integer value passes
$tempId = str_replace(",", "", $all_ids);
// Check id numeric or not
if ( is_numeric($tempId) ) {
$sql_query = "SELECT * FROM books WHERE id in (".intval($_GET['id'].")";
$result = mysql_query($sql_query);
while ($row = mysql_fetch_array ($result) )
unlink("/home/me/public_html/upload/image/{$row['image']}");
} else {
//echo 'errors';
}
}

how to make my page auto submit?

I have one payment page where payment values will fill automatically . so i don't want allow that page to user to submit . how can i do auto submit of my page ?
my code is
include "configaration/config.php";
// Merchant key here as provided by Payu
$MERCHANT_KEY = "4LbrUG";
// Merchant Salt as provided by Payu
$SALT = "EhDp06FA";
// End point - change to https://secure.payu.in for LIVE mode
$PAYU_BASE_URL = "https://test.payu.in";
$sucess_url = 'http://localhost/georamble/success.php';
$failur_url = 'http://localhost/georamble/failure.php';
$action = '';
$posted = array();
if(!empty($_POST)) {
foreach($_POST as $key => $value) {
$posted[$key] = $value;
}
}
$formError = 0;
if(empty($posted['txnid'])) {
// Generate random transaction id
$txnid = substr(hash('sha256', mt_rand() . microtime()), 0, 20);
} else {
$txnid = $posted['txnid'];
}
$hash = '';
// Hash Sequence
$hashSequence = "key|txnid|amount|productinfo|firstname|email|udf1|udf2|udf3|udf4|udf5|udf6|udf7|udf8|udf9|udf10";
if(empty($posted['hash']) && sizeof($posted) > 0) {
if(
empty($posted['key'])
|| empty($posted['txnid'])
|| empty($posted['amount'])
|| empty($posted['firstname'])
|| empty($posted['email'])
|| empty($posted['phone'])
|| empty($posted['productinfo'])
|| empty($posted['surl'])
|| empty($posted['furl'])
|| empty($posted['service_provider'])
) {
$formError = 1;
} else {
//$posted['productinfo'] = json_encode(json_decode('[{"name":"tutionfee","description":"","value":"500","isRequired":"false"},{"name":"developmentfee","description":"monthly tution fee","value":"1500","isRequired":"false"}]'));
$hashVarsSeq = explode('|', $hashSequence);
$hash_string = '';
foreach($hashVarsSeq as $hash_var) {
$hash_string .= isset($posted[$hash_var]) ? $posted[$hash_var] : '';
$hash_string .= '|';
}
$hash_string .= $SALT;
$hash = strtolower(hash('sha512', $hash_string));
$action = $PAYU_BASE_URL . '/_payment';
}
} elseif(!empty($posted['hash'])) {
$hash = $posted['hash'];
$action = $PAYU_BASE_URL . '/_payment';
}
//data from previous page
if(isset($_POST['submit1']))
{
$packname = $_POST['pname'];
$package_price = $_POST['advn_pay'];
$person = $_POST['person'];
$date = $_POST['date'];
$date = date('Y-m-d', strtotime($date));
$package_id = $_POST['pkid'];
$wallet_amount = $_POST['wallet_amount'];
$wallet_amount_use = 0;
if(isset($_POST['wuamount']))
{
$wallet_amount_use = $_POST['wuamount'];
}
$ref_no =rand(20,10000000);
$pay_status = "unpaid";
$req_status = "requested";
$wallet_update_money= $wallet_amount - $wallet_amount_use;
$update= mysql_query("UPDATE wallet SET amount='$wallet_update_money' WHERE user_id='$login_session'");
//fetch a user name
$query = mysql_query("select * from user where user_id= '$login_session'");
if(!$query)
{
echo "error";
}
while($row=mysql_fetch_array($query))
{
$name = $row['first_name'];
$email = $row['email'];
$contact_number = $row['contact_number'];
}
$p_name=$_POST['name'];
$age=$_POST['age'];
for($i=0;$i<count($p_name);$i++)
{
$qry_add="INSERT INTO trvel_person_details (ref_user_id,ref_cus_name,cus_name,cus_age,travel_date)
VALUES ('$login_session', '$name','$p_name[$i] ','$age[$i]','$date')";
if(!mysql_query($qry_add))
{
die('Error: ' . mysql_error());
}
}
$total_amount= $package_price - $wallet_amount_use ; //total amount
$qry="INSERT INTO pack_req (user_id,user_name,package_id,pacakage_name,amount,date_jrny,no_person,refrence_number,payment_status,req_status)
VALUES ('$login_session', '$name','$package_id ','$packname','$total_amount','$date ','$person','$ref_no','$pay_status ','$req_status')";
if(!mysql_query($qry))
{
die('Error: ' . mysql_error());
}
}
?>
<html>
<head>
<script>
var hash = '<?php echo $hash ?>';
function submitPayuForm() {
if(hash == '') {
return;
}
var payuForm = document.forms.payuForm;
payuForm.submit();
}
</script>
</head>
<body onload="submitPayuForm()">
<h2>PayU Form</h2>
<br/>
<?php if($formError) { ?>
<span style="color:red">Please fill all mandatory fields.</span>
<br/>
<br/>
<?php } ?>
<form action="<?php echo $action; ?>" method="post" id="payuForm" name="payuForm">
<input type="hidden" name="key" value="<?php echo $MERCHANT_KEY ?>" />
<input type="hidden" name="hash" value="<?php echo $hash ?>"/>
<input type="hidden" name="txnid" value="<?php echo $txnid ?>" />
<table>
<tr>
<td><b>Mandatory Parameters</b></td>
</tr>
<tr>
<td>Amount: </td>
<td><input name="amount" id="amount" value="<?php echo (empty($posted['amount'])) ? $total_amount : $posted['amount']; ?>" /></td>
<td>First Name: </td>
<td><input name="firstname" id="firstname" value="<?php echo (empty($posted['firstname'])) ? $name : $posted['firstname']; ?>" /></td>
</tr>
<tr>
<td>Email: </td>
<td><input name="email" id="email" value="<?php echo (empty($posted['email'])) ? $email : $posted['email']; ?>" /></td>
<td>Phone: </td>
<td><input name="phone" value="<?php echo (empty($posted['phone'])) ? $contact_number : $posted['phone']; ?>" /></td>
<td>transation Id: </td>
<td><input name="txnid" value="<?php echo (empty($posted['txnid'])) ? $ref_no : $posted['txnid']; ?>" /></td>
</tr>
<tr>
<td>Product Info: </td>
<td colspan="3"><textarea name="productinfo"><?php echo (empty($posted['productinfo'])) ? $packname : $posted['productinfo'] ?></textarea></td>
</tr>
<tr>
<td>Success URI: </td>
<td colspan="3"><input name="surl" value="<?php echo (empty($posted['surl'])) ? $sucess_url : $posted['surl'] ?>" size="64" /></td>
</tr>
<tr>
<td>Failure URI: </td>
<td colspan="3"><input name="furl" value="<?php echo (empty($posted['furl'])) ? $failur_url : $posted['furl'] ?>" size="64" /></td>
</tr>
<tr>
<td colspan="3"><input type="hidden" name="service_provider" value="payu_paisa" size="64" /></td>
</tr>
<?php if(!$hash) { ?>
<td colspan="4"><input type="submit" value="Submit" /></td>
<?php } ?>
</tr>
</table>
</form>
even i have tried with one javascript to auto submit the form
<script type="text/javascript">
$(document).ready(function(){
$("#payuForm").submit();
});
</script>
but still its not redirecting . how can do this . any hint or help . sorry for my bad english
Create a hidden submit type button(i.e. display:none;), after page load through jquery click on it automatically(i.e. $('#submit').click() ), Create a function for clicking on submit button, call it after page loads...
EDIT:
HTML:
<form ...>
...
<input type="submit" id="submit" style="display:none;" />
</form>
Javascript:
function submit_click(){
$("#submit").click();
}
Now, when your auto form populating data's function called, call this function in last line submit_click();
try this
<script>
$(document).ready(function(){
$('#payuForm').trigger('submit');
})
</script>
Remember that some browser do not let you trigger the "submit" event if you have not an ENABLED submit button (be it an input or button, with type="submit")
Thus, you need to a button in the form, and if you don't want it to be shown, you can add
#button {
display: none;
visibility: hidden;
}

Categories