Fetch corresponding value of a drop downlist - codeigniter

I want to fetch the corresponding value of my dropdown the image below shows the form and the database. the table was inside the javascript and Iam having a dificult time in figuring out this problem. please help me how to solve this problem... Thank you very much in advance...
Database
forms entry
My Controller
function getFeetypeEndDate() {
$feetype_id = $this->input->get('feety_id[]');
$data = $this->feegroup_model->getFeetypeByEndDate($feetype_id);
echo json_encode($data);
}
My Model
public function get($id = null) {
$this->db->select()->from('feetype');
$this->db->where('is_system', 0);
if ($id != null) {
$this->db->where('id', $id);
} else {
$this->db->order_by('id');
}
$query = $this->db->get();
if ($id != null) {
return $query->row_array();
} else {
return $query->result_array();
}
}
My Javascript in the View Section
<script>
$(document).ready(function (){
$("body").on('click', '.btn-add-more', function (e) {
e.preventDefault();
var amount = $("#amount").val();
var penalty = $("#penalty").val();
var $sr = ($(".jdr1").length + 1);
var rowid = Math.random();
var $html = '<tr class="jdr1" id="' + rowid + '">' +
'<td><span class="btn btn-sm btn-default">' + $sr + '</span><input type="hidden" name="count[]" value="'+Math.floor((Math.random() * 10000) + 1)+'"></td>' +
'<td><select id="feetype_id[]" name="feetype_id[]" class="form-control" >' +
'<?php foreach ($feetypeList as $feetype) { ?>' +
' <option value="<?php echo $feetype['id'] ?>" ' +
'<?php if (set_value('feetype_id[]') == $feetype['id']) { echo "selected =selected"; } ?>><?php echo $feetype['type'] ?></option> <?php $count++; } ?> </select></td>' +
'<td><input type="text" id="startDate" name="startDate" value="<?php echo date($this->customlib->getSchoolDateFormat($feetype->start_date), $this->customlib->dateyyyymmddTodateformat($feetype->start_date)); ?>" placeholder="Start Date" class="form-control input-sm"/></td>' +
'<td><input type="text" id="endDate" name="endDate" value="<?php echo date($this->customlib->getSchoolDateFormat($feetype->end_date), $this->customlib->dateyyyymmddTodateformat($feetype->end_date)); ?>" placeholder="End Date" class="form-control input-sm"/></td>' +
'<td><input type="text" name="amount_td[]" placeholder="Amount" class="form-control input-sm" value="'+amount+'"></td>' +
'<td><input type="text" name="penalty_td" placeholder="Penalty" class="form-control input-sm" value="'+penalty+'"></td>' +
'</tr>';
$("#table-details").append($html);
});
$("body").on('click', '.btn-remove-detail-row', function (e) {
e.preventDefault();
if($("#table-details tr:last-child").attr('id') != 'row1'){
$("#table-details tr:last-child").remove();
}
});
});

Related

Image is not uploading in CI

