Monday, December 19, 2022

Wordpress ajax call on checkbox

Hello. Now I am explained how to make ajax call on checkbox checked in unchecked.

mainfile.php

<?php

/*

Plugin Name: Product Options With Conditions

Plugin URI: #

Description: You can set extra price for extra condition

Version: 1.0

Author: Chirag

Author URI: #

License: GPL2

*/


/**

 * DEFINE PATHS

 */

define( 'UC_PATH', plugin_dir_path( __FILE__ ) );

define( 'UC_FUNCTIONS_PATH', UC_PATH . 'includes/functions.php' );

define('CRUD_PLUGIN_PATH1', plugin_dir_path( __FILE__ ));

define( 'WP_PLUGIN_URL1', plugin_dir_url( __FILE__ ) );


if(!defined('ABSPATH')){ exit; }


add_action('admin_menu','addMenu');


function addMenu() {

  add_menu_page('Product Options1', 'Product Options2', 'manage_options' ,__FILE__, 'displaySetting', 'dashicons-wordpress');

}


//activate plugin and create table

register_activation_hook( __FILE__, 'unserConstructiontablecreate');

function unserConstructiontablecreate() {

  global $wpdb;

  global $table_name;

  $charset_collate = $wpdb->get_charset_collate();

  $table_name = $wpdb->prefix . 'custom_product_test';

  $sql = "CREATE TABLE IF NOT EXISTS `$table_name` (

  `cid` int(11) NOT NULL AUTO_INCREMENT,

  `productid` int(11) DEFAULT NULL,

  `labelname` VARCHAR(256) DEFAULT NULL,

  `inputtype` VARCHAR(256) DEFAULT NULL,

  `inputvalue` VARCHAR(256) DEFAULT NULL,

  `price` VARCHAR(256) DEFAULT NULL,

  `datetime` DATETIME DEFAULT NULL,

  `status` int(1) DEFAULT 1,

  PRIMARY KEY(cid)

  ) ENGINE=MyISAM DEFAULT CHARSET=latin1;

  ";

  if ($wpdb->get_var("SHOW TABLES LIKE '$table_name'") != $table_name) {

    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');

    dbDelta($sql);

  }

}


//include function file

require_once(UC_PATH.'/ajax_setdata.php');



function displaySetting() {

echo "<h2>Set all options</h2>";

htmlDisplayFunction();

}

function display_all_product($pid=NULL){

/*$args = array(

        'post_type'      => 'product',

        'posts_per_page' => 10,

        'product_cat'    => 'hoodies'

    );

    $loop = new WP_Query( $args );*/


    $products = wc_get_products( array( 'status' => 'publish', 'limit' => -1 ) );



  $select = '';

  $select.='<select name="selectProductId" id="selectProductId">';

  $select.='<option disabled>Select Product</option>';


  /*$pages = get_pages(); 

  foreach ($pages as $page_data) {

      $title = $page_data->post_title; 

      $pageid = $page_data->ID; 

      if (!empty($pid)) {

        if ($pid == $pageid ) {

          $selected = 'selected';

        } else {

          $selected = '';

        }

      }

      //echo "<pre>"; print_r($page_data);

      $select.='<option value="'.$pageid.'" '.$selected.' >'.$title.'</option>';

  }*/

    foreach ( $products as $product ){ 

    $productName= $product->get_title();

    $productid = $product->get_id();

    $select.='<option value="'.$productid.'" >'.$productName.' ('.$productid.')</option>';

    }

  $select.='</select>';

  return $select;

}

function htmlDisplayFunction(){ ?>

<div class="htmlDisplayFunction">

<form  method="post" name="setproductoptiontable" id="setproductoptiontable" accept-charset="utf-8">

<label for="pagename">Select Product</label>

<?php echo display_all_product(); ?>


<label>Add Input</label>

<select name="selectInput" id="selectInput" >

<option value="">Select Input Type</option>

<option value="textbox">Textbox</option>

<option value="checkbox">Checkbox</option>

<option value="radio">Radio Button</option>

</select>

</form>

</div>

<?php }


//add js

