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.
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 have a question: How to get value form Ajax and sent value to PHP ? Can someone help me! Value percentold ajax sent to $percent for option value.
<div class="form-group p-1 m-0">
<h6>Percent </h6>
<select class="form-control form-control-lg p-2" name="percent" id="percent" >
<?php
$percent = 'val(data.percent)'; // <<<--- HERE HOW TO GET Value FORM Ajax and sent here
echo '<option class="text-white">'.$percent.'</option>';
for ($i=100; $i>=1; $i--) {
?>
<option value="<?php echo $i;?>"><?php echo $i;?>%</option>
<?php
}
?>
</select>
</div>
//////////////////////////////AJAX///////////////////////////
$("body").on("click",".editBtn", function(e){
e.preventDefault();
edit_skill = $(this).attr('id');
//console.log(edit_skill);
$.ajax({
url: 'assets/php/process.php',
method: 'post',
data: {edit_skill: edit_skill},
success:function(response){
//console.log(response);
data = JSON.parse(response);
//console.log(data);
$("#id").val(data.id);
$("#title").val(data.skill);
$("#percentold").val(data.percent);
$("#sequenceold").val(data.sequence);
$("#percentold").val(data.percent); <------Neet post go to php
}
});
});
what is val(data.percent). As is, its just string.
if you want to add it as option from javascript to select then you need to use
<script>
$('#percent').append(new Option(data.percent, ""));
</script>
in your case :
$('#percent').append(new Option(data.percent, ""));
I am trying to implement dependent dropdown using ajax and php. But anyhow the response from second dropdown is not coming. after checking in console, I am able to see the id of first dropdown but no response from second dropdown. So, When i click on first dropdown, I just get a blank value in Second dropdown.
HTML Code
<div class="col-md-6">
<?php
require_once('db.php');
$varient_result = $conn->query('select * from tv_varient');
?>
<select name="varient" id="varient-list" class="form-control c-square c-theme" required>
<option value="">Select Varient</option>
<?php
if ($varient_result->num_rows > 0) {
// output data of each row
while($row = $varient_result->fetch_assoc()) {
?>
<option value="<?php echo $row["id"]; ?>"><?php echo $row["name"]; ?></option>
<?php
}
}
?>
</select>
</div>
</br></br>
<label for="inputPassword3" class="col-md-4 control-label" style="margin-left: 15px;">Price:</label>
<div class="col-md-6">
<select name="price" id="price-list" class="form-control c-square c-theme" required>
<option value=''>Select Price *</option>
</select>
<div>
</div>
</div>
</div>
</div>
</div>
AJAX Code
<script>
$('#varient-list').on('change', function(){
var varient_id = this.value;
$.ajax({
type: "POST",
url: "get_price.php",
data:'varient_id='+varient_id,
success: function(result){
$("#price-list").html(result);
}
});
});
</script>
get_price.php
?php
require_once('db.php');
//$country_id = mysqli_real_escape_string($_POST['country_id']);
//var_dump($country_id);
//var_dump($_POST['country_id']);
$varient_id = $_POST['veriant_id'];
echo $varient_id;
//var_dump($varient_id);
var_dump($_POST['varient_id']);
if($varient_id!='')
{
$states_result = $conn->query('select * from tv_price where veriant_id='.$varient_id.'');
$options = "<option value=''>Select Price</option>";
while($row = $states_result->fetch_assoc()) {
$options .= "<option value='".$row['price']."'>".$row['price']."</option>";
}
echo $options;
}
?>
Try below code,
$(document).on('change', '#varient-list', function(e)
{
var varient_id = this.value;
$.ajax({
type: "POST",
url: "get_price.php",
data:'varient_id='+varient_id,
success: function(result){
$("#price-list").html(result);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
varient_id & veriant_id on the POST is wrong (the e & a difference).
$varient_id = $_POST['veriant_id']; should be $varient_id = $_POST['varient_id'];
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 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());
}
});