I'm having a problem, a need to apply a filter when user changes the selection of an input radio, I did this code, but it only works if I reload the page, what can I do to avoid reload and the page charge the filter whithout reloading?
`
add_action( 'wp_footer', 'wpmc_set_session_on_button_click' );
function wpmc_set_session_on_button_click() {
session_start();
$array_selectores = $_SESSION['array_selectores'];
$json = json_encode($array_selectores);
?>
<script>
document.querySelectorAll('input[name="horario-liga"]').forEach(function(input) {
input.addEventListener("change", function(e) {
var jsArray = <?php echo $json; ?>;
var horarioLigaValue = document.querySelector('input[name="horario-liga"]:checked').value;
var data = {
action: 'wpmc_set_session',
dto_manana: 'dto'
};
var data2 = {
action: 'wpmc_set_session',
dto_manana: 'no'
};
if (jsArray.includes(horarioLigaValue)) {
jQuery.post(
'<?php echo admin_url('admin-ajax.php'); ?>',
data,
function(response) {
console.log(response);
//console.log('dto');
}
);
}
else {
jQuery.post(
'<?php echo admin_url('admin-ajax.php'); ?>',
data2,
function(response) {
console.log(response);
//console.log('no');
}
);
}
});
});
</script>
<?php
}
// Manejador de petición AJAX para establecer la variable de sesión
add_action( 'wp_ajax_wpmc_set_session', 'wpmc_ajax_set_session' );
add_action( 'wp_ajax_nopriv_wpmc_set_session', 'wpmc_ajax_set_session' );
function wpmc_ajax_set_session() {
error_log(print_r($_POST, true));
echo $_POST['dto_manana'];
WC()->session->set( 'dto_manana', $_POST['dto_manana'] );
wp_die();
}
add_action( 'woocommerce_review_order_before_payment', 'detectar_radio_button_seleccionado' );
function detectar_radio_button_seleccionado() {
$dto_manana = WC()->session->get('dto_manana');
if (isset($dto_manana)) {
echo $dto_manana;
}
}
add_filter('woocommerce_cart_calculate_fees', 'add_recurring_postage_fees',10,1);
function add_recurring_postage_fees( $cart ) {
$dto_manana = WC()->session->get('dto_manana');
if ( (! empty( $cart->recurring_cart_key )) && ($dto_manana == 'dto') ) {
$cart->add_fee( 'Postage', 5 );
}
}`
If I go to checkout page I get the value 'dto' or 'no' but in order review only show the value of the last session, not the actual. I need to apply add_filter('woocommerce_cart_calculate_fees', 'add_recurring_postage_fees',10,1); when I select in horario-liga any value include in the array
Related
I am trying to echo the posted value of an input field via WP ajax, but it keeps returning empty (i.e. no $_POST content), why? If I try to echo 'test', it works.
functions.php:
add_action('wp_footer', 'ajx_action_subscriber');
function ajx_action_subscriber() {
?>
<script type="text/javascript">
jQuery( document ).on( 'click', '#subscribe-submit', function() {
var subscribe_email = $('#footer-email').val();
$('#subscribe-confirmation').html('Registering');
jQuery.ajax({
url : '<?php echo esc_url( home_url() ); ?>/wp-admin/admin-ajax.php',
type : 'post',
data : {action:'subscribe_user', subscribe_email:subscribe_email},
success : function( response ) {
$('#subscribe-confirmation').html(response);
}
});
});
</script>
<?php
}
add_action('wp_ajax_subscribe_user', 'subscribe_user');
function subscribe_user() {
echo $_POST['subscribe_email'];
// echo 'test'; // works successfully ?!!?
die();
}
I have the same problem which was talked over here
I have added the code using PHP snippets plugin, but I'm not sure where to add the ajax code
I just want to add product variations on shop page with possiblity of adding to cart without reloading the page
you can also check my website over here
if you don't have access to your main script files and you can't add another files then you can add the script to WordPress Footer using wp_footer hook as follow:
add_action('wp_footer', 'myScript');
function myScript()
{
?>
<script>
jQuery(document).ready(function ($) {
"use strict";
$('.custom_add_to_cart').click(function (e) {
e.preventDefault();
var id = $(this).next().next().next().attr('value');
var data = {
product_id: id,
quantity: 1
};
$(this).parent().addClass('loading');
$.post(wc_add_to_cart_params.wc_ajax_url.toString().replace('%%endpoint%%', 'add_to_cart'), data, function (response) {
if (!response) {
return;
}
if (response.error) {
alert("Custom Massage ");
$('.custom_add_to_cart').parent().removeClass('loading');
return;
}
if (response) {
var url = woocommerce_params.wc_ajax_url;
url = url.replace("%%endpoint%%", "get_refreshed_fragments");
$.post(url, function (data, status) {
$(".woocommerce.widget_shopping_cart").html(data.fragments["div.widget_shopping_cart_content"]);
if (data.fragments) {
jQuery.each(data.fragments, function (key, value) {
jQuery(key).replaceWith(value);
});
}
jQuery("body").trigger("wc_fragments_refreshed");
});
$('.custom_add_to_cart').parent().removeClass('loading');
}
});
});
});
</script>
<?php
}
add the whole code under here into your php snippet plugin and it would work like a charm
thanks to #kacholo
/**
* Replace add to cart button in the loop.
*/
function iconic_change_loop_add_to_cart() {
remove_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart', 10 );
add_action( 'woocommerce_after_shop_loop_item', 'iconic_template_loop_add_to_cart', 10 );
}
add_action( 'init', 'iconic_change_loop_add_to_cart', 10 );
/**
* Use single add to cart button for variable products.
*/
function iconic_template_loop_add_to_cart() {
global $product;
if ( ! $product->is_type( 'variable' ) ) {
woocommerce_template_loop_add_to_cart();
return;
}
remove_action( 'woocommerce_single_variation', 'woocommerce_single_variation_add_to_cart_button', 20 );
add_action( 'woocommerce_single_variation', 'iconic_loop_variation_add_to_cart_button', 20 );
woocommerce_template_single_add_to_cart();
}
/**
* Customise variable add to cart button for loop.
*
* Remove qty selector and simplify.
*/
function iconic_loop_variation_add_to_cart_button()
{
global $product;
?>
<div class="woocommerce-variation-add-to-cart variations_button">
<button type="submit" class="custom_add_to_cart single_add_to_cart_button button"><?php echo esc_html($product->single_add_to_cart_text()); ?></button>
<input type="hidden" name="add-to-cart" value="<?php echo absint($product->get_id()); ?>" />
<input type="hidden" name="product_id" value="<?php echo absint($product->get_id()); ?>" />
<input type="hidden" name="variation_id" class="variation_id" value="0" />
</div>
<?php
}
function iconic_add_to_cart_form_action( $redirect ) {
if ( ! is_archive() ) {
return $redirect;
}
return '';
}
add_filter( 'woocommerce_add_to_cart_form_action', 'iconic_add_to_cart_form_action' );
add_action('wp_footer', 'myScript');
function myScript()
{
?>
<script>
jQuery(document).ready(function ($) {
"use strict";
$('.custom_add_to_cart').click(function (e) {
e.preventDefault();
var id = $(this).next().next().next().attr('value');
var data = {
product_id: id,
quantity: 1
};
$(this).parent().addClass('loading');
$.post(wc_add_to_cart_params.wc_ajax_url.toString().replace('%%endpoint%%', 'add_to_cart'), data, function (response) {
if (!response) {
return;
}
if (response.error) {
alert("Custom Massage ");
$('.custom_add_to_cart').parent().removeClass('loading');
return;
}
if (response) {
var url = woocommerce_params.wc_ajax_url;
url = url.replace("%%endpoint%%", "get_refreshed_fragments");
$.post(url, function (data, status) {
$(".woocommerce.widget_shopping_cart").html(data.fragments["div.widget_shopping_cart_content"]);
if (data.fragments) {
jQuery.each(data.fragments, function (key, value) {
jQuery(key).replaceWith(value);
});
}
jQuery("body").trigger("wc_fragments_refreshed");
});
$('.custom_add_to_cart').parent().removeClass('loading');
}
});
});
});
</script>
<?php
}
Here I am trying to update the MSQL table using jQuery, both PHP code and jQuery script is written on the same page, the code working fine to update my tables but the response msg is not getting by the AJAX so it always shows me the default message "Some problem occurred, please try again.".
HTML
<!-- HTML code to display msg -->
<p class="statusMsg_post"></p>
jQuery
<script>
$(document).ready(function(){
$('#btn_publish').click( function() {
var obj_post_postID="<?php echo $post_id; ?>";
var publish_post="publish";
$.ajax({
type:'POST',
// url:'post_view.php',
data:{
"post_status_update": publish_post,
"obj_post_status": obj_post_postID,
},
success:function(res) {
if (res=='ok') {
$('.statusMsg_post').html('<span style="color:green;">Post has been '+publish_post+' sucessfully</span>');
}
else {
$('.statusMsg_post').html('<span style="color:red;">Some problem occurred, please try again.</span>');
}
}
});
});
});
</script>
PHP
// my PHP code to update my table
<?php
// require_once('../../inc/db-connect.php');
if (isset($_POST['post_status_update'])) {
$temp_publish_post = $_POST['post_status_update'];
echo $bj_post_postID = $_POST['obj_post_status'];
$obj_post_status_query = "UPDATE `objection_report` SET `obj_status` = '$temp_publish_post' WHERE `objection_report`.`obj_post_id` = $bj_post_postID;";
$obj_post_status_query .= "UPDATE `post` SET `status` = '$temp_publish_post' WHERE `post`.`post_id` = $bj_post_postID ;";
if (mysqli_multi_query($con, $obj_post_status_query)) {
echo "ok";
die;
}
}
?>
all the above codes are on the same page
The script is returning the HTML and JS on the ajax call. If you put checks around the HTML it will not:
<?php if ( ! isset( $_POST['post_status_update'] ) ): ?>
<p class="statusMsg_post"></p>
<script>
$( document ).ready( function () {
$( '#btn_publish' ).click( function () {
var obj_post_postID = "<?php echo $post_id; ?>";
var publish_post = "publish";
$.ajax( {
type: 'POST',
// url:'post_view.php',
data: {
"post_status_update": publish_post,
"obj_post_status": obj_post_postID,
},
success: function ( res ) {
if ( res === 'ok' ) {
$( '.statusMsg_post' ).html( '<span style="color:green;">Post has been ' + publish_post + ' sucessfully</span>' );
} else {
$( '.statusMsg_post' ).html( '<span style="color:red;">Some problem occurred, please try again.</span>' );
}
}
} );
} );
} );
</script>
<?php endif; ?>
I create a login form using AJAX .
And this is my JQUERY code:
$("#logbtn").on("click" , function() {
if (!$("div").hasClass("error"))
{
$.ajax
({
type:'post',
url:'http://localhost/mysite/wp-content/themes/facecar/admin/inc/proccesslogin.php',
data:{
username: $("#loguser").val(),
password: $("#logpass").val()
},
success:function(response) {
console.log(response);
if (response == "yes")
{
alert("answer is yes ");
} else {
alert("answer is no !");
}
}
});
}
});
This is my PHP code:
<?php
if (strpos($_POST["username"] , "moria") >= 0)
{
echo "yes";
} else {
echo "false";
}
?>
I put the response in the console and it show my php codes and alert "answer is no !" . what is problem ?
I believe, you are using wordpress and the way you are trying ajax in wordpress is not the right way. In wordpress ajax url is admin_url( 'admin-ajax.php' ).
You'll get an idea from this link: Ajax call from front in wordpress. I hope you can do the rest following that link.
Let's make it easy for you to understand...
write in your functions.php
/* include your js script */
add_action( 'wp_enqueue_scripts', 'my_enqueue_scripts' );
function my_enqueue_scripts() {
//Change the key and url with yours
wp_register_script('my-js', get_stylesheet_directory_uri(). '/js/my-js.js', array( 'jquery' ) );
wp_enqueue_script('my-js');
//Localize script data to be used in my-js.js
$scriptData = array();
$scriptData['ajaxurl'] = admin_url( 'admin-ajax.php' );
$scriptData['action'] = 'answerAction';
wp_localize_script( 'my-js', 'my_js_data', $scriptData );
}
/* Add your server code */
add_action("wp_ajax_answerAction", "answerAction");
add_action("wp_ajax_nopriv_answerAction", "answerAction");
function answerAction(){
if (strpos($_POST["username"] , "moria") >= 0)
{
echo "yes";
} else {
echo "false";
}
die();
}
Now, add you js script in my-js.js
(function($){
$(document).ready(function(){
$('#logbtn').on('click',function(e){
e.preventDefault();
var data = {
'action': my_js_data.action,
'username': jQuery("#loguser").val(),
'password': jQuery("#logpass").val()
};
if (!$("div").hasClass("error"))
{
jQuery.post( my_js_data.ajaxurl, data, function(response) {
console.log(response);
if (response == "yes")
{
alert("answer is yes ");
} else {
alert("answer is no !");
}
});
}
});
});
})(jQuery);
Best of luck.
I would like to update and then reload my cart via AJAX when the quantity of an item in the cart is changed.
I can already successfully load in my cart via AJAX.
To load in my cart my php function looks like this. (in my functions.php)
function enqueue_cart_show_ajax() {
wp_register_script( 'cart-show-ajax-js', get_template_directory_uri() . '/js/cart-show-ajax.js', array( 'jquery' ), '', true );
wp_localize_script( 'cart-show-ajax-js', 'cart_show_ajax', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
wp_enqueue_script( 'cart-show-ajax-js' );
}
add_action('wp_enqueue_scripts', 'enqueue_cart_show_ajax');
function ajax_show_cart() {
echo do_shortcode( '[woocommerce_cart]' );
die();
}
add_action('wp_ajax_show_cart', 'ajax_show_cart');
add_action('wp_ajax_nopriv_show_cart', 'ajax_show_cart');
My Jquery code looks like this (in cart-show-ajax.js)
jQuery(function($) {
//If view-cart is clicked, fill the view-cart-popup window with the cart
$( '.view-cart' ).on('click', function(){
show_cart();
});
//Main ajax function
function show_cart() {
$.ajax({
type: 'GET',
url: cart_show_ajax.ajax_url,
data: {
action: 'show_cart',
},
beforeSend: function ()
{
//You could show a loader here
},
success: function(data)
{
//Hide loader here
$( '.view-cart-popup' ).html(data);
activateReturnToShop();
},
error: function()
{
//If an ajax error has occured, do something here...
$(".product-container").html('<p>There has been an error</p>');
}
});
}
});
The HTML for the cart is as follows
<td class="product-quantity">
<div class="quantity">
<input type="number" step="1" min="0"
name="cart[1e334311e1ef4cf849abff19e4237358][qty]"
value="4" title="Qty" class="input-text qty text" size="4">
</div>
</td>
My best guess is that I can achieve this if when the input is changed I run a function that updates the cart, then simply runs the existing show_cart() function.
I'm not sure about how to make a function that will detect the change to input, grab the new quantity of the product and update the amount in the cart...
It could looks something like:
$( 'input.qty' ).on("change", function(){
// Grab the new product quantity
// Update the cart
show_cart();
});
Anyone know how to get the new quantity update the cart with it?
Thank you for all your help!
Okay so I figured it out!
I can now update cart item's quantities without refreshing via AJAX (:
my functions.php looks like this
//Enqueue Ajax Scripts
function enqueue_cart_qty_ajax() {
wp_register_script( 'cart-qty-ajax-js', get_template_directory_uri() . '/js/cart-qty-ajax.js', array( 'jquery' ), '', true );
wp_localize_script( 'cart-qty-ajax-js', 'cart_qty_ajax', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
wp_enqueue_script( 'cart-qty-ajax-js' );
}
add_action('wp_enqueue_scripts', 'enqueue_cart_qty_ajax');
function ajax_qty_cart() {
// Set item key as the hash found in input.qty's name
$cart_item_key = $_POST['hash'];
// Get the array of values owned by the product we're updating
$threeball_product_values = WC()->cart->get_cart_item( $cart_item_key );
// Get the quantity of the item in the cart
$threeball_product_quantity = apply_filters( 'woocommerce_stock_amount_cart_item', apply_filters( 'woocommerce_stock_amount', preg_replace( "/[^0-9\.]/", '', filter_var($_POST['quantity'], FILTER_SANITIZE_NUMBER_INT)) ), $cart_item_key );
// Update cart validation
$passed_validation = apply_filters( 'woocommerce_update_cart_validation', true, $cart_item_key, $threeball_product_values, $threeball_product_quantity );
// Update the quantity of the item in the cart
if ( $passed_validation ) {
WC()->cart->set_quantity( $cart_item_key, $threeball_product_quantity, true );
}
// Refresh the page
echo do_shortcode( '[woocommerce_cart]' );
die();
}
add_action('wp_ajax_qty_cart', 'ajax_qty_cart');
add_action('wp_ajax_nopriv_qty_cart', 'ajax_qty_cart');
My cart-qty-ajax.js looks like this.
jQuery( function( $ ) {
$( document ).on( 'change', 'input.qty', function() {
var item_hash = $( this ).attr( 'name' ).replace(/cart\[([\w]+)\]\[qty\]/g, "$1");
var item_quantity = $( this ).val();
var currentVal = parseFloat(item_quantity);
function qty_cart() {
$.ajax({
type: 'POST',
url: cart_qty_ajax.ajax_url,
data: {
action: 'qty_cart',
hash: item_hash,
quantity: currentVal
},
success: function(data) {
$( '.view-cart-popup' ).html(data);
}
});
}
qty_cart();
});
});
Works beautifully, though I'm not sure if this is 'good practice'.
Thanks all!
This is a easy ways to resolve this if your are doing the scripting your selves instead of any plugin. Below code will help you to update the cart on quantity dropdown change in customize pop up window where mini cart is displaying:
javascript:
$(document).on('click', '.qty', function (e)
{
e.preventDefault();
var qty = $(this).val();
var cart_item_key = $(this).attr("id");
$.ajax({
type: 'POST',
dataType: 'json',
url: '<?php echo SITE_URL; ?>/wp-admin/admin-ajax.php',
data: {action : 'update_item_from_cart', 'cart_item_key' : cart_item_key, 'qty' : qty, },
success: function (data) {
alert('Updated successfully.');
if (data) {
alert('You missed something');
}else{
alert('Updated Successfully');
}
}
});
});
*In above script .qty is class of the number dropdown.
*Pass two values only i.e cart_item_key and quantity.
*SITE_URL is domain name
*pass two values i.e. qty and cart item key
in functions.php place the below script
function update_item_from_cart() {
$cart_item_key = $_POST['cart_item_key'];
$quantity = $_POST['qty'];
// Get mini cart
ob_start();
foreach (WC()->cart->get_cart() as $cart_item_key => $cart_item)
{
if( $cart_item_key == $_POST['cart_item_key'] )
{
WC()->cart->set_quantity( $cart_item_key, $quantity, $refresh_totals = true );
}
}
WC()->cart->calculate_totals();
WC()->cart->maybe_set_cart_cookies();
return true;
}
add_action('wp_ajax_update_item_from_cart', 'update_item_from_cart');
add_action('wp_ajax_nopriv_update_item_from_cart', 'update_item_from_cart');