/*add_action( 'wp_enqueue_scripts', 'admin_enqueue_scripts1' );

function admin_enqueue_scripts1(){

  // JavaScript

    wp_enqueue_script( 'script-js1', plugins_url( '/admin/adminjs.js', __FILE__ ),array('jquery'));

  // Pass ajax_url to script.js

    wp_localize_script( 'script-js1', 'plugin_ajax_object',

            array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );

}*/


add_action('wp_enqueue_scripts','ava_test_init');

function ava_test_init() {

  wp_enqueue_style( 'custom_css', plugins_url('/css/custom.css', __FILE__ ) );

  //wp_enqueue_script( 'jquerymain', 'http://code.jquery.com/jquery-1.9.1.js');

  wp_enqueue_style( 'jquery-css', 'https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css');

  wp_enqueue_script( 'jquery-js', 'https://code.jquery.com/jquery-1.10.2.js');

  wp_enqueue_script( 'jqueyui-js', 'https://code.jquery.com/ui/1.10.4/jquery-ui.js');

  //wp_enqueue_script( 'my_custom_script3', plugins_url('/js/script.js',__FILE__)  );


  //wp_localize_script( 'frontscript', 'ajax_var', array( 'ajaxurl' => admin_url('admin-ajax.php') ));

  //wp_localize_script( 'my_custom_script3', 'ajax_var', array( 'ajaxurl' => admin_url('admin-ajax.php') ));

  //wp_enqueue_script( 'ava-test-js', plugins_url( '/admin/adminjs.js', __FILE__ ));


  wp_enqueue_script( 'my_custom_script3', WP_PLUGIN_URL1. 'js/script.js' );

  //wp_enqueue_script( 'my_custom_script4', WP_PLUGIN_URL1. 'js/jQuery.min.js' );

  wp_localize_script( 'my_custom_script3', 'ajax_var', array( 'ajaxurl' => admin_url('admin-ajax.php') ));

}

//end js


add_action('admin_footer','adminfooterjscode' ); // For back-end


function  adminfooterjscode()

{

  //echo "<script type=\"text/javascript\">alert('submit clicked');</script>";

  ?>

    <script type="text/javascript">

    /*jQuery(document).ready(function($){

$("#selectInput").change(function () {

        var inputvalue = this.value;

        if (inputvalue == 'textbox') {


        }

    });

});*/



    </script>

  <?php

}

?>


<?php

//display on single product page

add_action( 'woocommerce_before_add_to_cart_button', 'wpo_wcpdf_product_custom_field', 10, 3 );

function wpo_wcpdf_product_custom_field () {

  global $wpdb;

  global $product;

  $html_extra=$html_inputtype='';

  $pid = $product->get_id();

  $table_name = $wpdb->prefix . 'custom_product_test';

  $results = $wpdb->get_results("SELECT * FROM $table_name WHERE `productid` = $pid");

  $rowcount = count((array)$results);

  if ($rowcount > 0) {

    //changePrice($pid);

    $html_extra.= "<div class='newoptiondata' id='newoptiondata'>";

    $html_extra.="<table>";

    foreach ($results as $print) {

      $fee = $print->price;

      $html_extra.="<tr>";

      $html_extra.= "<td>".$print->labelname."(".$fee.")"."</td>";


      if ($print->inputtype == 'textbox') {

        $html_inputtype.="<input type='text' name='textbox' value='".$print->inputvalue."'>";

      }

      $html_extra.= "<td>".$html_inputtype."</td>";

      $html_extra.= "</tr>";

    }

    $html_extra.="</table>";

    $html_extra.=display_html_new($pid);

    $html_extra.="</div>";

  }

   //echo $html_extra;

}

//end

?>

<?php

/*

<!-- <div class="textboxdiv">

<label>Enter Lable for input text</label>

<input type="text" value="" name="inputlabel" id="inputlabel">

<br>

<label>Enter input settings</label> <br>

</div> -->

*/

?>

<?php

function changePrice($pid){

  // add_filter('woocommerce_get_price','change_price', 10, 2);

  // add_filter('woocommerce_get_regular_price','change_price', 10, 2);

  // add_filter('woocommerce_get_sale_price','change_price', 10, 2);

  

}

