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

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);
}

Related

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?

Dynamically populated select using ajax in WordPress

I want to use the value from my first dropdown in a MySQL query to generate a second dropdown. I'm doing this in wordpress and have tried to modify code I have used for a form plugin to apply to a coded form. But the code I have doesn't populate the second dropdown.
<form id="page-changer" action="" method="post"> <?php
$chart_types = $wpdb->get_results( "SELECT page_id, title FROM master_chart WHERE mod_id=$mod_id AND (geo_type=$geo_type OR geo_type IS NULL) ORDER BY sequence" );
echo '<select id="chart_type" required style="width: 100%; margin-bottom: 15px;"><option value="" disabled selected>Select Chart Type</option>';
foreach ($chart_types as $chart_type) :
echo '<option value="'.$chart_type->page_id.'">'.$chart_type->title.'</option>';
endforeach;
echo '</select>'; ?>
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery('#chart_type').change(function(){
var chartPOP=jQuery('#chart_type').val();
jQuery('#response').empty();
jQuery.ajax({
url:"<?php bloginfo( 'wpurl' ); ?>/wp-admin/admin-ajax.php",
type:'POST',
data:'action=populate_chart&pageID=' + chartPOP,
success:function(results) {
jQuery('#response').append(results);
}
});
});
});
</script> <?php
echo '<select id="response"><option value="" disabled selected>Select Frequency</option></select>';
function populate_chart() {
if( isset( $_POST['pageID'] ) ) :
$page_id=$_POST['pageID'];
global $wpdb;
$frequencies = $wpdb->get_results( "SELECT title FROM master_chartmeta WHERE measure >= $measure_toggle AND page_id=$page_id");
foreach( $results as $rows ) :
$option .= '<option value="'.$rows->title.'">';
$option .= $rows->title;
$option .= '</option>';
endforeach;
echo $option;
die();
endif;
}
add_action( 'wp_ajax_nopriv_populate_chart', populate_chart );
add_action( 'wp_ajax_populate_chart', populate_chart );

codeigniter dependent dropdown error