I am new in CI and I am trying to upload image but dont know why its not uploading,
Here is my view,
<form action="<?php echo site_url('admin/test/'.$param2.'/add'); ?>" enctype="multipart/form-data" method="post" id = 'mcq_form'>
<input type="hidden" name="question_type" value="mcq">
<div class="input-group">
<div class="custom-file">
<input type="file" class="custom-file-input" id="attachment" name="attachment" onchange="changeTitleOfImageUploader(this)">
<label class="custom-file-label" for="attachment"><?php echo get_phrase('attachment'); ?></label>
</div>
</div>
<div class="text-center">
<button class = "btn btn-success" id = "submitButton" type="button" name="button" data-dismiss="modal"><?php echo get_phrase('submit'); ?></button>
</div>
</form>
<script>
$('#submitButton').click( function(event) {
$.ajax({
url: '<?php echo site_url('admin/test/'.$param2.'/add'); ?>',
type: 'post',
data: $('form#mcq_form').serialize(),
success: function(response) {
if (response == 1) {
success_notify('<?php echo get_phrase('question_has_been_added'); ?>');
}else {
error_notify('<?php echo get_phrase('no_options_can_be_blank_and_there_has_to_be_atleast_one_answer'); ?>');
}
}
});
showLargeModal('<?php echo site_url('modal/popup/test/'.$param2); ?>', '<?php echo get_phrase('test'); ?>');
});
</script>
on Controller I am trying to get image data but dont know why its not fetching,
print_r($_FILES['attachment']['name']);
die();
I don't understand, what I am missing. Please help me out.
You can try it like this
<input type="file" name="logo" class="form-control" value="">
in your controller
$logo = '';
if (!empty($_FILES['logo']['name'])) {
/* Conf Image */
$file_name = 'profile_' . time() . rand(100, 999);
$configImg['upload_path'] = './uploads/profile/';
$configImg['file_name'] = $file_name;
$configImg['allowed_types'] = 'png|jpg|jpeg';
$configImg['max_size'] = 2000;
$configImg['max_width'] = 2000;
$configImg['max_height'] = 2000;
$configImg['file_ext_tolower'] = TRUE;
$configImg['remove_spaces'] = TRUE;
$this->load->library('upload', $configImg, 'logo');
if ($this->logo->do_upload('logo')) {
$uploadData = $this->logo->data();
$logo = 'uploads/profile/' . $uploadData['file_name'];
} else {
$this->custom_errors['logo'] = $this->logo->display_errors('', '');
}
}

How to run my function from my functions.php to a ajax request

I have a problem getting my function running through ajax.
I need it to use my function when the page has finished loading.
This is not a get function ore Post, it's pure code.
There should be a select opportunity.
I've really searched a lot on google but just can't find the solution.
I would then like to be able to use my php function and display it on the page after the page has finished loading
add_action('wp_ajax_add_woocommerce_file', 'add_woocommerce_file');
add_action('wp_ajax_nopriv_add_woocommerce_file', 'add_woocommerce_file');
function add_woocommerce_file() { ?>
<form class="cart variation" action="" method="post" enctype='multipart/form-data'>
<div class="popup">
<div class="popup-content">
<div class="close-content-container">X</div>
<?php the_content(); ?>
</div>
</div>
<?php
global $product, $post;
$output = '
<select name="variation_id" id="variation_id">
<option value="">Vælg...</option>';
foreach( $product->get_available_variations() as $variation ){
if($variation['max_qty'] > 0) {//Finder ud af om der er vare på lager det den kalde variation.
$option_value = array();
foreach( $variation['attributes'] as $attribute => $term_slug ){
$taxonomy = str_replace( 'attribute_', '', $attribute );
$attribute_name = get_taxonomy( $taxonomy )->labels->singular_name; // Attribute name
$term_name = get_term_by( 'slug', $term_slug, $taxonomy )->name; // Attribute value term name
$option_value[] = ' ' .$term_name. ' ';
}
$option_value = implode( ' :: ', $option_value );
$output .= '
<option class="option_value" value="'.$variation['variation_id'].'">'.$option_value.'</option>';
}
}
$output .= '
</select>';
?><a type="button" id="open" class="open-popup">Kort varebeskrivelse</a><?php
echo $output;
?>
<input type="hidden" name="variation_id" id="variation_id" value="" />
<input type="hidden" name="product_id" value="<?php echo esc_attr( $post->ID ); ?>" />
<input type="hidden" name="add-to-cart" value="<?php echo esc_attr( $post->ID ); ?>" />
<div class="tilfoej"><div class="cart_flex">Læg i kurv</div></div>
</form> <?php
}
add_filter('woocommerce_after_shop_loop_item', 'add_woocommerce_file', 60);
// My ajax call
jQuery(document).ready( function () {
// Ajax
jQuery.ajax({
url: the_ajax_script.ajaxurl,
type: "POST",
dataType: 'html',
data: {
action: 'add_woocommerce_file'
},
success: function( response ) {
jQuery(".variation").show();
},
error : function() {
alert("virker ikke");
}
});
});
// output on category
<div class="variation"></div>
$(window).on('load', function() {
// code here
});
Can you try this?

How to prepopulate a cascaded drop down and attachment on validation failure

