This question already has answers here:
How to get JavaScript variable value in PHP
(10 answers)
Closed 5 years ago.
So I am helping my friend with his woocommerce WordPress site. He has some short javascript code that needs to be added to the thank you page for the site.
The javascript code takes three variables (totalCost, orderId and setProductId). I can not get to the HTML. So how do I add this code to the PHP and also, how do I access the variables from the PHP and write them into the javascript?
And where in the already existing code should I add it? Is it in the functions.php file for the theme?
I would be super thankful for help!
EDIT:
So would this work?
add_action( 'studentkortet_tracking', 'my_custom_tracking' );
function studentkortet_tracking($order_id){
?>
<script id="pap_x2s6df8d" src="http://URL_TO_PostAffiliatePro/scripts/trackjs.js" type="text/javascript">
</script>
<script type="text/javascript">
PostAffTracker.setAccountId(’xxxxxx’);
var sale = PostAffTracker.createSale();
sale.setTotalCost('<?php echo ($order->order_total - $order->order_shipping); ?>');
sale.setOrderID('<?php echo $order->id; ?>');
sale.setCurrency('<?php echo $order->get_order_currency(); ?>');
PostAffTracker.register();
</script>
<?php
}
Here is some working code, answered here
<script>
var p1 = "success";
</script>
<?php
echo "<script>document.writeln(p1);</script>";
?>
Here's the correct way of accessing PHP variables within a script. It utilises the function wp_localize_script() so that PHP variables are accessible in a script file. First include this file in your functions.php file
function example_enqueue_scripts() {
if( is_checkout() ) {
$args = array( 'total_cost' => 443, 'order_id' => 4567, 'set_product_id' => 123 );
wp_register_script( 'checkout-script', get_stylesheet_directory_uri() . '/checkout-script.js' );
wp_localize_script( 'checkout-script', 'checkout_script', $args );
wp_enqueue_script( 'checkout-script' );
}
}
add_action( 'wp_enqueue_scripts', 'example_enqueue_scripts' );
Then include this javascript in a file under your theme folder called checkout-script.js for example.
(function( $ ) {
'use strict';
$(function() {
var totalCost = checkout_script.total_cost;
var orderId = checkout_script.order_id;
var setProductId = checkout_script.set_product_id;
exampleFunction( totalCost, orderId, setProductId );
function exampleFunction( totalCost, orderId, setProductId ) {
//Do something in here
//alert(totalCost);
}
});
})( jQuery );
I don't know what setProductId is meant to be as a variable, but the hook you are looking for is woocommerce_thankyou. The $order_id is passed by default, which you can then use to grab the order object. Pretty much all the info related to the order can be accessed through the setter/getter methods on the order object.
/**
* Print Javascript on Thankyou page.
* #param int $order_id
*/
function so_47117329_thankyou( $order_id ){
$order = wc_get_order( $order_id ); ?>
<script id="pap_x2s6df8d" src="http://URL_TO_PostAffiliatePro/scripts/trackjs.js" type="text/javascript">
</script>
<script type="text/javascript">
PostAffTracker.setAccountId(’xxxxxx’);
var sale = PostAffTracker.createSale();
sale.setTotalCost('<?php echo $order->get_total() - $order->get_shipping_
(); ?>');
sale.setOrderID('<?php echo $order_id; ?>');
sale.setCurrency('<?php echo $order->get_order_currency(); ?>');
PostAffTracker.register();
</script>
<?php
}
add_action( 'woocommerce_thankyou', 'so_47117329_thankyou' );
Editing to add an alternative for enqueuing the scripts as suggested by #Andrew-Schultz. Using the woocommerce_thankyou hook gets you easy access to the $order_id, which would otherwise need to be retrieved from the URL. You will still access the javascript variables as he's shown in his answer.
/**
* Enqueue Javascript on Thankyou page.
* #param int $order_id
*/
function so_47117329_thankyou( $order_id ){
$order = wc_get_order( $order_id );
$args = array(
'total_cost' => $order->get_total(),
'order_id' => $order_id,
'set_product_id' => 123
);
wp_register_script( 'checkout-script', get_stylesheet_directory_uri() . '/checkout-script.js', array(), false, true ); // Last parameter loads script in footer
wp_localize_script( 'checkout-script', 'checkout_script', $args );
wp_enqueue_script( 'checkout-script' );
}
add_action( 'woocommerce_thankyou', 'so_47117329_thankyou' );
Related
I'm trying to make some SQL queries using PHP in Wordpress, to auto populate and check values on a gravity form against the existing database.
To do that however, I'm going to need to pass some javascript variables to php, then use that to interact and pull that data back to the form. As someone with minimal web dev background, easier said then done.
My main issue is with an AJAX call that properly carries over a value, but only to the action function. All other calls will show null (I assume due to scoping, but globals don't seem to help).
The main relevant PHP is in a custom plugin as follows:
$address = 0;
function my_enqueue() {
wp_register_script( 'lead-scheduler', null);
wp_enqueue_script( 'lead-scheduler', plugins_url( '/lead_ajax.js', __FILE__ ), array('jquery') );
wp_localize_script( 'lead-scheduler', 'leadajax', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
wp_enqueue_script( 'jquery' );
wp_register_script( 'lead_ajax', null);
wp_enqueue_script( 'lead_ajax' );
}
add_action( 'init', 'my_enqueue' );
function handle_request(){
//Check post address, then apply to global variable
echo $_POST['address'] . "\n";
global $address;
$address = $_POST['address'];
echo $address . "\n";
wp_die("RIP");
}
add_action( 'wp_ajax_handle_request', 'handle_request' );
add_action( 'wp_ajax_nopriv_handle_request', 'handle_request' );
function functionCaller() {
if (is_page ('')) {
?>
<script type="text/javascript">
jQuery(document).ready(function ($) {
$(function(){
var addressField = document.getElementById('input_22_2');
var temp;
//Set up event listener
addressField.onchange = addressCheck;
function addressCheck(){
//Get foreign script
$.getScript("/wp-content/plugins/lead-scheduler/lead_ajax.js", function(){
//Wait until done to execute console.log
$.when(adrCheck()).done(function(){
console.log("Logging: " + "<?php global $address; echo $address ?>");
});
});
}
});
});
</script>
<?php
}
}
add_action('wp_head', 'functionCaller'); ?>
The AJAX call comes from a JS file that I call to:
//AJAX
function adrCheck(){
jQuery(document).ready( function() {
console.log("called")
var addressField = document.getElementById('input_22_2').value;
jQuery.ajax({
type : "post",
url : leadajax.ajax_url,
data : {action: "handle_request", address: addressField},
success: function(response) {
console.log(response)
},error: function(response){
console.log(response);
}
})
})
}
The call seems to work, as the echo in handle_request() works fine. But calling that variable anywhere else returns null. $.when.done doesn't seem to do much, nor does anything synchronous.
I'm sure there's something super elementary that I'm missing, but I can't seem to find it.
I have the following code which works. (When I press the button "test" is displayed on the input form.
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-
core/6.1.19/browser.min.js"></script>
<script>
function btn1() {
document.getElementsByName("admin-status")[0].value = "test";
}
</script>
I want to retrieve the username, so I thought I added it correctly, but it says not defined.
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-
core/6.1.19/browser.min.js"></script>
<script>
global $current_user;
$current_user = wp_get_current_user();
function btn1() {
document.getElementsByName("admin-status")[0].value = $current_user;
}
</script>
What am I missing? Thanks. Noob here.
The better way to add localize script
add_action( 'wp_enqueue_scripts', 'wp12311_enqueue_scripts' );
function wp12311_enqueue_scripts() {
wp_enqueue_script( 'wp12311-scripts', 'your_script_path/test.js', array( 'jquery' ), false, true );
wp_localize_script( 'wp12311-scripts', 'test', array(
'current_user' => wp_get_current_user()
) ) );
}
Now in test.js file you can access current user data like
var displayName = test.current_user.display_name;
You'll probably see a " is undefined" in js console and/or other errors. Note that you forgot the php <?php and ?> around the php code, and the $current_user would be "<?php echo $current_user ?>
If you are doing anything more than one line script you really should enqueue script and then localize script to a variable you can use in js on the page anywhere, not mix php and js!
On my wordpress page, I have the following loop, which successfully outputs an attachment's caption.
<?php
$the_query = new WP_Query(array( 'post_type' => 'attachment'));
while ( $the_query->have_posts() ) : $the_query->the_post();
$attachment_data = wp_prepare_attachment_for_js();
echo '<h2>'.$attachment_data['caption'].'</h2>'
;?>
Now, I also need to call the attachment caption outside of the loop. This is what I'm trying in functions.php:
function custom_info()
{
global $wp_query;
$query_id = $wp_query->post->ID;
$attachment_data_query = wp_prepare_attachment_for_js( $query_id );
wp_register_script( 'custom_data_info');
$info = array(
'data_query' => $attachment_data_query['caption']
);
wp_enqueue_script( 'custom_data_info' );
wp_localize_script('custom_data_info', 'info', $info);
}
if ( !is_admin() ) add_action( "wp_enqueue_scripts", "custom_info", 10 );
And then it would be called in the external javascript file like so:
return info.data_query
I know the custom_info function and javascript file are talking with each other correctly. The problem is with how I am defining $query_id
EDIT: Almost fixed. The problem was that I didn't include a foreach statement, and so the first item in the loop was being repeated over and over again.
I've adjusted below, but for some reason, now the array is empty upon output of info.data_query...
function custom_info(){
global $wp_query;
wp_register_script( 'custom_data_info');
$info = array('data_query' => array());
foreach ( $wp_query->posts as $query_id) {
$attachment_data_query = wp_prepare_attachment_for_js( $query_id );
$info['data_query'][$query_id] = $attachment_data_query['caption'];
}
Are you sure $wp_query will return the correct post ID? In my experience, it's better to use global $post instead. Pass that into wp_prepare_attachment_js() instead:
global $post;
$post_id = $post->ID;
$attachment_data_query = wp_prepare_attachment_for_js( $post_id );
Can somebody help me? I'm feeling so stupid. I took example code from WordPress codex, made a example plugin in my webpage, but there no respond...
PHP code is here:
/**
* Plugin Name: Ada Ajax Test
* Description: WP Codex based ajax example
* Version: 1.0.0
* Author: M. A. Tomas
* Author URI: http://www.matomas.cz
* License: GPL2
*/
add_action( 'admin_enqueue_scripts', 'my_enqueue' );
function my_enqueue($hook) {
if( 'index.php' != $hook ) {
// Only applies to dashboard panel
return;
}
wp_enqueue_script( 'ajax-script', plugins_url( '/js/my_query.js', __FILE__ ), array('jquery') );
// in JavaScript, object properties are accessed as ajax_object.ajax_url, ajax_object.we_value
wp_localize_script( 'ajax-script', 'ajax_object',
array( 'ajax_url' => admin_url( 'admin-ajax.php' ), 'we_value' => 1234 ) );
}
// Same handler function...
add_action( 'wp_ajax_my_action', 'my_action_callback' );
function my_action_callback() {
global $wpdb;
$whatever = intval( $_POST['whatever'] );
$whatever += 10;
return $whatever;
wp_die();
}
// shortcode pro zobrazeni na strance
add_shortcode( 'ajax-zkouska', 'my_action_callback' );
and Javascript code in external file is here:
// JavaScript Document
jQuery(document).ready(function($) {
var data = {
'action': 'my_action',
'whatever': ajax_object.we_value // We pass php values differently!
};
// We can also pass the url value separately from ajaxurl for front end AJAX implementations
jQuery.post(ajax_object.ajax_url, data, function(response) {
alert('Got this from the server: ' + response);
});
});
Where I mistake?
You have a few things mixed up.
Front End
If you are targeting the frontend, then you need to use this hook:
add_action( 'wp_enqueue_scripts', 'my_enqueue' );
This allows you to add the needed scripts to the front end and not the admin side.
Ajax Calls
All ajax calls are executed within the admin context. So you will need to test for it and add the ajax hooks accordingly.
if ( is_admin() ) {
add_action( 'wp_ajax_my_frontend_action', 'my_frontend_action_callback' );
add_action( 'wp_ajax_nopriv_my_frontend_action', 'my_frontend_action_callback' );
add_action( 'wp_ajax_my_backend_action', 'my_backend_action_callback' );
// Add other back-end action hooks here
} else {
// Add non-Ajax front-end action hooks here
}
No Priv
The no_priv hook is meant for users that are not logged in. Add it if that's your intention.
Not sure to post here or webmasters, I apologize if I got wrong.
Does anyone know of a way to execute a short code on a image click?
I can not find anything on how to do this
Edit: My apologizes
Yes Shortcode means wordpress shortcode
==== Template page ====
<script>
function executeShortCode() {
var url="<?php echo get_template_directory_uri(); ?>/yourAjaxPage.php";
jQuery.post(url,function(data){
console.log(data);
});
}
</script>
==== Ajax page ====
//yourAjaxPage.php
<?php echo do_shortcode('[yourshortcode]'); ?>
Because I just couldn't find answers online to my own question on this, I thought I'd post my solution. Using wp_localize_script to load my shortcodes, here is my example:
// PHP (in functions.php)
<?php
add_action( 'wp_enqueue_scripts', 'custom_add_scripts' );
function custom_add_scripts() {
wp_register_script( 'my_new_js_callname', plugins_url( '/js/filename.js' , __FILE__ ), array(), '1.0.0', true );
wp_enqueue_script( 'my_new_js_callname' );
}
add_action ('template_hook', 'custom_function_name');
function custom_function_name() {
// Because I used if/else statements in my JS, I loaded individual IDs into the array.
$examplea = do_shortcode('[add_to_cart id="118"]');
$exampleb = do_shortcode('[add_to_cart id="119"]');
$examplec = do_shortcode('[add_to_cart id="120"]');
$array = array(
'examplea' => $examplea,
'exampleb' => $exampleb,
'examplec' => $examplec,
);
wp_localize_script( 'my_new_js_callname', 'callword', $array );
Then, on image click or any other JS event you are using do:
// JS (in filename.js)
<script>
document.getElementById('myImg').onclick = function (){
$("#show").html( callword.examplea );
}
</script>
Then the shortcode is executed on my HTML page in there area where I have:
<div id="show"></div>
Get image element by it's id and attach the handler at onclick event something like
html
<img id="myImg" src="" />
JS
<script>
document.getElementById('myImg').onclick = function (){
//execute your short code here.
}
</script>