I have a company_model and a controller. I also have 3 corresponding tables in a database for where the data is saved and read from. The goal of this is to manage companies linked to sub holdings and the corresponding directors of the sub holdings.
When I add a new company, the Sub holding and Director fields work perfectly. My issue is when editing an already saved company, the corresponding Director field is not populated or populating. I have been trying to find the issue for sometime now, I am not receiving any console errors or Network XHR when checking with Chrome. I know this is going to be a simple fix, I can not see it or find the issue. Any advice or pointers would be greatly appreciated
The Database structure is as follows:
Table 1 is for the director information (director_id, director_name, director_subholding_id)
Table 2 is for subholding information (subholding_id, subholding_name)
Table 3 is for company information (company_id, company_name, ceo_name, company_subholding_id,
company_director_id)
Company_Model
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Company_model extends CI_Model{
function get_subholding(){
$query = $this->db->get('subholding');
return $query;
}
function get_director($subholding_id){
$query = $this->db->get_where('director', array('director_subholding_id' => $subholding_id));
return $query;
}
function save_company($company_name,$subholding_id,$director_id,$ceo_name){
$data = array(
'company_name' => $company_name,
'ceo_name' => $ceo_name,
'company_subholding_id' => $subholding_id,
'company_director_id' => $director_id
);
$this->db->insert('company',$data);
}
function get_company(){
$this->db->select('company_id,company_name,ceo_name,subholding_name,director_name');
$this->db->from('company');
$this->db->join('subholding','company_subholding_id = subholding_id','left');
$this->db->join('director','company_director_id = director_id','left');
$query = $this->db->get();
return $query;
}
function get_company_by_id($company_id){
$query = $this->db->get_where('company', array('company_id' => $company_id));
return $query;
}
function update_company($company_id,$company_name,$subholding_id,$director_id,$ceo_name){
$this->db->set('company_name', $company_name);
$this->db->set('ceo_name', $ceo_name);
$this->db->set('company_subholding_id', $subholding_id);
$this->db->set('company_director_id', $director_id);
$this->db->where('company_id', $company_id);
$this->db->update('company');
}
//Delete Product
function delete_company($company_id){
$this->db->delete('company', array('company_id' => $company_id));
}
Company Controller
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Company extends CI_Controller {
function __construct(){
parent::__construct();
$this->load->model('Company_model','company_model');
$this->load->library('session');
}
function index(){
$data['companies'] = $this->company_model->get_company();
$this->load->view('company_list_view',$data);
}
// add new company
function add_new(){
$data['subholding'] = $this->company_model->get_subholding()->result();
$this->load->view('add_company_view', $data);
}
// get sub category by category_id
function get_director(){
$subholding_id = $this->input->post('id',TRUE);
$data = $this->company_model->get_director($subholding_id)->result();
echo json_encode($data);
}
//save company to database
function save_company(){
$company_name = $this->input->post('company_name',TRUE);
$subholding_id = $this->input->post('subholding',TRUE);
$director_id = $this->input->post('director',TRUE);
$ceo_name = $this->input->post('ceo_name',TRUE);
$this->company_model->save_company($company_name,$subholding_id,$director_id,$ceo_name);
$this->session->set_flashdata('msg','<div class="alert alert-success">Company Saved</div>');
redirect('company');
}
function get_edit(){
$company_id = $this->uri->segment(3);
$data['company_id'] = $company_id;
$data['subholding'] = $this->company_model->get_subholding()->result();
$get_data = $this->company_model->get_company_by_id($company_id);
if($get_data->num_rows() > 0){
$row = $get_data->row_array();
$data['director_id'] = $row['company_director_id'];
}
$this->load->view('edit_company_view',$data);
}
function get_data_edit(){
$company_id = $this->input->post('company_id',TRUE);
$data = $this->company_model->get_company_by_id($company_id)->result();
echo json_encode($data);
}
//update company to database
function update_company(){
$company_id = $this->input->post('company_id',TRUE);
$company_name = $this->input->post('company_name',TRUE);
$subholding_id = $this->input->post('subholding',TRUE);
$director_id = $this->input->post('director',TRUE);
$ceo_name = $this->input->post('ceo_name',TRUE);
$this->company_model-
>update_company($company_id,$company_name,$subholding_id,$director_id,$ceo_name);
$this->session->set_flashdata('msg','<div class="alert alert-success">Company Updated</div>');
redirect('company');
}
//Delete Company from Database
function delete(){
$company_id = $this->uri->segment(3);
$this->company_model->delete_company($company_id);
$this->session->set_flashdata('msg','<div class="alert alert-success">Company Deleted</div>');
redirect('company');
}
Edit Company View
<!DOCTYPE html>
<html>
<head>
<title>Edit Company</title>
<link href="<?php echo base_url().'assets/css/bootstrap.css'?>" rel="stylesheet" type="text/css">
</head>
<body>
<div class="container">
<div class="row justify-content-md-center">
<div class="col col-lg-6">
<h3>Edit Company:</h3>
<form action="<?php echo site_url('company/update_company');?>" method="post">
<div class="form-group">
<label>Company</label>
<input type="text" class="form-control" name="company_name" placeholder="Company
Name" required>
</div>
<div class="form-group">
<label>Subholding</label>
<select class="form-control subholding" name="subholding" required>
<option value="">No Selected</option>
<?php foreach($subholding as $row):?>
<option value="<?php echo $row->subholding_id;?>"><?php echo $row->subholding_name;?></option>
<?php endforeach;?>
</select>
</div>
<div class="form-group">
<label>Director</label>
<select class="form-control director" name="director" required>
<option value="">No Selected</option>
</select>
</div>
<div class="form-group">
<label>CEO</label>
<input type="text" class="form-control" name="ceo_name" placeholder="CEO Name"
required>
</div>
<input type="hidden" name="company_id" value="<?php echo $company_id?>" required>
<button class="btn btn-success" type="submit">Update Company</button>
</form>
</div>
</div>
</div>
<script type="text/javascript" src="<?php echo base_url().'assets/js/jquery-3.3.1.js'?>"></script>
<script type="text/javascript" src="<?php echo base_url().'assets/js/bootstrap.js'?>"></script>
<script type="text/javascript">
$(document).ready(function(){
//call function get data edit
get_data_edit();
$('.subhodling').change(function(){
var id=$(this).val();
var director_id = "<?php echo $director_id;?>";
$.ajax({
url : "<?php echo site_url('company/get_director_id');?>",
method : "POST",
data : {id: id},
async : true,
dataType : 'json',
success: function(data){
$('select[name="director"]').empty();
$.each(data, function(key, value) {
if(director_id==value.director_id){
$('select[name="director"]').append('<option value="'+ value.director_id
+'" selected>'+ value.director_name +'</option>').trigger('change');
}else{
$('select[name="director"]').append('<option value="'+ value.director_id
+'">'+ value.director_name +'</option>');
}
});
}
});
return false;
});
//load data for edit
function get_data_edit(){
var company_id = $('[name="company_id"]').val();
$.ajax({
url : "<?php echo site_url('company/get_data_edit');?>",
method : "POST",
data :{company_id :company_id},
async : true,
dataType : 'json',
success : function(data){
$.each(data, function(i, item){
$('[name="company_name"]').val(data[i].company_name);
$('[name="subholding"]').val(data[i].company_subholding_id).trigger('change');
$('[name="director"]').val(data[i].company_director_id).trigger('change');
$('[name="ceo_name"]').val(data[i].ceo_name);
});
}
});
}
});
</script>
</body>
</html>
In your view, the select field for the Director is:
<select class="form-control director" name="directore" required>
Everywhere else in your view, controller and model, you're expecting a variable named director which is not really there, so when you use $this->input->post('director') you're actually getting a NULL value which explains why your updates are not working.
A simple fix would be to change your select to
<select class="form-control director" name="director" required>
and you should be ok
Related
I want to update multiple or single row in database in one query where multiple ids or single id post from the form. I couldn't find it works in update batch. I don't know how to do it. I have already searched on google on how to make it but I have no luck. Your answer is very much appreciated.
Html and AJAX
<form class="form-horizontal" enctype="multipart/form-data" method="POST">
<div class="form-group">
<label class="col-sm-3 control-label" for="name"><?php echo $this->lang->line('Select Lead Contacts'); ?>
</label>
<div class="col-sm-9 col-md-6 col-lg-6">
<select id="chkveg" name="mySelect[]" class="form-control" multiple="multiple">
<?php foreach($list_of_leads_contact as $lc) {
?>
<option value="<?php echo $lc->id ?>"><?php echo $lc->first_name ?> <?php echo $lc->last_name ?></option>
<?php } ?>
</select>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label" ><?php echo $this->lang->line('Contact Group'); ?> *
</label>
<div class="col-sm-9 col-md-6 col-lg-6">
<?php if(isset($group_checkbox)) echo $group_checkbox; ?>
<span class="red">
<?php
if($this->session->userdata('group_type_error')==1){
echo '<b>'.$this->lang->line('Contact Group').'</b>'.str_replace("%s","", $this->lang->line("required"));
$this->session->unset_userdata('group_type_error');
}
?>
</span>
</div>
</div>
</div>
<button name="submit" id="submitButton" type="button" class="btn btn-primary btn-lg"><i class="fa fa-save"></i> <?php echo $this->lang->line('Save');?></button>
</form>
<script type="text/javascript">
$j(function() {
$( ".datepicker" ).datepicker();
});
$(function() {
$('#submitButton').click(function() {
var dataString = $('.form-horizontal').serialize();
$.ajax({
type: 'POST',
url: base_url +'lead/insert_leads_in_groups', // your php url would go here
data: dataString,
}).done(function(msg) {
});
});
});
</script>
Controller Code
public function insert_leads_in_groups()
{
$user_id = $this->input->post('mySelect');
$contact_group_id = $this->input->post('contact_type_id');
foreach($user_id as $row ) {
$data = array(
array(
'contact_group_id' => $contact_group_id,
),
);
$this->db->update_batch('leads', $data, 'id');
}
}
Error
A Database Error Occurred
One or more rows submitted for batch updating is missing the
specified index.
In CI docs you can read
the third parameter is the where key.
and below see the resulting query example. From that its't obviouse that each sub-array should contain a corresponding value for that key.
So, in your case, you need to put the id value to each sub-array.
public function insert_leads_in_groups()
{
$user_id = $this->input->post('mySelect');
$contact_group_id = $this->input->post('contact_type_id');
$data = [];
foreach($user_id as $id ) {
$data[] = [
'id' = > $id,
'contact_group_id' => $contact_group_id,
];
}
$this->db->update_batch('leads', $data, 'id');
}
Here I have Two independent dropdowns : "Sub company " and " Role" and there is a third dropdown which depends on these two dropdowns. basically what I want to implement is if the chosen "Role" is NOT 'manager' and 'admin', then displays third dropdown "manager", which its options depends on sub company .
Right now I am able to get all the managers depends on sub company , what I need to do is to make a condition to only show managers list when role !== 'manager' && role !== 'admin'.
Here is the view.php
<div class="form-group col-md-4">
<label for="pwd">Sub Company Name</label>
<div class="alert-danger"><?php echo form_error('Subcom'); ?></div>
<select class="form-control" id="Subcom" name="Subcom" >
<option value="">Select Sub Company</option>
<?php
foreach($company_name as $row )
{
echo '<option value="'.$row->company_name.'" '.set_select('Subcom', $row->company_name).'>'.$row->company_name.'</option>';
}
?>
</select>
</div>
<div class="form-group col-md-4">
<label for="pwd">Role</label>
<div class="alert-danger"> <?php echo form_error('role'); ?></div>
<select class="form-control" id="role" name="role" placeholder="Select Role">
<option value="">Select Role</option></div>
<?php
foreach($role_name as $row )
{
echo '<option value="'.$row->id.'" '.set_select('role', $row->role_name).'>'.$row->role_name.'</option>';
}
?>
</select>
</div>
<div class="form-group col-md-4" >
<label for="pwd">Manager</label>
<div class="alert-danger"> <?php echo form_error('manager'); ?></div>
<select class="form-control" id="manager" name="manager" placeholder="Select Manager" style="display:none" disabled>
<option value="">Select Manager</option>
</select>
</div>
And here is the script
<script type="text/javascript">
$(document).ready(function(){
$(' #Subcom, #role').on('change' , function() {
var company_name = $('#Subcom').val();
var role = $('#role').val();
if( company_name!==''&& role !== '' && role !=='manager' && role !==
'admin')
{
//alert('ok');
$('#manager').prop('disabled', false);
$.ajax({
url:"<?php echo base_url()?>getManager",
type: "POST",
data: { 'company_name' : company_name},
dataType:'json',
success: function(data){
console.log(data);
false;
$('#manager').html(data.manager);
$('#manager').show();
},
error: function(event){
console.log(event);
alert('Error occur...');
}
});
}else {
//alert('sgsg');
$('#manager').prop('disabled', true);
$('#manager').hide();
}
});
});
</script>
Here is the controller
public function getManager()
{
//echo json_encode ($_REQUEST); die;
//print_r($_REQUEST);
//die;
$company_name = $this->input->post('company_name');
$getallmanager = $this->project_model->get_manager_query($company_name);
$getallstaff = $this->project_model->get_all_staff($company_name);
$all_the_mangers = '';
$all_the_staffs = '';
if(count($getallmanager)>0)
{
foreach ($getallmanager as $manager){
//if(role!=='manager')
$all_the_mangers .='<option value="' .$manager->first_name.'">'.$manager->first_name.'</option>';
}
}
if(count($getallstaff)>0)
{
foreach ($getallstaff as $staff){
$all_the_staffs .='<option value="' .$staff->first_name.'">'.$staff->first_name.'</option>';
}
}
$result = array('manager'=>$all_the_mangers,'staffs'=>$all_the_staffs);
echo json_encode($result);die;
}
}
And here is the Model:
public function get_manager_query($company_name)
{
$query = $this->db->get_where('user_login', array('company_name' => $company_name,'role'=>'manager'));
return $query->result();
}
public function get_all_staff($company_name)
{
$query = $this->db->get_where('user_login', array('company_name' => $company_name,'role !='=>'manager'));
return $query->result();
}
it is simply pass a var to show or hide.
in your controller file pass data['role_admin'] = 1;
in your view file
if($role_admin==1){
// show your Manager code
}
Add style="display:none" and disabled to manager select so it won't show up at load. Also selects don't need a value, if you want to set a specific option than you need to do it in the loops like this:
foreach($company_name as $row )
{
echo '<option value="'.$row->company_name.'" '.set_select('Subcom', $row->company_name).'>'.$row->company_name.'</option>';
}
Also it would be a good idea to move the form errors before the select and not wrap the options with it.
<script type="text/javascript">
$(document).ready(function(){
$('#Subcom,#role').on('change' , function() {
var company_name = $('#Subcom').val();
var role_name = $('#role').val();
if(company_name !== '' && role_name !== 'manager' && role_name !== 'admin')
{
$('#manager' ).prop('disabled', false);
$.ajax({
url:"<?php echo base_url()?>getManager",
type: "POST",
data: { 'company_name' : company_name},
dataType:'json',
success: function(data){
//alert('ok');
console.log(data);
$('#manager').html(data.manager);
$('#manager').show();
},
error: function(event){
console.log(event);
alert('Error occur...');
}
});
}
else
{
$('#manager').prop('disabled', true);
$('#manager').hide();
}
});
});
</script>
EDIT: for future reference here's the final code
https://jsfiddle.net/Lo50z6q8/
hello i want to display data of business2's data according to business1's dropdown list but on change() of business1 i got data in response but how to print it in second dropdown list using id. i didn't get response in success function. How to print options of dropdown list using Id.
I got response in mozila's firefox's console but i don't know how to return it in success and then how to print in second dropdown list.
<!-- ajax code starts here -->
<script>
$(document).on('change', 'select.Business1', function(){
var business1 = $('select.Business1 option:selected').val();
alert(business1);
var value = $(this).val();
$.ajax({
type:"POST",
data: { business1:business1 },
url: '<?php echo site_url('client_area/select_business_sub_cat'); ?>',
sucess : function (data){
alert(1);
var abc = $('#business2').html(data);
}
});
});
</script>
<!-- ajax code ends here -->
Model function
public function select_business_sub_cat()
{
$business1 = $this->input->post('business1');
$result_sub_cat1 = $this->db->query("select category.id,subcategory.* From category LEFT JOIN subcategory ON category.id = subcategory.category_id where category.id = '$business1'");
$row_cat1 = $result_sub_cat1->result();
$data = array(
'id' => $row_cat1['0']->id,
'name' => $row_cat1['0']->name
);
echo "<option value='" . $row_cat1['0']->id . "'>" . $row_cat1['0']->name . "</option>";
// return $this->output->set_output($data);
}
View --
<div class="form-group">
<label>Business 1</label>
<select name="txtBusiness1" id="" style="height: 30px;width: 100%;" class="Business1">
<option value=""> Select Business </option>
<?php
$result_cat1 = $this->db->query("select * from category");
$row_cat1 = $result_cat1->result();
?>
<?php foreach($row_cat1 as $item){ ?>
<option value="<?php echo $item->id; ?>"><?php echo $item->name; ?></option>
<?php } ?>
</select>
</div>
<div class="form-group">
<label>Business 2</label>
<select name="txtBusiness2" id="business2" style="height: 30px;width: 100%;" class="Business2">
<option value=""> Select Business2 </option>
</select>
You have a type in your ajax call:
success : function (data) {
It's success not sucess
2 things may creating issue:
1) add double quotes in url
2) make it success instead of sucess
$.ajax({
type:"POST",
data: { business1:business1 },
url: '<?php echo site_url("client_area/select_business_sub_cat"); ?>', // add double quotes in url
success : function (data){ // make it success instead of sucess
alert(1);
var abc = $('#business2').html(data);
}
});
Change sucesss to success. You are using CI framework then use CI parameterized query, don't use static query it's hackable.
Give unique id to both div and select
It's better to follow MVC if you are use CI. Put your query in model with ci parameterized query.
<div class="form-group" id = 'divtxtBusiness1'>
<label>Business 1</label>
<select name="txtBusiness1" id="txtBusiness1" style="height: 30px;width: 100%;" class="Business1">
........
</select>
</div>
<div class="form-group" id = "div_Business_2">
<label>Business 2</label>
<select name="txtBusiness2" id="business2" style="height: 30px;width: 100%;" class="Business2">
<option value=""> Select Business2 </option>
</select>
</div>
<script>
//$(document).on('change', 'select.Business1', function(){
// var business1 = $('select.Business1 option:selected').val();
$(document).on('change', '#txtBusiness1', function(){
var business1 = $('#txtBusiness1').val();
//alert(business1);
//var value = $(this).val();
$.ajax({
type:"POST",
data: { business1:business1 },
url: '<?php echo site_url("client_area/select_business_sub_cat"); ?>',
success : function (data){
//alert(1);
$('#div_Business_2 #business2').remove();
$('#div_Business_2').append(data);
}
});
});
</script>
Controller :
public function select_business_sub_cat()
{
$business1 = $this->input->post('business1');
$result_sub_cat1 = $this->xyzmodel->xyzmodelfunction($business1)
$str = '<select name="txtBusiness2" id="business2" style="height: 30px;width: 100%;" class="Business2">';
for($i = 0 ; $i< count($result_sub_cat1) ; $i++)
{
$str .= '<option value="'.$result_sub_cat1['id'].'"> '.$result_sub_cat1['name'].' </option>';
}
$str .= '</select>';
echo $str;
// return $this->output->set_output($data);
}
Model :
don't use static query it's hackable.
class Xyzmodel extends CI_Model
{
......
public function xyzmodelfunction($business1)
{
$this->db->select(category.id,subcategory.*);
$this->db->from('category');
$this->db->join("subcategory", "category.id = subcategory.category_id", 'LEFT');
$this->db->where('category.id', $business1);
$result = $this->db->get();
return $result->result_array();
}
........
}
I have tried a lot to find the solution of how to populate the city dropdown by selecting the country in the first dropdown but i didn't understand the available solutions.I have populated the first dropdown from the database but i cant populate the second one due to the no knowledge of Ajax. Please provide the full code of ajax or jquery how to populate the second one by selecting the first Thanks.
View
<div class="form-group">
<label for="" class="col-md-4 control-label">City</label>
<div class="col-md-8 text center">
<select class="form-control" name="city" id="city">
<?php foreach($cityData as $data){
$id = $data->city_id;
$country_name =$data->city_name;
?>
<option value="<?php echo $id; ?>"><?php echo $city_name; ?></option>
<?php } ?>
</select>
</div>
</div>
<div class="form-group">
<label for="" class="col-md-4 control-label">Country</label>
<div class="col-md-8 text center">
<select class="form-control" class="country" name="country">
<option value="">Select Country</option>
<?php foreach($countryData as $data){
$id = $data->country_id;
$country_name =$data->country_name;
?>
<option value="<?php echo $id; ?>"><?php echo $country_name; ?></option>
<?php } ?>
</select>
</div>
</div>
Ajax Code
<script>
$(document).ready(function(){
$("select.country").change(function(){
var selectedCountry = $(".country option:selected").val();
$.ajax({
type: "POST",
url: "../form_controller/populate_cities",
data: { country : selectedCountry }
});.done(function(data){
$("#city").html(data);
});
});
});
</script>
Controller to Populate Cities
public function populate_cities(){
$this->load->model('cities');
$country_id = $this->input->post('country');
$data['cityData'] = $this->cities->getData($country_id);
$this->load->view('reservation_detail');
}
NOTE:I Assume you have country and city and state table
How this code working:- When page load, at that time controller index function is called and trigger a model function getCountry() and this function retrieve all the available country name and pass this to view. When country drop down value change it called a ajax function selectState(current country id) and this ajax function called a controller loadData() and this function called a model function loadData(filter type like state or city) and on that basic this model function return data. The same procedure follow for state drown change but with different java script function selectCity(state id) function and follow previous flow. Both the java script function call loadData js function for loading the data.
Java Script Code:-
function selectState(country_id){
if(country_id!="-1"){
loadData('state',country_id);
$("#city_dropdown").html("<option value='-1'>Select city</option>");
}else{
$("#state_dropdown").html("<option value='-1'>Select state</option>");
$("#city_dropdown").html("<option value='-1'>Select city</option>");
}
}
function selectCity(state_id){
if(state_id!="-1"){
loadData('city',state_id);
}else{
$("#city_dropdown").html("<option value='-1'>Select city</option>");
}
}
function loadData(loadType,loadId){
var dataString = 'loadType='+ loadType +'&loadId='+ loadId;
$("#"+loadType+"_loader").show();
$("#"+loadType+"_loader").fadeIn(400).html('Please wait... <img src="image/loading.gif" />');
$.ajax({
type: "POST",
url: "loadData",
data: dataString,
cache: false,
success: function(result){
$("#"+loadType+"_loader").hide();
$("#"+loadType+"_dropdown").html("<option value='-1'>Select "+loadType+"</option>");
$("#"+loadType+"_dropdown").append(result);
}
});
}
Controller Functions:-
public function index()
{
$this->load->model('model');
$result['list']=$this->model->getCountry();
$this->load->view('top');
$this->load->view('index',$result);
$this->load->view('footer');
}
public function loadData()
{
$loadType=$_POST['loadType'];
$loadId=$_POST['loadId'];
$this->load->model('model');
$result=$this->model->getData($loadType,$loadId);
$HTML="";
if($result->num_rows() > 0){
foreach($result->result() as $list){
$HTML.="<option value='".$list->id."'>".$list->name."</option>";
}
}
echo $HTML;
}
Model Functions:-
function getCountry()
{
$this->db->select('id,country_name');
$this->db->from('country');
$this->db->order_by('country_name', 'asc');
$query=$this->db->get();
return $query;
}
function getData($loadType,$loadId)
{
if($loadType=="state"){
$fieldList='id,state_name as name';
$table='state';
$fieldName='country_id';
$orderByField='state_name';
}else{
$fieldList='id,city_name as name';
$table='city';
$fieldName='state_id';
$orderByField='city_name';
}
$this->db->select($fieldList);
$this->db->from($table);
$this->db->where($fieldName, $loadId);
$this->db->order_by($orderByField, 'asc');
$query=$this->db->get();
return $query;
}
I have asked this question twice, with no satisfactory answer, that is, the problem I faced two questions ago still remains and none the wiser as how I am going to proceed with this.
This time I will provide all the code and what I receive, plus where the problem is occurring, I know what the issue is but since I'm relatively new to using AJAX it has me puzzled.
I have a form, which when you click the second to last field, duplicates itself, with the help of another user all the id's get changed to be unique.
<form role="form" class="batchinvoice form-horizontal" id="batchinvoice">
<div class="row">
<div class="form-group col-md-2">
<select class="form-control" name="sl_propid" >
<?php foreach($property as $row) :?>
<option value="<?php echo $row['id']; ?>">
<?php echo $row[ 'property_name'] . " " . $row[ 'property_address1']; ?>
</option>
<?php endforeach; ?>
</select>
</div>
<div class="form-group col-md-1">
<input type="text" name="sl_date" placeholder="Date" class="sl_date form-control" id="datepicker">
</div>
<div class="form-group col-md-2">
<input type="text" name="sl_ref" placeholder="Invoice Reference" class="form-control" id="sl_ref">
</div>
<div class="form-group col-md-2">
<select class="form-control" name="sl_nom_id" id="sl_nom_id">
<?php foreach($subitem_nominals as $row) :?>
<option value="<?php echo $row['subnom_id']; ?>">
<?php echo $row[ 'nom_subitem_name']; ?>
</option>
<?php endforeach; ?>
</select>
</div>
<div class="form-group col-md-2">
<input type="text" name="sl_desc" id="sl_desc" placeholder="Invoice Description" class="form-control">
</div>
<div class="form-group col-md-2">
<input type="text" name="sl_vat" placeholder="VAT Amount" class="vat form-control" id="vat">
</div>
<div class="form-group col-md-1">
<input type="text" name="sl_net" placeholder="Net" class="form-control" id="sl_net">
</div>
</form>
The JS for the form clone
<script>
var clone_iterator = 0;
$(function () {
var i = 0;
$.datepicker.setDefaults($.datepicker.regional['']);
$.datepicker.formatDate("yy-mm-dd");
$('#datepicker').datepicker();
$('#batchinvoice .vat').click(function () {
// alert("ok");
var id = "batchinvoice" + clone_iterator;
$('#batchinvoice').clone(true).attr("name", id).attr('id', id).appendTo(".panel-body"); // here I added this .attr('id',id)
// here we'll change the id's of all the elements who actualy have an attribute
$('#' + id + ' *[id]').each(function () {
$(this).attr('id', $(this).attr('id') + clone_iterator); //we set the attribute id
});
clone_iterator++;
});
$('#submit').click(function () {
var res = {};
console.log(res);
$('.batchinvoice').each(function (i) { //the class is a good use to do things like that you can repeat it more than once !
res[i] = new Array();
console.log(res);
res[i].propid = $(this).find('*[name=sl_propid]').val();
res[i].date = $(this).find('.sl_date formcontrol').val();
res[i].ref = $(this).find('*[name=sl_ref]').val();
res[i].id = $(this).find('*[name=sl_nom_id]').val();
res[i].desc = $(this).find('*[name=sl_desc]').val();
res[i].vat = $(this).find('*[name=sl_vat]').val();
res[i].net = $(this).find('*[name=sl_net]').val();
console.log(res);
alert(res[i].propid);
// i++;
//$.each('',function( index, value ){}
//(int)i is already incremented if you use class and not IDS
});
console.log(res);
$.ajax({
type: 'POST',
url: '<?php echo base_url(); ?>FinancialInput/addInvoiceToLedger',
data: res,
sucess: function (e) {
alert(e);
},
error: function (e) {
alert(e.toString());
}
});
});
});
</script>
This is the particular controller function in CodeIgniter, Note I have tried multiple things.
function addInvoiceToLedger(){
// $this->load->model('SalesLedgerModel');
// $propid = $this->input->post('propid');
// print_r($this->input->post());
// $date = $this->input->post('date');
// $ref = $this->input->post('ref');
// $nomid = $this->input->post('id');
// $desc = $this->input->post('desc');
// $vat = $this->input->post('vat');
// $net = $this->input->post('net');
$res = $this->input->post(NULL, TRUE);
//problem is probably here, it's
//for($x = 0; $x < count($res); $x++){
foreach($res as $row){
$this->SalesLedgerModel->addInvoiceToLedger($row.propid, $row.date, $row.ref, $row.nomid, $row.desc, $row.vat, $row.net);
}
//}
//redirect('home/financial_input/');
}
the Model Function
function addInvoiceToLedger($propid, $date, $ref, $nomid, $desc, $vat, $net){
$data = array('sl_prop_id' => $propid, 'sl_date' => $date,
'sl_ref' => $ref, 'sl_nominal_sub' => $nomid, 'sl_invoice_desc' => $desc, 'sl_vat' => $vat, 'sl_amount' => $net);
$this->db->insert_batch('salesledger', $data);
}
Which all have the relevant field data for each form inside them.
My question is how do I receive and handle the array? Every loop I've tried doesn't work, I've tried getting variables singularly(as you can see above commented out) but that doesn't make sense (or work) because in the $.ajax data it is set to res, but $this->input->post('res') doesn't return anything nor does $this->input->post(NULL, TRUE)
Majorly stuck, I feel this should be a simple thing, but I clearly don't understand it.
Edit, still same problem can't find an answer anywhere D:, tried many things.
Still the same problem "res" is sent as post, but I can't retrieve it in the controller with $this->input->post()...anyone?
I only wanted to submit a comment but apparently I need 50 rep for that so I'll take my chances with an answer.
In your $.ajax block what if you change the data section to this:
$.ajax({
type: 'POST',
url: '<?php echo base_url(); ?>FinancialInput/addInvoiceToLedger',
data: { res : res },
sucess: function (e) {
alert(e);
},
error: function (e) {
alert(e.toString());
}
});