I have 2 drop downs, just for simplicity let's say they are Country / States.
<select id="country_id" name = "country_id">
<option value="">Select...</option>
<?php foreach ($countries as $country): ?>
<option value="<?php echo $country->id; ?>" <?php if (null !== set_value("country_id") && set_value("country_id") == $country->id) : echo ' selected '; ?>>$country->name;
<?php endforeach?>
</select>
<select id="state_id" name = "state_id">
<option value="">Select...</option>
</select>
<input type="file" name="attachment_id" value="" />
What I do is when the country is selected I populate the states. This I do using AJAX and ".change" and this works well
The problem I'm having is when I do form_validation and
$this->form_validation->run() == FALSE
Then I reload all controls using set_value, which does work for the first drop down (the countries) just fine, however the second drop down stays empty( as there was no ".change" triggered on the "country_id" to populate "state_id".
Similarly I am asked to re-attach the file
So what I need and is not working is after form_validation fail to
Load up second drop down with data => RESOLVED see below with .trigger event
Select the previous selection int he second drop down => ALMOST RESOLVED however only if I use alert :)
The attachment should still stay attached until form is dismissed or committed successfully => NOT RESOLVED
I feel like I need to manually trigger the data change to get (1) but in my case I have a foreach (see above) where I just add lines and if the selection is the same I simply set is as "selected" but nothing happens after.
Here is the AJAX part
<script>
$(document).ready(function(){
$("#country_id").change(function(){
$.ajax({
url:"<?php echo base_url(); ?>location/getCountries",
data: {country_id: $(this).val()},
type: "POST",
success: function(data){
$("#state_id").html(data);
$("#state_id").val(null);
}
});
});
<?php if (!empty(set_value('country_id'))) : ?>
var value = "<?php echo set_value('country_id'); ?>";
$('#country_id').val(value);
$('#country_id').trigger('change');
<?php endif; ?>
<?php if (!empty(set_value('state_id'))) : ?>
var value = "<?php echo set_value('state_id'); ?>";
//without this alert the selection doesn't work
alert(value);
$('#state_id').val(value);
$('#state_id').trigger('change');
<?php endif; ?>
});
</script>
So I am getting the values saved only if I use an alert. This seems to be an asynchronous execution where the selection of second drop down is done before it gets populated, so the last thing to do is to figure out how to wait.
Still to do the attachment part
Thanks in advance!
Add this code at the end of view page
For country dropdown
<?php if (!empty(set_value('country_id'))) : ?>
<script type="text/javascript">
var value = "<?php echo set_value('country_id'); ?>";
$('select[name="country_id"]').find('option[value="'+value+'"]').attr("selected",true);
</script>
<?php endif; ?>
For state dropdown
<?php if (!empty(set_value('state_id'))) : ?>
<script type="text/javascript">
var value = "<?php echo set_value('state_id'); ?>";
$('select[name="state_id"]').find('option[value="'+value+'"]').attr("selected",true);
</script>
<?php endif; ?>
Follow the below points
1) For select tag, use set_select(), like this
<select name="myselect">
<option value="one" <?php echo set_select('myselect', 'one', TRUE); ?> >One</option>
<option value="two" <?php echo set_select('myselect', 'two'); ?> >Two</option>
<option value="three" <?php echo set_select('myselect', 'three'); ?> >Three</option>
</select>
2) If the form validation failed, call your ajax function to set second drop down.
3) For attachment, Whatever result of the form validation, first upload the image and keep the image path in session variable. After successful form validation, save the data into database and destroy the session variable.
edited >>>
**html**
<?php
if (isset($edit) && !empty($edit)) { //while editing
$StateID = $edit['StateID'];
$CountryID = $edit['CountryID'];
} else { // while adding
$StateID = set_value('StateID');
$CountryID = set_value('CountryID');
} ?>
<div class="col-3">
<div class="form-group">
<label class="mb-0">Country</label>
<select class="form-control Country" id="country" name="CountryID" data_state_value="<?php echo $StateID; ?>" >
<option value="">Select Country</option>
<?php
foreach ($country as $row) {
$selected = ($row->id == $CountryID) ? 'selected' : '';
echo '<option value="' . $row->id . '"' . $selected . '>' . $row->country_name . '</option>';
}
?>
</select>
<span class="text-danger font9"><?php echo form_error('CountryID'); ?></span>
</div>
</div>
<div class="col-3">
<div class="form-group">
<label class="mb-0">State</label>
<select class="form-control State" id="State" name="StateID">
</select>
<span class="text-danger font9"><?php echo form_error('StateID'); ?></span>
</div>
</div>
**script**
$(document).on('change', '.Country', function () {
var country_id = $(this).val();
var state_id = $(this).attr('data_state_value');
url = $("body").attr('b_url');
$.ajax({
url: url + "Education/fetch_state",
method: "POST",
data: {
country_id: country_id,
state_id: state_id
},
success: function (res) {
var response = $.parseJSON(res);
$('#State').html('<option value="">Select State</option>' + response.view);
$('.State').trigger('change');
}
});
});
$('.Country').trigger('change');
**controller**
public function fetch_state() {
$data = array();
if (isset($_POST['country_id']) && !empty($_POST['country_id'])) {
$states = $this->Location_model->fetch_state($this->input->post('country_id')); // array of states
$view = array();
if (!empty($states)) {
foreach ($states as $val) {
$selected = (isset($_POST['state_id']) && !empty($_POST['state_id']) && $_POST['state_id'] == $val['id']) ? 'selected' : '';
$view[] = "<option value='" . $val['id'] . "'" . $selected . ">" . $val['states_name'] . "</option>";
}
$data['view'] = $view;
$data['status'] = 0;
} else {
$data['status'] = 0;
$data['view'] = '<option value="">No State Found</option>';
}
} else {
$data['status'] = 0;
$data['view'] = '<option value="">Select State</option>';
}
echo json_encode($data);
}

