Hi I am using codeigniter framework. I already done a autofill action with onkey change.I used ajax to post a id value to my controller function that will fetch a single data row from service table. Now I have more than 1 record ow row which is having same id. For example,
+----+-----------------+------+
+  1 +  iPhone6        +   2  +
+----+-----------------+------+
+  1 +  ipod           +   5  +
+----+-----------------+------+
Here I have 2 rows that has the same Id now when I post the id value then I need to get both the data and display in my view page. For this I need to add rows in table accordingly.
My controller function
<?php
class Admin_billing extends CI_Controller {
    public function __construct()
    {
        parent::__construct();
        $this->load->model('billing_model');
    }
 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['price']=$this->billing_model->get_service_pricevalue($data_to_search);
        echo json_encode($details);
     }
    }
Here I have a getdetails() that has a array details. In that details array I have key and value for single data such as it can hold data like
description=>phone order, type=> iphone, price => $7000. This fills the data in my view page. Now if I have more than one row how to make it work?
My model function
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']; 
}
This function is used to get the name from service table in my database.
My view file.
<html>
<head>
  <script src="<?php echo base_url(); ?>assets/js/jquery.min.js"></script>
<script type="text/javascript" src="<?php echo base_url(); ?>assets/js/jquery-2.1.1.min.js"></script>
<script type='text/javascript' src='<?php echo base_url(); ?>assets/js/jquery-compat-git.js'></script>
<link href="<?php echo base_url(); ?>assets/css/jquery-ui.css" rel="Stylesheet"></link>
<script src="<?php echo base_url(); ?>assets/js/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) + ")");
            $('.description', rowToUpdate).val(json.description);
            $('.type', rowToUpdate).val(json.type);
        }
    }.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[]" onclick="BindControls()" id="pid" 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" value="" style="width:45px;"/></td>';
}
</script>
</head>
<body>
<?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/add_tickets');
      ?>
            <div id="form"> 
             <!-- div form starts here.its for add table  -->
            <table id="test">
            <thead>
            <tr>
            <td>Employee</td>
            <td>Start Time</td>
            <td>Id</td>
            <td>Description</td>
            <td>Type</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>
            </tr>
            </tbody>
            </table>
            <div id="add_row">
        <button type="button" onClick="displayResult()" class="add_r"></button>
                </div>
  <script src="<?php echo base_url(); ?>assets/js/function.js"></script>
</body>
</html>
This my view page here I have a table with id test and this table consist of row with input elements in each cell.I have a add row button that calls a javascript function to add row dynamically.In this table I have a input element with id="pid[]" when key change action happens it calls a ajax function and get value from the database.
This works fine for single record. When I have multiple record I am struck up with no clear Idea. 
1.I need to get a array of data.
2.add rows dynamically and fill data in all rows added in one key change action.
Can someone please help me code? Thanks in advance.
EDIT: Once you have got the array, simply json_encode() and send back to the ajax. There you can decode it back. You also need to use this in your ajax : dataType : 'json'
Also note that we are setting key 'error' in the php and returnig $data array, if there was an error and checking the value in the success() of ajax to deduce if there was an error or not.
Javascript: Note this is striped down version of what you will do, but it serves the purpose of what you need to do. Hope it helps.
$.ajax ( { method : 'POST',url : scriptUrl,data : data,
    cache : false, processData: false, /** Don't process the data **/
    contentType: false, /** Set content type to false as jQuery will tell the server its a query string request **/
    dataType : 'json', /** we will return data in the key-value format from the php file **/
    success : function ( data, textStatus, jqXHR ) { /** We can treat the returned data as object. **/
        if ( typeof data.error === 'undefined' ) { /** damn error **/ }
        else { /** We got our data. **/
            for (var key in data) {
                alert(key + " -> " + data[key]);
            }
        }
    }
This should work for all your queries irrespective of number of records and number of columns.
$query = $this->db->get();
/** Check for return value
    If there is an error, set error key, we will use it in the ajax to
    check if there was an error at the bancend 
 */
if ( ! $query ) { $data['error'] = TRUE; return $data; }
/**
 * Array to hold our data.
 * For reference look at the foreach() loop.
 */
$data = array (  );
/** Get each record as $row. **/
foreach ( $query->result (  ) as $row )
{
    /**
     * Temporary array to hold the data of this record.
     */
    $temp = array (  );
    /** Get each value as $key => $value pair **/
    foreach ( $row as $key => $value)
    {
        $temp [ $key ] = $value;
    }    
    array_push ( $data, $temp );
}
return $data;
Now $data is an multidimensional associative arrays, $data[0] is equals to one record array ( 'id' =>1, 'name' => 'something'... ); 
$data = array ( array ( 'id' =>1, 'name' => 'something'... ), ( 'id' =>1, 'name' => 'something'... ),.... );
                        Say if you changed the amount in row 4 inside on change function fetch the values of all the n rows and form an object such as
var a = "[{ "key1"=>"value1", "key2"=>"value2", "key3"=>"value3", "key4"=>"value4" },{ "key1"=>"value1", "key2"=>"value2", "key3"=>"value3", "key4"=>"value4" },{ "key1"=>"value1", "key2"=>"value2", "key3"=>"value3", "key4"=>"value4" }, ]"
and post this to PHP
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With