This is my code. It does not work with codeigniter 3.0 and jquery. I need to use dropdown dependent so I made that but it will be display "Error occur..." by alert() after choosing any item in first dropdown.
Please have a look to my source code. I don't know what is wrong. Thanks everyone
VIEW:
<script type="text/javascript">
$(document).ready(function(){
$('#senf').on('change', function(){
var senf_id = $(this).val();
if(senf_id == '')
{
$('#raste').prop('disabled', true);
}
else
{
$('#raste').prop('disabled', false);
$.ajax({
url:"<?php echo base_url() ?>index.php/shoppings/get_subgroup/",
type: "POST",
data: {'senf_id' : senf_id},
dataType: 'json',
success: function(data){
alert('okkk');
},
error: function(){
alert('Error occur...!!');
}
});
}
});
});
</script>
<div class="form-group ">
<label for="group_name" class="control-label col-lg-2">group 1</label>
<select id="senf" name="group">
<option value="" selected="selected">select</option>
<?php
foreach ($get_groups as $value) {
$group_id = $value['group_shop_id'];
$group_name = $value['group_shop_name'];
?>
<option value="<?php echo $group_id; ?>"> <?php echo $group_name; ?> </option>
<?php } ?>
</select>
<label for="raste" >group 2</label>
<select id="raste" name="raste">
<option value="">select</option>
</select>
</div>
CONTROLLER:
public function get_subgroup(){
$id = $this->input->post('senf_id');
$ajax_get_subgroup = $this->shopping_model->ajax_get_subgroup($id);
$pro_select_box = '';
$pro_select_box .= '<option value="">Select Province</option>';
foreach($ajax_get_subgroup as $ajax_get_subgroup_value){
$pro_select_box .= '<option>'. $ajax_get_subgroup_value->cat_shop_name .'</option>';
}
echo json_encode($pro_select_box);
}
MODEL:
public function ajax_get_subgroup($id){
$query = $this->db->get_where('cat_shopping_group', array('group_shop_id' => $id));
return $query->result();
}
try this
Controller
public function ajax_get_subgroup()
{
extract($_POST);
$tmp='';
$sql = "SELECT * FROM cat_shopping_group where group_shop_id=$id";
$data = $this->db->query($sql)->result_array();
$tmp .="<option value=''>-- Select --</option>";
foreach($data as $row)
{
$tmp .="<option value='".$row['your_id']."'>".$row['cat_shop_name ']."</option>";
}
die($tmp);
}`
AJAX
function get_data()
{
var id = $('#senf').val()
datana= 'id='+id
$.ajax({
type: 'POST',
url: '<?=base_url()?>your_controller/ajax_get_subgroup',
data: datana,
error: function(data) {
alert('Failed');
},
success: function(data)
{
$('#raste').html(data)
}
})
}
Views
<select id="senf" name="group" onchange='ajax_get_subgroup();'>
<option value="" selected="selected">select</option>
<?php
your code
?>
</select>
<select id="raste">
</select>
Hope this help.

Creating a cascade drop down without primary and foriegn key relationship with coeigniter

This is the structure of my table "task"
projectname
employee
clientname
task
Dependencies are as follows
One project has multiple task
One project has multiple employees
I need to create a dropdown list when user selects a particular project tasks relevant to them will automatically load to the next dropdown list. In this situation I do not need primary and foriegn key relationship. Any help would be really appreciated
This is my controller
public function Task(){
$data['cname'] = $this->welcome4->show_students3();
$data['projects'] = $this->welcome4->show_students();
$data['employee'] = $this->welcome4->show_students2();
$this->load->view('template/navigation');
$this->load->view('template/sideNav');
$this->load->view('template/header');
$this->load->view('Task',$data);
$this->load->view('template/footer');
}
This is my model
function show_students2(){
$query = $this->db->get('employee');
$query_result = $query->result();
return $query_result;
}
function show_students3(){
$query = $this->db->get('clientdetails');
$query_result = $query->result();
return $query_result;
}
function show_students4(){
$query = $this->db->get('task');
$query_result = $query->result();
return $query_result;
}
This is my view
<div class="form-group">
<label>Select Project</label>
</div>
<div class="form-group">
<select name="projectname" class="input form-control">
<option value="none" selected="selected">Select Project</option>
<?php foreach($projects as $s):?>
<option value="<?php echo $s->projectname?>"><?php echo $s->projectname?></option>
<?php endforeach;?>
</select>
</div>
<div class="form-group">
<label>Select Client</label>
<select name="cname" class="input form-control">
<option value="none" selected="selected">Select client</option>
<?php foreach($cname as $s):?>
<option value="<?php echo $s->cname?>"><?php echo $s->cname?></option>
<?php endforeach;?>
</select>
</div>
<div class="form-group">
<label>Select Employee</label>
</div>
<div class="form-group">
<select name="employee" class="input form-control">
<option value="none" selected="selected">Select Employee</option>
<?php foreach($employee as $s):?>
<option value="<?php echo $s->employee?>"><?php echo $s->employee?></option>
<?php endforeach;?>
</select>
</div>
This loads all projects, clients, employee in the database.But now I want when project is selected in the first drodown, second dropdown should show only relevant clients and employees to it. Not all of them
Lets consider this will be your Projects select box, in which you are loading data dynamically on page load with php.
<select name="projectname" id="projectname"></select>
Tasks select box.
<select name="tasks" id="tasks"></select>
Inside your controller add below mentioned code. This function will be used for get data from ajax call.
public function getTasks() {
$Id = $this->input->post('project_id');
if ($Id):
$this->load->model('Task_model', 'Tasks', TRUE);
$data = $this->Tasks->getProjectTasks($Id);
if ($data):
$result['status'] = true;
$result['records'] = $data;
endif;
else:
$result['status'] = false;
endif;
echo json_encode($fdata);
}
Inside model please add this function. Which will fetch data from DB
ans pass it to controller back.
public function getProjectTasks($id = null) {
if ($id):
$this->db->select('id,task');
$this->db->where('project_id', $id);
$this->db->where('status', TRUE);
$query = $this->db->get('tasks');
$records = $query->result();
if ($records):
return $records;
else:
return false;
endif;
else:
return false;
endif;
}
And finally in you View file please add below function.
$(document).on('#projectname', 'change', function() {
var projectId = $(this).val();
$.ajax({
type: 'POST',
url: 'URL',
data: {project_id: projectId},
dataType: "json",
beforeSend: function() {
$('#tasks')
.empty()
.append('<option selected="selected">Select Task</option>');
},
success: function(data) {
if (data.status) {
$.each(data.records, function(i, item) {
$('#tasks').append($('<option>', {
value: item.value,
text: item.text
}
));
});
} else {
$('#tasks')
.empty()
.append('<option selected="selected">No Task available</option>');
}
}
});
});

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;
}
}

Resources