function change_price($price, $product){ 

       if($product->id == '60'){ 

          //$price = "150"; 

       } 

       update_post_meta($product->id, '_regular_price', (float)$price);

    update_post_meta($product->id, '_price', (float)$price);

      return $price; 

}

function display_html_new($pid){ 

  //$pid = $product->get_id();

  

  echo '<div class="newclass1" id="newclass1">

    <table>

      <tbody>

        <tr>

          <td colspan="2">

            <input type="hidden" name="productid" id="productid" value="'.$pid.'" >

            <input type="checkbox" name="checkbox_text" id="checkbox_text"> 

            <label for="checkbox_text">Click for add Print Text (<span class="woocommerce-Price-currencySymbol">₹</span>5)</label>

          </td>

        </tr>

        <tr id="autoUpdate" class="autoUpdate" style="display:none;">

          <td>Write text for print</td>

          <td><input type="text" name="printtext1" id="printtext1" placeholder="Write print text here"></td>

        </tr>

        <tr>

          <td colspan="2">

            <input type="radio" name="radiobutton" id="radiobutton1"> 

            <label for="radiobutton1">Red (<span class="woocommerce-Price-currencySymbol">₹</span>2)</label>

          </td>

        </tr>

        <tr>

          <td colspan="2">

            <input type="radio" name="radiobutton" id="radiobutton2"> 

            <label for="radiobutton2">Green (<span class="woocommerce-Price-currencySymbol">₹</span>3)</label>

          </td>

        </tr>

        <tr>

          <td colspan="2">

            <input type="radio" name="radiobutton" id="radiobutton3"> 

            <label for="radiobutton3">Blue (<span class="woocommerce-Price-currencySymbol">₹</span>4)</label>

          </td>

        </tr>

        <tr>

          <td colspan="2">

            <input type="checkbox" name="checkbox_2" id="checkbox_2"> 

            <label for="checkbox_2">Check for test1 (<span class="woocommerce-Price-currencySymbol">₹</span>5)</label>

          </td>

        </tr>

        <tr>

          <td colspan="2">

            <input type="checkbox" name="checkbox_3" id="checkbox_3"> 

            <label for="checkbox_3">Check for test2 (<span class="woocommerce-Price-currencySymbol">₹</span>5)</label>

          </td>

        </tr>

      </tbody>

    </table>

  </div>';


}

?>


script.js

$(document).ready(function () {

$('#checkbox_text').change(function () {

if (this.checked){

$('#autoUpdate').fadeIn('fast');

var op = 'add';

}

else {

$('#autoUpdate').fadeOut('fast');

var op = 'sub';

}

change_price(op);

});

function change_price(op){

var productid = $('#productid').val();

var optionvalue = '5';

var data = new FormData();

data.append("productid", productid);

data.append("optionvalue", optionvalue);

data.append("op", op);

data.append("action", "my_action2");

jQuery.post({

url: ajax_var.ajaxurl,

data: data,

contentType: false,

cache: false,

processData: false,

success: function (response) {

//$('.wqsubmit_message').html(response);

//setTimeout(function() { location.reload(); }, 3500);

}

});

}

});


/ajax_setdata.php

<?php 

//echo "chhhh";

add_action( 'wp_ajax_my_action2', 'my_action2' );

add_action( 'wp_ajax_nopriv_my_action2', 'my_action2' );


function my_action2(){

//print_r($_POST);

$productid = $_POST['productid'];

$optionvalue = $_POST['optionvalue'];

$op = $_POST['op'];


// Get an instance of the WC_Product object

$product = wc_get_product( $productid );


if ($op == 'add') {

$product_price = $product->get_price() + $optionvalue;

}

else{

$product_price = $product->get_price() - $optionvalue;

}

echo $product_price;

//$product['new_price'] = $product->get_sale_price() + $optionvalue;

//echo $product['new_price'];

// Set product prices

//$product->set_sale_price( $sale_price );

//$product->set_price( $price );


// Save data and update caches

//$product->save();

}

?>


No comments:

Post a Comment