Change input value using ajax in codeigniter

I wanted to change an input value based on the selection from a combobox in codeigniter. I tried to code it but theres nothing to be displayed.
Here is my code in my controller.....
function fill_info()
{
// retrieve the group and add to the data array
$group_id = $this->input->post('group_id');
$data = "0.00";
if($group_id)
{
$this->load-model('Base_amount_setting_model');
$baseamount = $this->Base_amount_setting_model->getbaseamount($group_id);
$data .= $baseamount;
echo $data;
}
else
{
echo $data;
}
}
And in my Base_amount_setting_model there is this method....
function getbaseamount($group_id)
{
$this->db->where('group_id',$group_id);
$baseamount = $this->db->get('base_amount_setting')->row()->amount;
if($baseamount -> num_rows() == 1)
{
return $baseamount->result();
}
}
And there in my view the ajax looks like this.....
<script>
$(document).ready(function()
{
$("#group_id").change(function()
{
var group_id = $("#group_id").val();
$.ajax({
type : "POST",
url : "<?php echo base_url('payment/fill_info'); ?>",
data : "group_id=" + group_id,
success: function(data)
{
$("#base_amount").html(data);
}
});
});
});
</script>
and finally my form is like this...
<div class="control-group">
<label class="control-label" for="select01">Group Id </label>
<div class="controls">
<select class="chzn-select" name="group_id" id="group_id" placeholder="Group Id" value="<?php echo $group_id; ?>">
<option></option>
<?php
if (count($groups)) {
foreach ($groups as $list) {
echo "<option value='". $list['group_id'] . "'>" . $list['group_name'] . "</option>";
}
}
?>
</select>
<label for="int" class="err"><?php echo form_error('group_id') ?></label>
</div>
<input class="input-xlarge disabled" id="base_amount" name="base_amount" type="text" placeholder="Base Amount" disabled="">
<input class="input-xlarge disabled" id="total_members" type="text" placeholder="Total Members" disabled="">
</div>
Thank You!
change this $("#base_amount").html(data);
to $("#base_amount").val(data);
Actually if you get your value after ajax hit in data object
then only change this :
$("#base_amount").html(data);
to
$("#base_amount").val(data);
Actually .html replce the html not change the value.
i'm really curious - but i think your model doesnt return anything
try the following
function getbaseamount($group_id)
{
$query = $this->db
->where('group_id',$group_id)
->get('base_amount_setting');
if ($query->num_rows() == 1)
{
$obj = $query->row();
return $obj->amount;
}
}
and as others suggested
change your script code to
$("#base_amount").val(data);
and your controller function should look like
function fill_info()
{
// retrieve the group and add to the data array
$group_id = $this->input->post('group_id');
$data = "0.00";
if($group_id)
{
$this->load-model('Base_amount_setting_model');
$baseamount = $this->Base_amount_setting_model->getbaseamount($group_id);
echo $baseamount;
}
else
{
echo $data;
}
}

