Problem passing data from a shortcode to Javascript.
-
Hello, I have a problem when passing attributes from a shortcode to JavaScript to make a query on Firebase.
From the shortcode to the array the data is fine, but when passing it to Javascript it passes the data by default.
Shortcode:
[custom_firebase clientid=”0002″ name=”Louise”]
The function:
function custom_firebase_scripts_function($atts){
wp_enqueue_script(‘custom_firebase’, get_template_directory_uri() . ‘/js/firebase-script.js’,
array(‘firebase_app’, ‘firebase_auth’, ‘firebase_database’, ‘firebase_firestore’, ‘firebase’));$atts = shortcode_atts(array(
‘clientid’ => ‘0001’,
‘name’ => ‘Matt PHP’
), $atts);$paramsc = array (
‘clientid’ => $atts[‘clientid’],
‘name’ => $atts[‘name’]
);
wp_add_inline_script(‘custom_firebase’,’ const vars_client = ‘ . json_encode($paramsc), ‘before’);
return ‘<div id=”custom-firebase”> ‘ . $paramsc[‘clientid’] . ‘ </div>’;//The result I get from this line is 0002.
}
add_shortcode(‘custom_firebase’, ‘custom_firebase_scripts_function’);
add_action(‘wp_enqueue_scripts’, ‘custom_firebase_scripts_function’);I tried using wp_localize_script, but saw that the correct way is to use wp_add_inline_script, I got the same results anyway.
For the query in Firebase I refer to the attributes in this way, it shows the fields correctly, but not the documents I want.
const collectionName = ‘Clients’;
const documentName = vars_client.clientid;console.log(‘Value: ‘, vars_client.clientid);
console.log(‘Value: ‘, vars_client.name);The console shows the default values: 0001 and Matt PHP, but on the page it shows me 0002 (which is what I have as data in the shortcode).
Extra data that could be relevant:
– For the Firebase integration I use the Integrate Firebase plugin.
– I use Cloud Firestore.
– The php function is in function.php directly in the theme.I have almost no knowledge of PHP, Javascript and HTML, there are probably things misspelled or with little logical sense, I apologize for that.
I am on the lookout for any extra information that is required.
Thanks. -
Hi,
Can you share the URL of your website?
I’m not seeing any WordPress.com sites associated with the user account you are posting from. This frequently means that you have a site using the open-source WordPress software from WordPress.org, but hosted elsewhere.
We’re only able to provide support for WordPress websites that are hosted by us here at WordPress.com. For help with a WordPress site hosted elsewhere you’ll need to ask over at the WordPress.org forums:
https://wordpress.org/support/forums/
Depending on the level of support that is included with your hosting plan, your webhost’s support team may also be able to assist.
If you want to know more about the differences between WordPress.com and the open-source WordPress software you can read this article:
- The topic ‘Problem passing data from a shortcode to Javascript.’ is closed to new replies.