Passing ajax variable to more than one wordpress plugin function - php

I'm trying to get information from the front end of my Wordpress site, I used ajax to do that, it gave me the ability to use the data in one of my plugin functions, but in my case I want to use this data in more than just one function.
add_action( 'admin_footer', 'my_action_javascript' );
function my_action_javascript() { ?>
<script type="text/javascript" >
jQuery(document).ready(function($) {
var data = {
'action': 'my_action',
'whatever': 1234
};
jQuery.post(ajaxurl, data);
});
</script> <?php
}
add_action( 'wp_ajax_my_action', 'my_action' );
function my_action() {
$whatever = $_POST['whatever'];
}
In other words I need to use $_POST['whatever'] in other functions in my plugin not only my_action() function, I tried using PHP global variables like so , but it didn't workout:
$whatever;
function my_action(){
global $whatever = $_POST['whatever'];
}
function my_other_function(){
global $whatever;
if(isset($whatever)){
echo $whatever;
}
}

Related

WP functions undefined in plugin

I am having trouble with a plugin I am writing, the plugin shows a form and the form submits to ajaxupload.php.
Basically in my plugin file:
add_action('plugins_loaded','add_to_menu');
function add_to_menu(){
add_action('admin_menu', 'test_plugin_setup_menu');
}
function test_plugin_setup_menu(){
add_menu_page( 'Test Plugin Page', 'add new entry', 'manage_options', 'test-plugin-link', 'test_init' );
// ,'dashicons-database-add'
}
function test_init(){
//echo "<h1>Hello World!</h1>";
// do_action( 'admin_init' );
include(ABSPATH."/wp-content/plugins/my-plugin/form.php");
}
In form.php I can call wp functions!
<?php
// this works!
echo wp_get_current_user()->user_login;
?>
<form>
...
</form>
<script>
$(document).ready(function(){
$("#my_form").on("submit",function(e){
e.preventDefault();
var sendData = $( this ).serialize();
$.ajax({
url: "../wp-content/plugins/my-plugin/ajaxupload.php",
type: "POST",
data: new FormData(this),
...
</script>
in Ajaxupload.php I can't use any WP constants or functions before submission...
if( !empty($_POST['imgurl']) || !empty($_FILES['image']) )
{
$someform_field = $_POST["name"];
echo wp_get_current_user()->user_login; //this line fails
//then call to wpdb to add data to DB
What should be the correct sequence to make wp functions usable in the ajaxupload.php file?
You have to load the wp-load.php file in your ajaxload.php, which loads all wordpress functions, because your ajaxload.php file is called directly:
<?php
require_once __DIR__ . '/../../../wp-load.php';
$someform_field = $_POST["name"];
$user = wp_get_current_user()->user_login; // should now work
//then call to wpdb to add data to DB

wocommerce calculate shipping not being called

Hi have a wocommerce plugin, While changing the payment method. the cost for shipping my function calculate_shipping is not being called. and therefore shipping methods are not updating with appropriate cost
here are some samples from my code.
public function __construct() {
add_action('woocommerce_review_order_before_payment', array($this, 'update_shipping_charges'), 1);
}
public function update_shipping_charges() {
// jQuery code
?>
<script type="text/javascript">
(function ($) {
$('form.checkout').on('change', 'input[name^="payment_method"]', function () {
// Set the select value in a variable
$('body').trigger('update_checkout');
//testing
$('body').on('updated_checkout', function() {
console.log('updated');
});
});
})(jQuery);
</script>
<?php
}
Try wrapping everything inside the init hook. Maybe the code gets executed too early:
public function __construct() {
add_action( 'init', [ $this, 'init_action' ] );
}
public function init_action(): void {
add_action( 'woocommerce_review_order_before_payment', [ $this, 'update_shipping_charges' ], 1 );
}
public function update_shipping_charges(): void {
// jQuery code
?>
<script type="text/javascript">
(function ( $ ) {
$( 'form.checkout' ).on( 'change', 'input[name^="payment_method"]', function () {
// Set the select value in a variable
let body = $( 'body' );
body.trigger( 'update_checkout' );
//testing
body.on( 'updated_checkout', function () {
console.log( 'updated' );
} );
} );
})( jQuery );
</script>
<?php
}
You could try multiple hooks if init don't works:
woocommerce_loaded
woocommerce_init
plugins_loaded <- I use this one in my plugins for example
Please try the following (Add to functions.php or via Code Snippets plugin)
function kia_checkout_on_payment_change() {
wp_add_inline_script( 'wc-checkout', '
jQuery( document.body ).on( "payment_method_selected", function() {
jQuery( "form.checkout" ).trigger( "update_checkout", { update_shipping_method: true } );
console.log("payment selected");
} );
'
);
}
add_action( 'wp_enqueue_scripts', 'kia_checkout_on_payment_change' );
A couple notes....
We're adding the script right after the wc-checkout script is loaded.
We're listening for the WooCommerce checkout script's payment_method_selected (but yes, it's a core Woo trigger in the checkout) trigger which should fire when the payment method is changed
We're explicitly passing some arguments to the update_checkout function.
Don't have any shipping methods set up locally to test it properly, but I hope it points you in the right direction.

Clear WooCommerce cart on Currency Switcher change

I'm using the currency switcher WordPress plugin to change currencies on my website, I want the cart to be cleared once I change the currency. I've been trying for some time now, but can't figure out why it isn't working.
This is my source code in the theme functions.php file
function currency_change_action_callback() {
global $woocommerce;
$url_data=$_POST['url_data'];
$woocommerce->cart->empty_cart();
echo $url_data;
die();
}
add_action( 'wp_ajax_currency_change_action', 'currency_change_action_callback' );
add_action( 'wp_ajax_nopriv_currency_change_action', 'currency_change_action_callback' );
I've also tried creating a javascript file and calling it to my functions.php file. here are my source codes
app.js
$('#alg_currency_select').on('change', function () {
function Clearcart(d){
jQuery.post(
"http://localhost/epay/wp-admin/admin-ajax.php",
//ajaxurl,
{
"action": "clearcart",
"data": d.getAttribute("data-product")
},
function(){
window.location = d.getAttribute("data-href");
}
);
})};
functions.php
function load_javascript() {
wp_register_script('custom', get_template_directory_uri().'/app.js', 'jquery', 1, true);
wp_enqueue_script('custom');
}
add_action('wp_enqueue_scripts', 'load_javascript');
would greatly appreciate it if someone can help me solve the issue of why my cart isn't clearing. thanks.
There are some mistakes in your code and unnecessary things.
In the code below, the jQuery code is now located in a php function and enqueued in WordPress using the WooCommerce wc_enqueue_js() function.
// The jQuery Ajax enqueued code
add_action('template_redirect', 'currency_change_trigger_clear_cart_js' );
function currency_change_trigger_clear_cart_js() {
wc_enqueue_js( "jQuery( function($){
$(document.body).on('change', '#alg_currency_select', function() {
$.ajax({
url: '" . admin_url('/admin-ajax.php') . "',
type: 'POST',
data: {
'action': 'currency_change_clear_cart'
},
success: function(response) {
if( response == 'cleared' ) {
$(document.body).trigger('wc_fragment_refresh'); // Refresh cart
}
// console.log(response);
}
});
});
});" );
}
// Php AJAX receiver: Empty cart
add_action( 'wp_ajax_currency_change_clear_cart', 'currency_change_clear_cart' );
add_action( 'wp_ajax_nopriv_currency_change_clear_cart', 'currency_change_clear_cart' );
function currency_change_clear_cart() {
if( count(WC()->cart->get_cart()) > 0 ) {
WC()->cart->empty_cart();
echo 'cleared';
}
die();
}
Code goes in functions.php file of the active child theme (or active theme). Tested and works.

Access WC() to get cart content in ajax callback

I'm trying to get woocommerce cart content in ajax callback function but it returns empty.
I've also tried using global $woocommerce variable that also returns the same result. I'm trying to get the cart content and convert all product to autoship feature. I'm using wooautoship plugin for that. however, main query is, how to get the cart details in ajax callback.
My Code is as follow:
add_action('wp_footer', 'woo_cart_autoship_js', 99);
function woo_cart_autoship_js(){
?>
<script type="text/javascript">
(function($){
$(document).on('click', '#convert-to-autoship', function(e){
e.preventDefault();
$.post( "<?php echo admin_url('admin-ajax.php'); ?>", { action: "convert-to-autoship" })
.done(function( data ) {
alert( "Data Loaded: " + data );
});
});
})(jQuery);
</script>
<?php
}
add_action( 'wp_ajax_convert-to-autoship', 'convert_to_autoship', 99 );
add_action( 'wp_ajax_nopriv_convert-to-autoship', 'convert_to_autoship', 99 );
function convert_to_autoship(){
print_r(WC()->cart->get_cart());
wp_die();
}

How to get wp_ajax to work with jQuery $.post

Straight from WP Codex: http://codex.wordpress.org/AJAX_in_Plugins
I have this in my functions.php:
add_action( 'admin_footer', 'my_action_javascript' );
function my_action_javascript() {
?>
<script type="text/javascript" >
jQuery(document).ready(function($) {
var data = {
'action': 'my_action',
'whatever': 1234
};
// since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
$.post(ajaxurl, data, function(response) {
alert('Got this from the server: ' + response);
});
});
</script>
<?php
}
add_action( 'wp_ajax_my_action', 'my_action_callback' );
function my_action_callback() {
global $wpdb; // this is how you get access to the database
$whatever = intval( $_POST['whatever'] );
$whatever += 10;
echo $whatever;
die(); // this is required to return a proper result
}
And I don't get a response. I do get an alert saying 'Got this from the server: ', but no response. What gives?
Running your code on two separate wordpress installs from within a plugin file (plugin-name.php) and from within functions.php in my theme, it returns the proper value both times. There do not seem to be any errors in your code either.
Is this the only javascript you're including in the admin area?

Categories