Default value of drop-down list with JavaScript and JSON

I have a City field in my form when user select his province/state a drop-down list of cities appear according to selected state. However for the cities list there is no default value like 'Select your city'. I want to add this value.
Below is my field.js :
function getAjaxReqest(action, selectCountry, stateId, normalImput,selectedCity) {
var request = new Ajax.Request(action,
{
method: 'GET',
onSuccess: function (data) {
$('billing:city').replace('<select id="billing:city" name="billing[city]" class="required-entry">' +
'<option value=""></option>' + convertJsonToHtml(data.responseText, this,selectedCity) +
'</select>');
},
onFailure: $('billing:city').replace(normalImput),
parameters: {city_id: stateId, country_id: selectCountry}
}
);
}
function getAjaxReqestCustomer(action, selectCountry, stateId, normalImput, selectedCity) {
var request = new Ajax.Request(action,
{
method: 'GET',
onSuccess: function (data) {
$('city').replace('<select id="city" name="city" class="required-entry">' +
'<option value=""></option>' + convertJsonToHtml(data.responseText, this, selectedCity) +
'</select>');
},
onFailure: $('city').replace(normalImput),
parameters: {city_id: stateId, country_id: selectCountry}
}
);
}
function getAjaxReqestShip(action, selectCountry, stateId, normalImput,selectedCity) {
if (normalImput != null) {
var resetShip = true;
} else {
var resetShip = false;
}
var request = new Ajax.Request(action,
{
method: 'GET',
onSuccess: function (data) {
$('shipping:city').replace('<select id="shipping:city" name="shipping[city]" class="required-entry">' +
'<option value=""></option>' + convertJsonToHtml(data.responseText, this,selectedCity) +
'</select>');
},
onFailure: function (resetShip) {
if (resetShip) {
$('shipping:city').replace(normalImput)
}
},
parameters: {city_id: stateId, country_id: selectCountry}
}
);
}
function convertJsonToHtml(data, ship, selectedCity) {
var jsonData = data.evalJSON();
if (jsonData.length == 0) {
ship.replace(normalImput);
return;
}
console.log(jsonData);
htmlData = '';
jsonData.each(function (item) {
if (item.cityname == selectedCity) {
htmlData += '<option value="' + item.cityname + '" selected>' + item.cityname + '</option>';
} else {
htmlData += '<option value="' + item.cityname + '">' + item.cityname + '</option>';
}
});
return htmlData;
}
While the following code generates the City field on frontend in the form.
<div class="input-box">
<input type="text" title="<?php echo $this->__('City') ?>" name="billing[city]"
value="<?php echo $this->escapeHtml($this->getAddress()->getCity()) ?>"
class="input-text <?php echo $this->helper('customer/address')->getAttributeValidationClass('city') ?>"
id="billing:city"/>
</div>
Any help and tips are appreciated.I am a novice in Javascript and JSON so i am having a hard time playing with it.
EDIT:
I tried this:
div class="input-box">
<input type="text" title="<?php echo $this->__('City') ?>" name="billing[city]"
value="<?php echo $this->escapeHtml($this->getAddress()->getCity()) ?>"
class="input-text <?php echo $this->helper('customer/address')- >getAttributeValidationClass('city') ?>"
id="billing:city"/>
<select name="anything"><option value="undefined" disabled="selected">Select your city</option></select>
</div>
This works but adds the text 'Select your city' below the city field NOT inside it.
use this code as default showing before selecting city (i.e)set value as "undefined" disabled selected.
' +
'Select your city' + convertJsonToHtml(data.responseText, this, selectedCity) +
''

Resources