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());
}
});
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');
}
I am trying to populate my form fields with AJAX when a request is being made. I was able to successfully made the request and fetched data, but the issue I am facing is that the input fields are not being populated.
If I populate the return data into a div it will display but not displaying in a form fields.
My HTML code
<form id="fm" method="post" novalidate>
<div style="margin-bottom:10px">
<input class="easyui-textbox" name="descr" id="descr" multiline="true" data-options="label:'Description:'" style="width:100%;">
</div>
<div style="margin-bottom:10px">
<input class="easyui-textbox" name="unit" id="unti" style="width:100%" data-options="label:'Unit:'">
</div>
<div style="margin-bottom:10px">
<input class="easyui-numberbox" name="rate" id="rate" style="width:100%" data-options="label:'Rate:'">
</div>
<div style="margin-bottom:10px">
<input class="easyui-numberbox" name="fixing" id="fixing" style="width:100%" data-options="label:'Fixing:'">
</div>
<div style="margin-bottom:10px">
<input class="easyui-numberbox" name="quantity" id="quantity" style="width:100%" data-options="label:'Quantity:'">
</div>
</form>
jQuery Code
function load_click(param)
{
var resp = $("#loadstatus");
$.ajax({
type: "POST",
url: "boqs/load.php",
data: {},
dataType: 'json',
beforeSend: function(){
resp.html(' <img src="../assets/img/rot_small.gif" />');
},
success: function (data) {
if (Array.isArray(data) && data.length) {
for (var i = 0; i < data.length; i++) {
//for each value in the json response
$(".descr").val(data[i].descr);
$(".unit").val(data[i].unit);
$(".rate").val(data[i].rate);
$(".fixing").val(data[i].fixing);
$(".quantity").val(data[i].quantity);
//alert(data[i].descr);
} // for
resp.html('');
}
});
}
PHP source code
$sql = "SELECT * FROM bill_preparation ORDER BY id DESC LIMIT 1";
$ret2 = $db->query($sql);
$json_resp = array();
while($row = $ret2->fetchArray(SQLITE3_ASSOC)){
$json_array['descr'] = $row['descr'];
$json_array['unit'] = $row['unit'];
$json_array['rate'] = $row['rate'];
$json_array['fixing'] = $row['fixing'];
$json_array['quantity'] = $row['quantity'];
//$json_array['amount'] = $row['amount'];
array_push($json_resp, $json_array);
}
//$result["rows"] = $items;
echo json_encode($json_resp, true);
Thanks to very one for your support. #Patrick suggestion pointed me to the right direction.
I discovered using $(".descr").val(data[i].descr); doesn't work in easyui form so I used $(".descr").textbox('setValue',data[i].descr); which worked.
I hope this help someone working with easyui.
This is my php CodeIgniter Code which is generating 30 Dropdowns which is also populated from database and that is workig absolutly fine.
here is the preview of my dropdown list. every list will be populated with the related paraller field.
<?php for($i=1; $i<=30; $i++){ ?>
<div class="form-group c">
<div class="col-sm-12">
<div class="input-group">
<div class="col-xs-12 col-sm-12 <?php if (form_error('iat_code_'.$i)) { echo "has-error";} ?>">
<?php
$itm_iat_codes = $itm_iat_code_1.$i;
if(isset($itm_iat_codes)){$itm_iat_codes;}else{$itm_iat_codes = "";}
echo form_dropdown(
'iat_code_'.$i,
$ProductAttributeTitle,'',
'class="col-xs-12 col-sm-6 required-field form-control"
id="iat_code_'.$i.'" placeholder="IAT Code" tabindex="1" data-style="form-control" required');
?>
</div>
<?php echo form_error('iat_code_'.$i, '<div for="iat_code_'.$i.'" class="alert-danger">', '</div>'); ?>
</div>
</div>
</div>
<?php }?>
Here is another Code which is also generating 30 emppty dropdowns and these will be filled up by using ajax.
PHP Code
`<?php for($i=1; $i<=30; $i++){ ?>
<div class="form-group c">
<div class="col-xs-12 col-sm-12">
<div class="input-group">
<select name="istbs_code_<?php echo $i; ?>" class="col-xs-12 col-sm-6 required-field form-control" id="istbs_code_<?php echo $i; ?>" placeholder="ISTBS Code" tabindex="1" data-style="form-control">
<option value="">Select Option</option>
</select>
</div>
</div>
</div>
<?php } ?>`
Here is my ajax code that populates other dropdown from database.
$("#iat_code_1").change(function(){
var json = {};
var abc = json['iat_code_1'] = $(this).val();
var request = $.ajax({
url: "<?php echo base_url($controller.'/get_product_attributes'); ?>",
type: "POST",
data: json,
dataType: "html",
success : function(response){
$("#istbs_code_1").html(response);
}
});
});
Now problem is that which i'm facing is in ajax, if i'm populating all 30 dropdown with each related for that purpose i've to make 30 ajax functions but i want to make it with only one ajax function, is it posible to do it? if any one know please help.
Here you can fetch all the dropdown data by using single ajax call but after that you need to do client side validation as per requirnment.
You don't have to write ajax call 30 times . Just create one function which calls ajax and on change event call that function as shown below. and even you don't have to write change event 30 time just add one common class (here eg.dropchange ) to all dropdown as shown below and change dropdown change event accordingly
`<?php for($i=1; $i<=30; $i++){ ?>
<div class="form-group c">
<div class="col-xs-12 col-sm-12">
<div class="input-group">
<select name="istbs_code_<?php echo $i; ?>" class="dropchange col-xs-12 col-sm-6 required-field form-control" id="istbs_code_<?php echo $i; ?>" placeholder="ISTBS Code" tabindex="1" data-style="form-control">
<option value="">Select Option</option>
</select>
</div>
</div>
</div>
<?php } ?>`
$(document).on("change",".dropchange ",function(){
var thisid=this.id;
var json = {};
var abc = json['iat_code_1'] = $(this).val();
var request = callajax(thisid);
});
function callajax(thisid){
$.ajax({
url: "<?php echo base_url($controller.'/get_product_attributes'); ?>",
type: "POST",
data: json,
dataType: "html",
success : function(response){
$("#"+thisid).html(response);
}
});
}
Here is a sample code which fetching data by single Ajax call & repopulate those data in the dynamically created dropdown list.
client Side file(index.php)
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
<script type="text/javascript">
$( document ).ready(function() {
console.log( "ready!" );
$.ajax({
method: "GET",
url: "dropDownList.php",
}).done(function( response ) {
console.log('Response Data', response);
$.each( response, function( key, value ) {
$.each( value, function( key1, value1 ) {
console.log( "KEY1 : "+key1+", VALUE1 : " + value1['value'] );
var option_value = value1['value'];
var option_text = value1['text'];
var dd_option_list = "<option value='"+option_value+"'>"+option_text+"</option>";
$('#dropdown_'+key).append(dd_option_list);
});
});
});
});
</script>
</head>
<body>
<?php
$noOfDropDownList = 3;
for ($i=1; $i <= 3 ; $i++) {
echo "<select id='dropdown_$i' name=''>";
echo "</select><br>";
}
?>
</body>
</html>
Server Side FIle (dropDownList.php)
<?php
$dropdownList[1][] = array('value' => 'apple','text' => 'apple');
$dropdownList[1][] = array('value' => 'mango','text' => 'mango');
$dropdownList[1][] = array('value' => 'bananan','text' => 'bananan');
$dropdownList[2][] = array('value' => 'cat','text' => 'cat');
$dropdownList[2][] = array('value' => 'dog','text' => 'dog');
$dropdownList[2][] = array('value' => 'rat','text' => 'rat');
$dropdownList[3][] = array('value' => 'google','text' => 'google');
$dropdownList[3][] = array('value' => 'apple','text' => 'apple');
$dropdownList[3][] = array('value' => 'microsoft','text' => 'microsoft');
header('Content-Type: application/json');
echo json_encode($dropdownList);
Hope, it'll help you fig. out how to impliment such functionality in your context.
Please help me on how to get the last inserted id from database using codeigniter and jquery. What I want is to get the the last inserted id after inserting. I am using jquery to insert the data. I don't have any idea on how to it. Thanks a lot in advance.
SCRIPT
$('#add-tag').click(function () {
var lang = $('#lang').val();
var tag = $('#tag').val();
var data = {
tag: tag,
lang: lang
}
if (tag === '') {
$('.error').html('<h4><i class="glyphicon glyphicon-info-sign">' +
'</i> Field cannot be empty!</h4>').addClass('bounceIn').show();
$('.error').delay(3000).fadeOut();
} else {
$.ajax({
url: "<?= site_url('blog/add_tag'); ?>",
type: 'POST',
data: data,
success: function (result) {
//display message if successful
$('.message').html('<h4><i class="glyphicon glyphicon-ok">' +
'</i> Tag has been added</h4>').addClass('bounceIn').show();
$('.message').delay(3000).fadeOut();
$('#tag').val('');
$('#tags').append('<a class="tags animated fadeInDown">' +
'<span class="remove-tag" id="remove-tag' + lid + '">' +
'</span></span> ' + tag + '</a>');
window.setTimeout(function () {
location.reload();
}, 2000);
}
});
}
});
VIEW
<div class="row">
<div class="col-md-12 col-sm-12 col-xs-12">
<div id="add-tag-form" class="display-none relative">
<div class="well well-sm">
<div class="row">
<div class="col-md-12 col-sm-12 col-xs-12">
<h5>Add Tag</h5>
<input type="text" id="tagLastID" class="form-control" placeholder="Tag Last ID" readonly>
<input type="hidden" id="lang" class="form-control" placeholder="Lang" required value="<?= $lang; ?>">
<input type="text" id="tag" class="form-control" placeholder="Tag" required>
<br />
<button id="add-tag" class="btn col-md-12 col-sm-12 col-xs-12">Add Tag</button>
<div class="text-center"><a id="close-tag">cancel</a></div>
</div>
</div>
</div>
</div>
<button id="add-tag-btn" class="btn col-md-12 col-sm-12 col-xs-12">Add Tag</button>
</div>
</div>
CONTROLLER
public function add_tag() {
$this->Mblog->addTag();
}
MODEL
public function addTag() {
$lang = $this->input->post('lang');
$tag = $this->input->post('tag');
$data = array(
'tags' => $tag,
'lang' => $lang
);
$this->blog->insert('tags', $data);
return $this->blog->insert_id();
}
Add return to your controller function or echo the result like as follows:
public function add_tag() {
return $this->Mblog->addTag();
}
OR
public function add_tag() {
echo json_encode(['data' => $this->Mblog->addTag()]);
exit;
}
And then try to modify dump and see the ajax success response:
$.ajax({
url: "<?= site_url('blog/add_tag'); ?>",
type: 'POST',
data: data,
dataType: 'json', // this will convert your results to json by default
success: function (result) {
// You should get the json result
console.log(result.data);
// Your regular logic to handle result
},
fail: function(res) {
console.log(res); // will log fail results
}
});
Try these and let us know if this works for you or not.
If you are asking that how to return data from controller to jQuery then yes, this is the answer.
Replace your controller code with this
public function add_tag() {
$insert_id = $this->Mblog->addTag();
echo(json_encode(array("insert_id"=>$insert_id)));
}
The echo'ed result will be appear in your success of jQuery.ajax.
You're already returning the id from the Model, so in your controller the only thing you have to do is echo-ing the result.
public function add_tag() {
echo $this->Mblog->addTag();
}
Then in you jquery the result will be what you have echoed from the controller.
I will try the cascading dependent select box and input in Codeigniter with Ajax. The first step works quite well. The Securities can be easily loaded, when selecting an Account. The problem starts with the second step. So, when I try after the Security-selection to set the appropriate changeable Inputs, the Security-select will getting blocked and then nothing works. Don't understand what the problem is.
Please help me, the nasty blockage to dissolve. Thanks.
Ajax:
$(document).ready(function(){
var _form = $("#trans_form").serializeArray();
$('#amount_section').hide();
$('#quantity_section').hide();
$('#accountDrop').on('change',function(){
$("#securityDrop > option").remove();
var accountID = $(this).val();
if(accountID == '#') {return false;}
$.ajax({
data: _form,
type: "POST",
url: global_base_url + "custody/get_securities_dropdown/" + accountID,
success: function(securities) {
$.each(securities,function(id,value) {
var opt = $('<option />');
opt.val(id);
opt.text(value);
$('#securityDrop').append(opt);
});
}
});
});
$('#securityDrop').on('change',function(){
$('#amount_section').hide();
$('#quantity_section').hide();
var securityID = $(this).val();
if(securityID == '#') {return false;}
$.ajax({
data: _form,
type: "POST",
url: global_base_url + "custody/get_security_unit_ajax/" + securityID,
success: function(securUnit) {
if (securUnit == "UNIT") {
$('#quantity_section').show(300);
};
else if (securUnit == "FAMT") {
$('#amount_section').show(300);
};
}
});
});
});
Controller:
public function get_securities_dropdown($account_id){
$securities = $this->custody_model->get_security_by_account($account_id);
header('Content-Type: application/x-json; charset=utf-8');
echo json_encode($securities);
}
public function get_security_unit_ajax($security_id){
$securUnit = $this->custody_model->get_security_unit($security_id);
header('Content-Type: application/x-json; charset=utf-8');
echo json_encode($securUnit);
}
Model:
public function get_accounts_dropdown(){
$accounts = $this->db->select("ID as id, Account_Desc as descr")
->order_by("descr", "ASC")
->get($this->table2)->result();
$accounts_arr;
$accounts_arr['#'] = '-- Please select Account --';
foreach ($accounts as $account) {
$accounts_arr[$account->id] = $account->descr;
}
return $accounts_arr;
}
public function get_security_by_account($account_id){
if(!is_null($account_id)){
$securities = $this->db->where("a.ID_Account", $account_id)
->select("b.ID as id, b.Security_Desc as descr")
->join($this->table5 . " as b", "b.ID = a.ID_Security")
->order_by("descr", "ASC")
->get($this->table6 . " as a");
if($securities->num_rows() > 0){
$securities_arr;
foreach ($securities->result() as $security) {
$securities_arr[$security->id] = $security->descr;
}
return $securities_arr;
}
}
return;
}
View:
<?php echo form_open_multipart(site_url("custody/add_transaction_pro"), array("id" => "trans_form")) ?>
<div>
<label for="accountDrop">Account</label>
<div>
<?php echo form_dropdown('accountDrop', $account_arr, '#', 'id="accountDrop"'); ?>
</div>
</div>
<div id="security_section">
<label for="security_select">Security</label>
<div>
<select name="securityDrop" class="required" id="securityDrop">
<option value="#">-- Please select Security --</option>
</select>
</div>
</div>
<div id="quantity_section">
<label for="quantity">Quantity</label>
<div id="quantityInput">
<input type="text" id="quantity" name="quantity">
</div>
</div>
<div id="amount_section">
<label for="settl_amount">Amount</label>
<div id="amountInput">
<input type="text" id="settl_amount" name="settl_amount">
</div>
</div>
I have solved it. The error was quite simple, the unnecessary semicolons in the ajax part. The syntax is if() { } else if{ }