Skip to content
Advertisement

PHP modify fetched variable and return to frontend for JS

Im fetching Product Attributes from Woocommerce, and echo them out in a script tag as variable to use with javascript in frontend. This might be a bad practice, feel free to enlighten me.

Example:

Product Attributes:

Total height: 43m

Total length: 55m

PHP queries “Total-height” as Attribute Name and “43m” as Attribute Value. PHP replaces empty space with “-“. I can’t define a javascript var with “-” in var name. Example: var Total-height = "43m";

How could I fix this issue? Here is my code. Thanks in advance.

JavaScript

Advertisement

Answer

try using window["variable_name"] do this:

JavaScript

then in your js:

JavaScript

It seems like the clearest shortest way to do this.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement