Dynamically populated select using ajax in WordPress - ajax

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

Related

woocommerce product sort order change by our own weight value or menu order

I need to add a specified value or weight for a product so that product will display as per order on the woocommerce shop page. I think this can be done by product bulk edit. But not sure is it right or any conflict may arise in the future. can anyone suggest how I a custom sort function as per a given value for the bulk products? Currently, the drag and drop method is difficult in the case of thousand of products.
add_action( 'woocommerce_product_bulk_edit_start', 'custom_field_product_bulk_edit', 10, 0 );
function custom_field_product_bulk_edit() {
?>
<div class="inline-edit-group">
<label class="alignleft">
<span class="title"><?php _e('Custom Sort Weight', 'woocommerce'); ?></span>
<span class="input-text-wrap">
<select class="change_t_dostawy change_to" name="change_t_dostawy">
<?php
$options = array(
'' => __( '— No change —', 'woocommerce' ),
'1' => __( 'Change to:', 'woocommerce' ),
);
foreach ( $options as $key => $value ) {
echo '<option value="' . esc_attr( $key ) . '">' . $value . '</option>';
}
?>
</select>
</span>
</label>
<label class="change-input">
<input type="text" name="_t_dostawy" class="text t_dostawy" placeholder="<?php _e( 'Enter Weight Here ', 'woocommerce' ); ?>" value="" />
</label>
</div>
<?php
}
// Save the custom fields data when submitted for product bulk edit
add_action('woocommerce_product_bulk_edit_save', 'save_custom_field_product_bulk_edit', 10, 1);
function save_custom_field_product_bulk_edit( $product ){
if ( $product->is_type('simple') || $product->is_type('external') ){
$product_id = method_exists( $product, 'get_id' ) ? $product->get_id() : $product->id;
if ( isset( $_REQUEST['_t_dostawy'] ) ){
// update_post_meta( $product_id, 'menu_order', sanitize_text_field( $_REQUEST['_t_dostawy'] ) );
$arg=array('ID' => $product_id,'menu_order' => $_REQUEST['_t_dostawy']);
$result = wp_update_post($arg);
}
}
}
I have added an option on quick edit and then update the menu order value by ajax. so that all the product having same menu order will be displayed on same row.But this is not a correct way.
So I have do other stuff that added text box in the product listing and where we can add a menu order for product.
//
Add product new column in administration
add_filter( 'manage_edit-product_columns', 'woo_product_weight_column', 20 );
function woo_product_weight_column( $columns ) {
$columns['sort_weight'] = esc_html__( 'Weight', 'woocommerce' );
return $columns;
}
// Populate weight column
add_action( 'manage_product_posts_custom_column', 'woo_product_weight_column_data', 2 );
function woo_product_weight_column_data( $column ) {
global $post;
if ( $column == 'sort_weight' ) {
$postval = get_post( $post->ID);
$menu_order_new = $postval->menu_order;
?>
<input type="text" name="menuorder" id="id_<?php echo $post->ID;?>" data-productid="<?php echo $post->ID;?>" value="<?php echo $menu_order_new; ?>" class="menuorder"/>
<?php
}
}
add_action('admin_head', 'my_column_width');
function my_column_width() {
echo '<style type="text/css">';
echo 'table.wp-list-table .column-sort_weight { width: 101px; text-align: left!important;padding: 5px;}';
echo 'table.wp-list-table .column-wpseo-score { width: 101px; text-align: left!important;padding: 5px;}';
echo'.menuorder{ width: 101px; }';
echo '</style>';
}
// this code adds jQuery script to website footer that allows to send AJAX request
add_action( 'admin_footer', 'misha_jquery_event' );
function misha_jquery_event(){
echo "<script>jQuery(function($){
var weight_val;
var pr_id;
jQuery('.menuorder').on('input', function(){
weight_val = $(this).val();
pr_id=$(this).attr('data-productid');
var dataVariable = {
'action': 'productmetasave',
'product_id': pr_id,
'value':weight_val
};
jQuery.ajax({
url: ajaxurl,
type: 'POST',
data: dataVariable,
success: function (response) {
if(response==1){
location.reload(true);
}else{
console.log('Failed To update menu-order ');
}
}
});
});
});</script>";
}
// this small piece of code can process our AJAX request
add_action( 'wp_ajax_productmetasave', 'misha_process_ajax' );
function misha_process_ajax(){
if($_POST['product_id'] && $_POST['value'] ){
$arg=array('ID' => $_POST['product_id'],'menu_order' => $_POST['value']);
$rs = wp_update_post($arg);
if($rs){
echo "1";
}else{
echo "0";
}
}
die();
}

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

