wordpress passing variable to javascript - javascript

I'm trying to pass a variable to a javascript file from a plugin. Here is my plugin code:
<?php
/**
* #package JS Test
* #version 1.0
*/
/*
Plugin Name: JS Test
Description: JS Test.
*/
add_action('init', 'my_init');
add_action( 'wp', 'test_js' );
function my_init() {
wp_enqueue_script( 'jquery' );
}
function test_js() {
wp_register_script ('testjs', plugins_url('jstest.js', __FILE__));
wp_enqueue_script ('testjs');
$my_arr = array('my array',
'name' => 'Test',
);
$my_json_str = json_encode($my_arr);
$params = array(
'my_arr' => $my_json_str,
);
wp_enqueue_script('my-java-script');
wp_localize_script('my-java-script', 'php_params', $params);
}
Here is the jstest.js file:
jQuery(document).ready(function() {
alert ('test');
var my_json_str = php_params.my_arr.replace(/"/g, '"');
var my_php_arr = jQuery.parseJSON(my_json_str);
alert(php_params);
});
What I get is this error in JavaScript:
ReferenceError: php_params is not defined
Anybody see what I'm doing wrong?

You Don't need to enqueue a script just for your localized parameters you can use your testjs for that, here is a quick plugin i cooked up to test:
<?php
/*
Plugin Name: PHP to JS
Plugin URI: http://en.bainternet.info
Description: wordpress passing variable to javascript
http://stackoverflow.com/questions/12761904/wordpress-passing-variable-to-javascript
Version: 1.0
Author: Bainternet
Author URI: http://en.bainternet.info
*/
add_action('init', 'my_init');
add_action( 'wp', 'test_js' );
function my_init() {
/wp_enqueue_script( 'jquery' );
}
function test_js() {
wp_register_script ('testjs', plugins_url('jstest.js', __FILE__));
wp_enqueue_script ('testjs');
$my_arr = array('my array',
'name' => 'Test',
);
$my_json_str = json_encode($my_arr);
$params = array(
'my_arr' => $my_json_str,
);
wp_localize_script('testjs', 'php_params', $params);
}
add_action('wp_footer','footertestjs');
function footertestjs(){
?>
<script>
jQuery(document).ready(function() {
alert ('test');
var my_json_str = php_params.my_arr.replace(/"/g, '"');
var my_php_arr = jQuery.parseJSON(my_json_str);
alert(php_params);
});
</script>
<?php
}
as you can see here the wp_localized_script uses the same script as you enqueue and not a fake script.

Related

Accessing query of query loop block from another block, gutenberg wordpress

I'm creating a custom block inside a plugin. It's a drop down selector of categories for posts. I'm simply trying to update the query of a query loop block on the same page. However I'm not sure how to access the query of the query loop block.
I've tried the above however getting the blockId of the block doesn't seem to be possible on the front end. Does anyone know how i can reference the query loop block from a front end js file?
plugin.php
function tapacode_selector_ajax_callback() {
$nonce = $_POST['nonce'];
if ( ! wp_verify_nonce( $nonce, 'wp-tapacode-nonce' ) ) {
die ( 'Busted!' );
}
$category = intval( $_POST['category']);
$query_args = array(
'cat' => $category
);
$query = new WP_Query( $query_args );
wp_send_json( $query->posts );
wp_die();
}
add_action( 'wp_ajax_tapacode_selector', 'tapacode_selector_ajax_callback' );
add_action( 'wp_ajax_nopriv_tapacode_selector', 'tapacode_selector_ajax_callback' );
add_action( 'wp_enqueue_scripts', 'my_enqueue' );
function my_enqueue() {
wp_register_script( 'ajax-selector-script', plugins_url( '/selector.js', __FILE__ ), array( 'wp-blocks', 'wp-editor', 'wp-element', 'jquery' ), '1.0', true );
wp_enqueue_script( 'ajax-selector-script' );
// in JavaScript, object properties are accessed as ajax_object.ajax_url, ajax_object.we_value
wp_localize_script( 'ajax-selector-script', 'ajax_object',
array(
'ajax_url' => admin_url( 'admin-ajax.php' ),
'nonce' => wp_create_nonce( 'wp-tapacode-nonce' )
) );
}
another plugin.php file
<p <?php echo get_block_wrapper_attributes(); ?>>
<?php wp_dropdown_categories(); ?>
</p>
selector.js
document.addEventListener('DOMContentLoaded', setupCategorySelector, false);
function setupCategorySelector() {
document.getElementById('cat').onchange = function () {
// if value is category id
if (this.value !== '-1') {
if (typeof wp !== 'undefined' && wp.data) {
const blockId = document.querySelector('.wp-block-tapacode-category-selector').getAttribute('data-block-id');
const queryBlock = wp.data.select('core/block-editor').getBlock(blockId);
queryBlock.setAttributes({ categories: this.value });
queryBlock.update();
}

My js effects are not working on Elementor edit page. How can I solve the problem?

I'm developing an elementor widget as a plugin. The font view js working fine but the backend (Elementor edit page) js are not working. I'm using hooks (admin_enqueue-scripts, wp_enqueue_scripts, elementor/editor/before_enqueue_scripts, elementor/elements/categories_registered, elementor/widgets/widgets_registered, elementor/editor/after_enqueue_scripts, elementor/frontend/init). Which is perfect the js loading for elementor font page. Now, My js effects are not working on Elementor edit page. How can I solve the problem?
The enqueue code:- `public function bwdic_admin_editor_scripts() {
add_filter( 'script_loader_tag', [ $this, 'bwdic_admin_editor_scripts_as_a_module' ], 10, 2 );
}
public function bwdic_admin_editor_scripts_as_a_module( $tag, $handle ) {
if ( 'bwdic_the_compare_editor' === $handle ) {
$tag = str_replace( '<script', '<script type="module"', $tag );
}
return $tag;
}
private function include_widgets_files() {
require_once( __DIR__ . '/widgets/bwdic-compare.php' );
}
public function bwdic_register_widgets() {
// Its is now safe to include Widgets files
$this->include_widgets_files();
// Register Widgets
\Elementor\Plugin::instance()->widgets_manager->register_widget_type( new Widgets\BWDMEcompare() );
}
private function add_page_settings_controls() {
require_once( __DIR__ . '/page-settings/image-compare-manager.php' );
new Page_Settings();
}
// Register Category
function bwdic_add_elementor_widget_categories( $elements_manager ) {
$elements_manager->add_category(
'bwd-image-compare-category',
[
'title' => esc_html__( 'BWD Image Compare', 'bwd-image-compare' ),
'icon' => 'eicon-person',
]
);
}
public function bwdic_all_assets_for_the_public(){
wp_enqueue_script( 'bwdic_compare_the_main_js', plugin_dir_url( __FILE__ ) . 'assets/public/js/custom.js', array('jquery'), '1.0', true );
$all_css_js_file = array(
'bwdic_compare_main_css' => array('bwdic_path_define'=>BWDIC_ASFSK_ASSETS_PUBLIC_DIR_FILE . '/css/style.css'),
);
foreach($all_css_js_file as $handle => $fileinfo){
wp_enqueue_style( $handle, $fileinfo['bwdic_path_define'], null, '1.0', 'all');
}
}
public function bwdic_all_assets_for_elementor_editor_admin(){
wp_enqueue_script( 'bwdic_compare_the_main_js_admin', plugin_dir_url( __FILE__ ) . 'assets/public/js/custom.js', array('jquery'), '1.0', true );
$all_css_js_file = array(
'bwdic_compare_admin_icon_css' => array('bwdic_path_admin_define'=>BWDIC_ASFSK_ASSETS_ADMIN_DIR_FILE . '/icon.css'),
);
foreach($all_css_js_file as $handle => $fileinfo){
wp_enqueue_style( $handle, $fileinfo['bwdic_path_admin_define'], null, '1.0', 'all');
}
}
public function __construct() {
// For public assets
add_action('wp_enqueue_scripts', [$this, 'bwdic_all_assets_for_the_public']);
// For Elementor Editor
add_action('elementor/editor/before_enqueue_scripts', [$this, 'bwdic_all_assets_for_elementor_editor_admin']);
// Register Category
add_action( 'elementor/elements/categories_registered', [ $this, 'bwdic_add_elementor_widget_categories' ] );
// Register widgets
add_action( 'elementor/widgets/widgets_registered', [ $this, 'bwdic_register_widgets' ] );
// Register editor scripts
add_action( 'elementor/editor/after_enqueue_scripts', [ $this, 'bwdic_admin_editor_scripts' ] );
$this->add_page_settings_controls();
}`

How to pass PHP values to js script in Wordpress using AJAX

I have tried both wp_localize_script and wp_add_inline_script : it doesn't work the way I expect.
I have this in my plugin's PHP file (it is enqueued with wp_enqueue_scripts somewhere else but I don't need to write the code here right ?) :
wp_register_script(
'custom-profile-script',
"{$this->plugin_url}js/custom-profile-plugin.js",
array( 'jquery' ),
null,
false
);
wp_enqueue_script(
'custom-profile-script'
);
wp_localize_script(
'custom-profile-plugin',
'wp_ajax',
array(
'ajax_url' => admin_url( 'admin-ajax.php' ),
'ajaxnonce' => wp_create_nonce( 'ajax_post_validation' ),
'plugin_url' => "url"
)
);
wp_add_inline_script( 'custom-profile-plugin', 'const PHPVAR = ' . json_encode( array(
'plugin_url' => "url"
) ), 'before' );
And then, in my js file :
var data = {
action: 'custom_user_plugin_update_meta_rating_value',
security: wp_ajax.ajaxnonce
};
$.post(wp_ajax.ajax_url, data, function(result) {
console.log(wp_ajax);
console.log(PHPVAR.plugin_url);
});
The first console log (related to wp_localize_script) is an object that contains "ajax_url" and "ajax_nonce" with the right values, but "plugin_url" doesn't appear and is UNDEFINED when I call it using wp_ajax.plugin_url.
The second console log (related to wp_add_inline_script) tells me that PHPVAR is not defined...
What I don't understand is why the first two values are passed correctly using localize script, but not the third one and, furthermore, why wp_add_inline_script doesn't work.
The script needs to be registered in the footer for the PHP value to be passed, like this :
wp_register_script(
'custom-profile-script',
"{$this->plugin_url}js/custom-profile-plugin.js",
array( 'jquery' ),
null,
true // register script in the footer
);
Instead of :
wp_register_script(
'custom-profile-script',
"{$this->plugin_url}js/custom-profile-plugin.js",
array( 'jquery' ),
null,
false // default value of the wp_register_script function that registers script in header
);
You need to add wp_enqueue_script after wp_localize_script and also you add wrong handle to wp_localize_script check the below code.
wp_register_script(
'custom-profile-script',
"{$this->plugin_url}js/custom-profile-plugin.js",
array( 'jquery' ),
null,
true
);
wp_localize_script(
'custom-profile-script',
'wp_ajax',
array(
'ajax_url' => admin_url( 'admin-ajax.php' ),
'ajaxnonce' => wp_create_nonce( 'ajax_post_validation' ),
'plugin_url' => "url"
)
);
wp_enqueue_script(
'custom-profile-script'
);
var data = {
action: 'custom_user_plugin_update_meta_rating_value',
security: wp_ajax.ajaxnonce
};
$.post(wp_ajax.ajax_url, data, function(result) {
console.log(wp_ajax);
console.log(wp_ajax.plugin_url);
});

WP wp_ajax_function is not calling PHP function

I'm building a wordpress plugin for a cookie notice, i want the cookies to be created with PHP. And the button in the notice bar is supposed to run a php function, ajax is not really working with me right now.
My ajax request is being processed as far as i know, in the network tab it shows admin-ajax.php with status 200, but it just won't call the actual function.
this is my code
Main plugin file
function setAjaxCallbacks(){
add_action('wp_ajax_accepted', 'accepted');
add_action('wp_ajax_nopriv_accepted', 'accepted');
}
add_action('init', 'setAjaxCallbacks');
function accepted(){
die('test');
echo 'LOLALLES';
global $wpdb;
$whatever = intval( $_POST['whatever'] );
$whatever += 10;
echo $whatever;
wp_die('0 ', 400);
echo '<script>
alert("jhwgvbht ij")
</script>';
wp_die();
}
isset($_COOKIE['cookieBar']) or setCookieBar();
function setCookieBar()
{
if (!is_admin()){
add_action('wp_enqueue_scripts', 'enqueue_script_custom');
function enqueue_script_custom()
{
wp_enqueue_style('CookieBarStyle', plugin_dir_url(__FILE__) . 'css/styles.css');
wp_enqueue_script('ajax-script', plugins_url('/js/my_query.js', __FILE__), array('jquery'));
wp_localize_script('ajax-script', 'ajax_object',
array('ajaxurl2' => 'https://wordpressjip.jmulder.dt2/wp-admin/admin-ajax.php', 'we_value' => 1234));
wp_print_scripts('ajax-script');
}
?>
<div class="cookieBar" id="cookieBar" style="display: block">
<p align="center"></p>
<button id="submitCookies" class="submitCookies" name="accepted">Accepteer</button>
</div>
<?php
}
}
my_query.js
jQuery(document).ready(function ($) {
jQuery(".submitCookies").click(function (event) {
event.preventDefault();
jQuery.ajax({
url: ajax_object.ajaxurl2,
type: 'POST',
data: {
action: 'accepted',
whatever: 1234
},
succes: function (response) {
return response;
}
})
})
});
Function named "accepted" is inside another function, that's why it is not working. You need to learn how ajax is working in wordpress. Please go through following link. It will teach you how to use ajax in wordpress https://medium.com/techcompose/how-to-use-ajax-precisely-in-wordpress-custom-themes-dc61616720a8
Following code may help you:
<?php
function setAjaxCallbacks()
{
add_action('wp_ajax_accepted', 'accepted');
add_action('wp_ajax_nopriv_accepted', 'accepted');
}
add_action('init', 'setAjaxCallbacks');
function accepted()
{
echo 'LOLALLES';
global $wpdb;
$whatever = intval($_POST['whatever']);
$whatever += 10;
echo $whatever;
exit;
}
add_action('wp_enqueue_scripts', 'enqueue_script_custom');
function enqueue_script_custom()
{
wp_enqueue_style('CookieBarStyle', plugin_dir_url(__FILE__) . 'css/styles.css');
wp_enqueue_script('ajax-script', plugins_url('/js/my_query.js', __FILE__), array('jquery'));
wp_localize_script(
'ajax-script',
'ajax_object',
array('ajaxurl2' => 'https://wordpressjip.jmulder.dt2/wp-admin/admin-ajax.php', 'we_value' => 1234)
);
wp_print_scripts('ajax-script');
}
function setCookieBar()
{
if (!is_admin()) {
if (! isset($_COOKIE['cookieBar'])) {
?>
<div class="cookieBar" id="cookieBar" style="display: block">
<p align="center"></p>
<button id="submitCookies" class="submitCookies" name="accepted">Accepteer</button>
</div>
<?php
}
}
}
add_action( 'wp_footer', 'setCookieBar' );

jQuery load() internal server error with wordpress

I have this simple wordpress menu that I want to load in div element.
<?php
$menuParameters = array(
'theme_location' => 'sidebar-menu',
'container' => false,
'echo' => false,
'items_wrap' => '%3$s',
'depth' => 0,
);
echo strip_tags(wp_nav_menu( $menuParameters ), '<a>' );
?>
I'm using modernizr and jQuery load() to load the php file into the div element when a certain media query is detected.
jQuery(document).ready(function($){
if(Modernizr.mq('only all and (max-width:600px)')) {
$('#content-wrapper').removeClass('col-4-5');
$("#trending-Container").load( 'wordpress/wp-content/themes/test_theme/navbar-mobile.php' );
}
});
This works if just use some html or if just echo some string but when I use a wordpress function like above or something like the_title() I get a 500 internal server error.
Any ideas?
I suppose you should no directly access any file in your theme for security reasons.
Register your function in funcitons.php in your theme and then call that function_name as refereed over here enter link description here
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);
});
});
and register your action in functions.php
<?php
add_action( 'admin_enqueue_scripts', 'my_enqueue' );
function my_enqueue($hook) {
if( 'index.php' != $hook ) return; // Only applies to dashboard panel
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;
echo $whatever;
die();
}

Categories

Resources