I am doing an Ajax call and return the value. The post id is coming. But when i tried with this code, It is return blank
function visa_status() {
$postid = $_POST['appid'];
// args
$args = array(
'numberposts' => 1,
'post_type' => 'cpt_15',
'meta_key' => 'application_number',
'meta_value' => $postid
);
$metaarry = array();
// query
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
$posti = get_the_ID();
endwhile;
//echo $posti;
echo get_post_meta( $posti, 'given_name');
exit();
}
In the above code, $posti is coming. But get_post_meta() is not working.
This is my JS part
onStepChanging: function (event, currentIndex, newIndex) {
if ( newIndex === 1 ) {
jQuery('.wizard > .steps ul').addClass('step-2');
appId = jQuery('#appid').val();
jQuery.ajax({
type: 'POST',
dataType: 'json',
url: my_ajax_object.ajax_url,
data: {
'action': 'visa_status',
'appid': appId,
},
success: function (msg) {
console.log(msg);
}
});
} else {
jQuery('.wizard > .steps ul').removeClass('step-2');
}
if ( newIndex === 2 ) {
jQuery('.wizard > .steps ul').addClass('step-3');
} else {
jQuery('.wizard > .steps ul').removeClass('step-3');
}
return true;
},
Is there any mistake i have done. Please help me in this.
Try this
$given_name = get_post_meta( $posti, 'given_name', true );
echo $given_name;
OR Try this
echo get_post_meta( $posti, 'given_name', true );
Check here what get_post_meta function returns based on 3rd parameter.
Related
Am trying to get the shipping packages with ajax but its always returning empty value.
same issue while trying to call get the zones with: WC_Shipping_Zones::get_zones();
am using the same code in woocommerce_checkout_before_order_review and its working without any issue!
function jsforwp_add_like() {
check_ajax_referer( 'jsforwp_likes_nonce' );
$packages = WC()->shipping->get_packages();
if(empty($packages)){
$check = 'empty';
}else{
$check = $packages;
}
$success = true;
if( true == $success ) {
$response['type'] = 'success';
$response['zone'] = $check;
}
$response = json_encode( $response );
echo $response ;
die();
}
add_action( 'wp_ajax_jsforwp_add_like', 'jsforwp_add_like' );
add_action( 'wp_ajax_nopriv_jsforwp_add_like', 'jsforwp_add_like' );
My javascript
add_action('wp_footer','my_custom_ajax');
function my_custom_ajax(){
?>
<script>
(function($){
$( document.body ).on( 'updated_checkout', function(){
$.ajax({
type : 'post',
dataType : 'json',
url : jsforwp_globals.ajax_url,
data : {
action: 'jsforwp_add_like',
_ajax_nonce: jsforwp_globals.nonce
},
success: function( response ) {
if( 'success' == response.type ) {
console.log( response );
}
else {
console.log( 'Something went wrong, try logging in!' );
}
}
});
} );
} )( jQuery );
</script>
<?php
}
returned value
{type: "success", zone: "empty"}
I'm trying to add more than one fee to the order total amount checkout using ajax.
So far, the first fee, insurance_shipping_fee, is working correctly, but when checking the second one, premium_gift_box, I receive a 400 error ("xxx.com/wp-admin/admin-ajax.php").
Any ideas on why?
Any help appreciated
This is the full code:
// Calculate insurance fee
function as_calculate_insurance_fee() {
$shipping_country = WC()->customer->get_shipping_country();
$cart_subtotal = WC()->cart->subtotal;
$cart_subtotal_rounded = ceil($cart_subtotal / 100) * 100;
if($shipping_country == 'AU') {
if($cart_subtotal <= 5000) $insurance_fee = $cart_subtotal_rounded/100 + 1;
} else {
$chosen_methods = WC()->session->get( 'chosen_shipping_methods' );
$chosen_shipping = $chosen_methods[0];
if ($chosen_shipping == 'free_shipping:12' || $chosen_shipping == 'starshipit_4') {
if($cart_subtotal <= 5000) $insurance_fee = $cart_subtotal_rounded/100 * 3;
} else if($chosen_shipping == 'starshipit_5') {
$insurance_fee = ($cart_subtotal_rounded - 1000)/100 * 3 + 25;
}
}
return $insurance_fee;
}
// Add a Shipping Insurance checkbox field
function add_custom_checkout_checkbox() {
$insurance_fee = as_calculate_insurance_fee();
if( WC()->session->get('enable_fee') ) $checked = true;
else $checked = false;
woocommerce_form_field( 'insurance_fee', array(
'type' => 'checkbox',
'label' => __('<span class="woocommerce-Price-amount amount"><bdi><span class="woocommerce-Price-currencySymbol">'.get_woocommerce_currency().' </span>'.$insurance_fee.'</bdi></span>'),
'class' => array( 'form-row-wide' ),
), $checked );
}
add_action( 'as_review_order_after_shipping', 'add_custom_checkout_checkbox', 20 );
// Add Signature Gift Box checkbox field
function add_custom_checkout_checkbox_2() {
if( WC()->session->get('enable_fee_2') ) $checked = true;
else $checked = false;
woocommerce_form_field( 'premium_giftbox_fee', array(
'type' => 'checkbox',
'label' => __('<span class="woocommerce-Price-amount amount"><bdi><span class="woocommerce-Price-currencySymbol">'.get_woocommerce_currency().' </span>9</bdi></span>'),
'class' => array( 'form-row-wide' ),
), $checked );
}
add_action( 'as_review_order_before_shipping', 'add_custom_checkout_checkbox_2', 20 );
// Add custom fees
function custom_fee( $cart ) {
// Only on checkout
if ( ( is_admin() && ! defined( 'DOING_AJAX' ) ) || ! is_checkout() )
return;
$insurance_fee = as_calculate_insurance_fee();
if( WC()->session->get('enable_fee') )
$cart->add_fee( __( 'Insurance fee', 'woocommerce'), $insurance_fee );
if( WC()->session->get('enable_fee_2') )
$cart->add_fee( __( 'Siganture Gift Box fee', 'woocommerce'), 9 );
}
add_action( 'woocommerce_cart_calculate_fees', 'custom_fee', 20, 1 );
// Remove "(optional)" label on checkbox field
function remove_order_comments_optional_fields_label( $field, $key, $args, $value ) {
// Only on checkout page for Order notes field
if( ( 'insurance_fee' === $key || 'premium_giftbox_fee' === $key ) && is_checkout() ) {
$optional = ' <span class="optional">(' . esc_html__( 'optional', 'woocommerce' ) . ')</span>';
$field = str_replace( $optional, '', $field );
}
return $field;
}
add_filter( 'woocommerce_form_field' , 'remove_order_comments_optional_fields_label', 10, 4 );
// jQuery - Ajax script
function checkout_fees_script() {
// Only on Checkout
if( is_checkout() && ! is_wc_endpoint_url() ) :
if( WC()->session->__isset('enable_fee') )
WC()->session->__unset('enable_fee');
if( WC()->session->__isset('enable_fee_2') )
WC()->session->__unset('enable_fee_2');
?>
<script type="text/javascript">
jQuery( function($){
if (typeof wc_checkout_params === 'undefined')
return false;
$('form.checkout').on('change', 'input[name=insurance_fee]', function(e){
var fee = $(this).prop('checked') === true ? '1' : '';
$.ajax({
type: 'POST',
url: wc_checkout_params.ajax_url,
data: {
'action': 'enable_fee',
'enable_fee': fee,
},
success: function (result) {
$('body').trigger('update_checkout');
},
});
});
$('form.checkout').on('change', 'input[name=premium_giftbox_fee]', function(e){
var fee2 = $(this).prop('checked') === true ? '1' : '';
$.ajax({
type: 'POST',
url: wc_checkout_params.ajax_url,
data: {
'action': 'enable_fee_2',
'enable_fee_2': fee2,
},
success: function (result) {
$('body').trigger('update_checkout');
},
});
});
});
</script>
<?php
endif;
}
add_action( 'wp_footer', 'checkout_fees_script' );
// Get Ajax request and saving to WC session
function get_enable_fee() {
if ( isset($_POST['enable_fee']) ) {
WC()->session->set('enable_fee', ($_POST['enable_fee'] ? true : false) );
}
if ( isset($_POST['enable_fee_2']) ) {
WC()->session->set('enable_fee_2', ($_POST['enable_fee_2'] ? true : false) );
}
die();
}
add_action( 'wp_ajax_enable_fee', 'get_enable_fee' );
add_action( 'wp_ajax_nopriv_enable_fee', 'get_enable_fee' );
```
You forgot to register the second fee ajax action.
It should be like that.
add_action( 'wp_ajax_enable_fee', 'get_enable_fee' );
add_action( 'wp_ajax_nopriv_enable_fee', 'get_enable_fee' );
add_action( 'wp_ajax_enable_fee_2', 'get_enable_fee' );
add_action( 'wp_ajax_nopriv_enable_fee_2', 'get_enable_fee' );
Hi I try to make validation form with ajax. When Textbox is empty, There is no problem everything works fine and give right errors. But when I fill in form Ajax else is not working and it goes to error:function . Please could you help!
When I enable dataType:"JSON",
I see output
false
Basvuru:1379 {isim: " İsim Zorunludur!", soyad: " Soyad Zorunludur!", emailadresi: " Email Adresi Zorunludur!", ilce: "", il: "", …}
When I disable dataType:"JSON", ı could see console.log(data) of post datas otherwise goesto error:function
controller:
function basvuru_ekle()
{
$this->form_validation->set_rules('isim', 'İsim', 'required');
$this->form_validation->set_rules('soyad', 'Soyad', 'required' );
$this->form_validation->set_rules('emailadresi', 'Email Adresi', 'required' );
$this->form_validation->set_rules('ilce', 'İlçe', 'required' );
$this->form_validation->set_rules('il', 'İl', 'required' );
$this->form_validation->set_rules('adres', 'Adres', 'required' );
$this->form_validation->set_rules('kordinat', 'Kordinat', 'required' );
//$this->form_validation->set_error_delimiters('Hata:', '');
$this->form_validation->set_message('required', ' {field} Zorunludur!');
if ($this->form_validation->run() == FALSE) {
$data = array(
'isim' => form_error('isim'),
'soyad' => form_error('soyad'),
'emailadresi' => form_error('emailadresi'),
'ilce' => form_error('ilce'),
'il' => form_error('il'),
'adres' => form_error('adres'),
'kordinat' => form_error('kordinat'),
'status'=> FALSE
);
echo json_encode($data);
}
else {
$basvurubiletnumarasi = strftime("%Y%m%d%H%M%S");
$basvurudurumu = "1";
$data = array(
'basvurubiletnumarasi' => $basvurubiletnumarasi,
'isim' => $this->input->post('isim') ,
'soyad' => $this->input->post('soyad') ,
'emailadresi' => $this->input->post('emailadresi') ,
'ilce' => $this->input->post('ilce') ,
'il' => $this->input->post('il') ,
'ilce' => $this->input->post('ilce') ,
'adres' => $this->input->post('adres') ,
'kordinat' => $this->input->post('kordinat') ,
'basvurudurumu' => $basvurudurumu,
// 'olusturulmatarihi' => $this->input->post('olusturulmatarihi'),
);
$insert = $this->basvuru_model->basvuru_ekle($data);
echo $data=json_encode(array("status" => TRUE));
}
}
View Ajax:
function save()
{
var url;
if(save_method == 'add')
{
url = "<?php echo site_url('index.php/basvuru/basvuru_ekle')?>";
}
else
{
url = "<?php echo site_url('index.php/basvuru/basvuru_guncelle')?>";
}
// ajax adding data to database
$.ajax({
type:"POST",
url:url,
data:$('#form').serialize(),
dataType:"JSON",
success:function (data) {
// var obj = $.parseJSON(data);
// $('#data1').html(data);
$('#isim1').html(data.isim);
$('#soyad1').html(data.soyad);
$('#emailadresi1').html(data.emailadresi);
$('#ilce1').html(data.ilce);
$('#il1').html(data.il);
$('#adres1').html(data.adres);
$('#kordinat1').html(data.kordinat);
console.log(data.status);
// alert(data.sonuc);
if(data.status){
console.log("false");
}
else{
console.log("true");
console.log(data);
}
},
error:function(data){
console.log("error");
}
});
}
model:
function basvuru_ekle($data)
{
print_r($data);
$this->db->insert($this->table, $data);
return $this->db->insert_id();
}
Remove print_r() in insert function and try this:
function save() {
var url;
if (save_method == 'add') {
url = "<?php echo site_url('index.php/basvuru/basvuru_ekle')?>";
} else {
url = "<?php echo site_url('index.php/basvuru/basvuru_guncelle')?>";
}
// ajax adding data to database
$.ajax({
type: "POST",
url: url,
data: $('#form').serialize(),
dataType: "JSON",
success: function(data) {
if (data.status == false) {
console.log('false');
$('#isim1').html(data.isim);
$('#soyad1').html(data.soyad);
$('#emailadresi1').html(data.emailadresi);
$('#ilce1').html(data.ilce);
$('#il1').html(data.il);
$('#adres1').html(data.adres);
$('#kordinat1').html(data.kordinat);
} else {
console.log("true");
}
},
error: function(data) {
console.log("error");
}
});
}
I checked to find the exact problem.As Alex said problem was because of Print_r() in modal. After I erased it ,now it works fine.
After fixed the problem.
view:
function save()
{
var url;
if(save_method == 'add')
{
url = "<?php echo site_url('index.php/basvuru/basvuru_ekle')?>";
}
else
{
url = "<?php echo site_url('index.php/basvuru/basvuru_guncelle')?>";
}
// ajax adding data to database
$.ajax({
type:"POST",
url:url,
data:$('#form').serialize(),
dataType:"JSON",
success: function(data) {
if (data.status == false) {
console.log('false');
$('#isim1').html(data.isim);
$('#soyad1').html(data.soyad);
$('#emailadresi1').html(data.emailadresi);
$('#ilce1').html(data.ilce);
$('#il1').html(data.il);
$('#adres1').html(data.adres);
$('#kordinat1').html(data.kordinat);
} else {
console.log("true");
$('#modal_form').modal('hide');
location.reload();// for reload a page
}
},
error: function (jqXHR, textStatus, errorThrown) {
if (jqXHR.status == 404) { alert('AJAX page not found.');
}
else {
alert('AJAX Error: ' + textStatus + ': ' + errorThrown); }
}
});
}
controller:
function basvuru_ekle()
{
$this->form_validation->set_rules('isim', 'İsim', 'required');
$this->form_validation->set_rules('soyad', 'Soyad', 'required' );
$this->form_validation->set_rules('emailadresi', 'Email Adresi', 'required' );
$this->form_validation->set_rules('ilce', 'İlçe', 'required' );
$this->form_validation->set_rules('il', 'İl', 'required' );
$this->form_validation->set_rules('adres', 'Adres', 'required' );
$this->form_validation->set_rules('kordinat', 'Kordinat', 'required' );
//$this->form_validation->set_error_delimiters('Hata:', '');
$this->form_validation->set_message('required', ' {field} Zorunludur!');
if ($this->form_validation->run() == FALSE) {
$data = array(
'isim' => form_error('isim'),
'soyad' => form_error('soyad'),
'emailadresi' => form_error('emailadresi'),
'ilce' => form_error('ilce'),
'il' => form_error('il'),
'adres' => form_error('adres'),
'kordinat' => form_error('kordinat'),
'status'=> FALSE
);
echo json_encode($data);
}
else {
$basvurubiletnumarasi = strftime("%Y%m%d%H%M%S");
$basvurudurumu = "1";
$data = array(
'basvurubiletnumarasi' => $basvurubiletnumarasi,
'isim' => $this->input->post('isim') ,
'soyad' => $this->input->post('soyad') ,
'emailadresi' => $this->input->post('emailadresi') ,
'ilce' => $this->input->post('ilce') ,
'il' => $this->input->post('il') ,
'ilce' => $this->input->post('ilce') ,
'adres' => $this->input->post('adres') ,
'kordinat' => $this->input->post('kordinat') ,
'basvurudurumu' => $basvurudurumu,
// 'olusturulmatarihi' => $this->input->post('olusturulmatarihi'),
);
$insert = $this->basvuru_model->basvuru_ekle($data);
echo json_encode(array(
"status" => TRUE,
));
}
}
model:
function basvuru_ekle($data)
{
$this->db->insert($this->table, $data);
return $this->db->insert_id();
}
I am trying to add custom product type to product like here wild card
and i succeeded but now i have to add this value to cart with ajax how i suppose to do this with drop-down and shortcode? i just added load_book.js but didn't added any script code because i don't know how to write ajax code for this. thanks.
My code:
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
add_filter("product_type_options", "woo_bookable_product");
function woo_bookable_product($product_type_options)
{
$product_type_options["Bookable"] = array(
"id" => "_bookable",
"wrapper_class" => "show_if_simple",
"label" => "Bookable",
"description" => "Book Your Product",
"default" => "yes",
);
return $product_type_options;
}
add_action("save_post_product",'woo_save_bookable_data', 10, 3);
function woo_save_bookable_data($post_ID, $product, $update)
{
$meta_value = $_POST["_bookable"] ? 'yes' : 'no';
update_post_meta($product->ID, "_bookable" ,$meta_value);
}
function woo_bookable_scripts()
{
wp_enqueue_script('load_book', plugin_dir_url( __FILE__ ).'js/load_book.js',array('jquery'));
wp_localize_script('load_book','ajax_object',array('ajax_url'=>admin_url('admin-ajax.php')));
}
add_action('wp_enqueue_scripts','woo_bookable_scripts');
add_action('wp_ajax_woo_bookable_shortcode', 'woo_bookable_shortcode');
add_action('wp_ajax_nopriv_woo_bookable_shortcode', 'woo_bookable_shortcode');
function woo_bookable_shortcode()
{
$Data = '';
$query = new WP_Query(array(
'post_type' => 'product',
'meta_key' => '_bookable'
));
$Data.='<select name="woo_book_id" class="woo_book_pro">
<option value="0">Bookable Products</option>';
if($query->have_posts()):while($query->have_posts()):$query->the_post();
$Data.='<option value="'. get_the_ID() .'">'. get_the_title() .'</option>';
endwhile;endif;
$Data.='</select>';
$Data.= woo_bookable_add_to_cart();
echo $Data;
}
add_shortcode('bookable','woo_bookable_shortcode');
Finally find the solution
PHP:
<?php
/**
* Plugin Name: Bookable
* Description: Add shortcode [bookable] or in php - echo do_shortcode('[bookable]');
* Version: 0.1
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
if ( class_exists( 'WooCommerce' ) || in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) || function_exists( 'WC' ) && is_object( WC() ) && is_a( WC(), 'WooCommerce' ) ){
/////////////////////////////////////////////////////////////////////////////////////////////////
add_filter("product_type_options", "woo_bookable_product");
if(!function_exists('woo_bookable_product')):
function woo_bookable_product($product_type_options)
{
$product_type_options["bookable"] = array(
"id" => "_bookable",
"wrapper_class" => "show_if_simple",
"label" => __("Bookable",'woocommerce'),
"description" => __("Check if product is bookable or not",'woocommerce'),
"default" => "no",
);
return $product_type_options;
}
endif;
/////////////////////////////////////////////////////////////////////////////////////////////////
add_action( 'woocommerce_add_cart_item_data', 'woo_bookable_custom_field', 10, 2 );
if(!function_exists('woo_bookable_custom_field')):
function woo_bookable_custom_field( $cart_item_data, $product_id )
{
$get_custom_meta = get_post_meta( $product_id , '_bookable', true );
if( $get_custom_meta == 'yes' )
{
$cart_item_data[ '_bookable' ] = $get_custom_meta;
$len = 10;
$word = array_merge(range('a', 'z'), range('A', 'Z'));
$name = shuffle($word);
$name = substr(implode($word), 0, $len);
$cart_item_data['unique_key'] = $name ;
}
return $cart_item_data;
}
endif;
/////////////////////////////////////////////////////////////////////////////////////////////////
add_filter( 'woocommerce_get_item_data', 'render_woo_bookable_meta_data', 10, 2 );
if(!function_exists('render_woo_bookable_meta_data')):
function render_woo_bookable_meta_data( $cart_data, $cart_item )
{
global $woocommerce;
$custom_items = array();
if( !empty( $cart_data ) )
{
$custom_items = $cart_data;
}
if( isset( $cart_item['_bookable'] ) )
{
$custom_items[] = array(
"name" => __( "Bookable", "woocommerce" ),
"value" => $cart_item['_bookable'] );
$custom_items[] = array(
"name" => __( $cart_item['unique_key'], "woocommerce" ),
"value" => '$10' );
}
return $custom_items;
}
endif;
/////////////////////////////////////////////////////////////////////////////////////////////////
add_action( 'woocommerce_before_calculate_totals', 'add_custom_price' );
if(!function_exists('add_custom_price')):
function add_custom_price( $cart_object )
{
foreach ( $cart_object->get_cart() as $hash => $value )
{
if($value['_bookable'] && $value['data']->is_on_sale())
{
$newprice = $value['data']->get_sale_price()+10;
$value['data']->set_price( $newprice );
}
elseif($value['_bookable'])
{
$not_sell = $value['data']->get_regular_price()+10;
$value['data']->set_price( $not_sell );
}
}
}
endif;
/////////////////////////////////////////////////////////////////////////////////////////////////
add_action( 'woocommerce_cart_calculate_fees', 'woo_bookable_cart_calculate_totals', 10, 1 );
if(!function_exists('woo_bookable_cart_calculate_totals')):
function woo_bookable_cart_calculate_totals( $cart_object )
{
$get_price = 0;
foreach ( $cart_object->get_cart() as $hash => $value )
{
if(!empty($value['_bookable']))
{
$percent = 10;
$get_price += $value['line_total'];
$fee = ($get_price * $percent) / 100;
}
}
$cart_object->add_fee( __("Bookable Charge($percent%)"),$fee ,false );
}
endif;
/////////////////////////////////////////////////////////////////////////////////////////////////
add_action("save_post_product",'woo_save_bookable_data', 10, 3);
if(!function_exists('woo_save_bookable_data')):
function woo_save_bookable_data($post_ID, $product, $update)
{
$meta_value = $_POST["_bookable"];
if(isset($meta_value))
{
$meta_value = 'yes';
update_post_meta( $product->ID, "_bookable" ,$meta_value );
wp_set_object_terms( $product->ID, 'Bookable', 'product_tag' );
}
else
{
delete_post_meta($product->ID, "_bookable");
wp_remove_object_terms( $product->ID, 'Bookable', 'product_tag' );
}
}
endif;
/////////////////////////////////////////////////////////////////////////////////////////////////
add_action('woocommerce_add_order_item_meta','woo_bookable_add_order_meta', 9, 3 );
if(!function_exists('woo_bookable_add_order_meta')):
function woo_bookable_add_order_meta( $item_id, $item_values, $item_key )
{
if( ! empty( $item_values['_bookable'] ) )
wc_update_order_item_meta( $item_id, '_bookable', sanitize_text_field( $item_values['_bookable'] ) );
}
endif;
/////////////////////////////////////////////////////////////////////////////////////////////////
}
else
{
add_action( 'admin_notices', 'woo_bookable_active' );
if(!function_exists('woo_bookable_active')):
function woo_bookable_active()
{
$err_text = site_url()."/wp-admin/plugin-install.php?tab=plugin-information&plugin=woocommerce&TB_iframe=true";
?>
<div class="error notice">
<p><?php echo sprintf("Please Activate or <a href='%s'>Install Woocommerce</a> to use Bookable plugin",$err_text); ?></p>
</div>
<?php
//If woocommerce is not installed deactive plugin
if (is_plugin_active('bookable/bookable.php')) {
deactivate_plugins(plugin_basename(__FILE__));
}
unset($_GET['activate']);
}
endif;
}
/////////////////////////////////////////////////////////////////////////////////////////////////
add_action('wp_enqueue_scripts','woo_bookable_scripts');
function woo_bookable_scripts()
{
wp_enqueue_script('load_book', plugin_dir_url( __FILE__ ).'js/load_book.js',array('jquery'));
wp_localize_script('load_book','ajax_object',array('ajax_url'=>admin_url('admin-ajax.php')));
}
/////////////////////////////////////////////////////////////////////////////////////////////////
add_shortcode('bookable','woo_bookable_shortcode');
function woo_bookable_shortcode()
{
global $product;
$Data = '';
$query = new WP_Query(array(
'post_type' => 'product',
'meta_key' => '_bookable',
'meta_value' => 'yes'
) );
$Data.='<select name="woo_book_id" class="woo_book_pro">
<option value="0">Bookable Products</option>';
if($query->have_posts()):while($query->have_posts()):$query->the_post();
$Data.='<option value="'. get_the_ID() .'">'. get_the_title() .'</option>';
endwhile;endif;
$Data.='</select>';
$Data.= woo_bookable_add_to_cart();
echo $Data;
}
/////////////////////////////////////////////////////////////////////////////////////////////////
$InArray = array('woo_bookable_product_id','woo_bookable_add_to_cart');
foreach($InArray as $SingleValue)
{
add_action('wp_ajax_'.$SingleValue,$SingleValue);
add_action('wp_ajax_nopriv_'.$SingleValue,$SingleValue);
}
/////////////////////////////////////////////////////////////////////////////////////////////////
function woo_bookable_product_id()
{
$product_id = $_POST['product_id'];
if($product_id != null && $product_id!=0)
{
$add['id'] = 'success';
$add['msg'] = 'View Cart';
WC()->cart->add_to_cart( $product_id);
}
else
{
$add['id'] = 'fail';
$add['msg'] = 'Please Select Product From DropDown!!';
}
echo json_encode($add);
die();
}
/////////////////////////////////////////////////////////////////////////////////////////////////
function woo_bookable_add_to_cart()
{
return '<button type="submit" style="margin-left:10px" name="add-to-cart" value="" class="single_add_to_cart_button button alt">Add To Cart</button>
<div class="message"></div>';
die();
}
ajax Script:
jQuery(document).ready(function()
{
jQuery("select.woo_book_pro").change(function(e)
{
var id = jQuery('.woo_book_pro option:selected').val();
var action = 'woo_bookable_add_to_cart';
jQuery.ajax({
url:ajax_object.ajax_url,
type:"POST",
dataType:"json",
cache:false,
data:{
"action":action,
"id":id
},
success: function(data)
{
jQuery('.single_add_to_cart_button').attr('value',id);
jQuery('.single_add_to_cart_button').attr("disabled", "disabled");
jQuery('.single_add_to_cart_button').text('WAIT...');
setTimeout(function() {
jQuery('.single_add_to_cart_button').removeAttr("disabled");
jQuery('.single_add_to_cart_button').text('Add To Cart');
}, 3000);
}
});
});
jQuery(".single_add_to_cart_button").click(function(e) {
e.preventDefault();
var product_id = jQuery(this).val();
var action = 'woo_bookable_product_id';
jQuery('.message').empty();
jQuery.ajax({
url:ajax_object.ajax_url,
type:"POST",
dataType:"json",
cache:false,
data:{
"action":action,
"product_id":product_id
},
success: function(data)
{
if(data.id == 'success')
{
jQuery('.message').prepend(data.msg);
return false;
}
if(data.id == 'fail')
{
jQuery('.message').prepend(data.msg).css('color','#F33')
return false;
}
}
});
});
});
I've created a wordpress plugin to vote on a post, using ajax.
When you click the 'vote' link the jquery popup works, your vote is added but then the page reloads
add_action("wp_ajax_my_user_vote", "my_user_vote");
add_action("wp_ajax_nopriv_my_user_vote", "my_must_login");
function my_user_vote() {
if ( !wp_verify_nonce( $_REQUEST['nonce'], "my_user_vote_nonce")) {
exit("No naughty business please");
}
$user_id = get_current_user_id();
date_default_timezone_set('GMT+2');
$dateVoted = get_user_meta($user_id, 'date');
$today = date('d M Y');
if ($dateVoted === $today){
//Already Voted
echo '<script language="javascript">';
echo 'alert("already voted")';
/*
echo 'alert("User ID: ' . $user_id . '")';
echo 'alert("Date Voted: ' . $dateVoted . '")';
echo 'alert("Today: ' . $today . '")';
*/
echo '</script>';
}else{
$vote_count = get_post_meta($_REQUEST["post_id"], "votes", true);
$vote_count = ($vote_count == '') ? 0 : $vote_count;
$new_vote_count = $vote_count + 1;
$vote = update_post_meta($_REQUEST["post_id"], "votes", $new_vote_count);
if($vote === false) {
$result['type'] = "error";
$result['vote_count'] = $vote_count;
}
else {
$result['type'] = "success";
$result['vote_count'] = $new_vote_count;
}
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$result = json_encode($result);
echo $result;
}
else {
header("Location: ".$_SERVER["HTTP_REFERER"]);
}
update_user_meta( $user_id, 'date', $today );
}
die();
}
function my_must_login() {
echo "You must log in to vote";
die();
}
add_action( 'init', 'my_script_enqueuer' );
function my_script_enqueuer() {
wp_register_script( "my_voter_script", WP_PLUGIN_URL.'/video-of-the- day/my_voter_script.js', array('jquery') );
wp_localize_script( 'my_voter_script', 'myAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' )));
wp_enqueue_script( 'jquery' );
wp_enqueue_script( 'my_voter_script' );
}
I also have a jquery file:
jQuery(document).ready( function() {
jQuery(".user_vote").click( function() {
post_id = jQuery(this).attr("data-post_id")
nonce = jQuery(this).attr("data-nonce")
jQuery.ajax({
type : "post",
dataType : "json",
url : myAjax.ajaxurl,
data : {action: "my_user_vote", post_id : post_id, nonce: nonce},
success: function(response) {
if(response.type == "success") {
}
else {
alert("Your vote could not be added")
}
}
});
})
});
why is the ajax not working?
Try this
jQuery(".user_vote").click( function(e) {
e.PreventDefault();
});