Making Dependent Combobox in codeigniter project

i am suffering greatly but still unable to make a dependent dropdown box in Codeigniter .
Here is the schema :
groups(group_id,group)
forum(forum_id,subject)
group_forum(group_id,forum_id)
Here is my code :
model
function get_group(){
$query = $this->db->get('group');
return $query->result();
}
function get_subject_by_group($id)
{
$subjects=array();
$this->db->from('forum');
$this->db->join('group_forum','group_forum.forum_id=forum.forum_id','group_id='.$id);
$q=$this->db->get();
foreach($q->result() as $y)
{
$subjects[$y['forum_id']] = $y['subject'];
}
return $subjects;
}
}
Controller:
<?php
class C_control_form extends CI_Controller {
function add_all(){
#Validate entry form information
$this->load->model('Model_form');
$this->form_validation->set_rules('f_group', 'Group', 'trim|required');
$this->form_validation->set_rules('f_forum', 'Forum', 'trim|required');
$data['groups'] = $this->Model_form->get_group(); //gets the available groups for the dropdown
if ($this->form_validation->run() == FALSE)
{
$this->load->view('header_for_combo',$data);
$this->load->view('view_form_all', $data);
$this->load->view('footer_for_combo',$data);
}
else
{
#Add Member to Database
$this->Model_form->add_all();
$this->load->view('view_form_success');
}
}
function get_subjects($group)
{
//echo "hi";
$this->load->model('Model_form');
header('Content-Type: application/x-json; charset=utf-8');
echo (json_encode($this->Model_form->get_subject_by_group($group)));
}
}
?>
View
<html>
<head>
<script type="text/javascript" src="<?php echo base_url("js/jquery-1.7.2.min.js"); ?>" ></script>
<script type="text/javascript">
// $('#f_group, #f_forum').hide();
$(document).ready(function(){
$('#f_group').change(function(){
var group_id = $('#f_group').val();
if (group_id != ""){
var post_url = "index.php/c_control_form/get_subjects/"+group_id;
// var post_url = "<?php echo base_url();?>"+"c_control_form/get_subjects"+group_id;
$.ajax({
type: 'POST',
url: post_url,
dataType : 'json',
success: function(subjects) //we're calling the response json array 'cities'
{
$("#f_forum > option").remove();
// $('#f_forum').empty();
// $('#f_forum, #f_forum_label').show();
$.each(subjects,function(forum_id,subject)
{
var opt = $('<option/>'); // here we're creating a new select option for each group
opt.val(forum_id);
//alert(id);
opt.text(subject);
$('#f_forum').append(opt);
});
} //end success
}); //end AJAX
} else {
$('#f_forum').empty();
// $('#f_forum, #f_forum_label').hide();
}//end if
}); //end change
});
</script>
</head>
<body>
<?php echo form_open('c_control_form/add_all'); ?>
<p>
<label for="f_group">Group<span class="red">*</span></label>
<select id="f_group" name="f_group">
<option value=""></option>
<?php
foreach($groups as $group){
echo '<option value="' . $group->group_id . '">' . $group->group_name.'</option>';
}
?>
</select>
</p>
<p>
<label for="f_forum">Subject<span class="red">*</span></label>
<select id="f_forum" name="f_forum" id="f_forum_label">
<option value=""></option>
</select>
</p>
<?php echo form_close(); ?>
</body>
Please change
$subjects[$y['forum_id']] = $y['subject'];
to
$subjects[$y->forum_id] = $y->subject;
in the model file. Also spaces or newlines in model php file after and before the php tags.
EDIT: Added below
function(subjects){
var select = $('#f_forum').empty();
$.each(subjects.values, function(i,item) {
select.append( '<option value="'
+ item.id
+ '">'
+ item.name
+ '</option>' );
});

Resources