Home > Mobile >  PHP modify fetched variable and return to frontend for JS
PHP modify fetched variable and return to frontend for JS

Time:02-20

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.

function product_attribute_dimensions(){
    global $product;
    
foreach ($product->get_attributes() as $taxonomy => $attribute_obj ) {
    // Get the attribute label
    $attribute_label_name = wc_attribute_label($taxonomy);
    $value = $product->get_attribute($taxonomy);
        if ($value) {
            $label = get_taxonomy($taxonomy)->labels->singular_name;
    
            $profile_one = $value;
            echo '<script>' . $attribute_label_name . ' = "' . $value . '";
            </script>';
                
        }

}

CodePudding user response:

As I understand the generated string in the variable "$attribute_label_name" is the problem? Take a look at https://www.php.net/manual/de/function.str-replace.php

With this native PHP function you can search for a character (eg."-") and replace with something else (eg. "_") echo '<script>' . str_replace("-", "_", $attribute_label_name) . ' = "' . $value . '";

But as you said, this might not be the best approach. I personally would add this kind of information into a "data-X" HTML attribute in some HTML element and would extract this in my JS. Similar to this:

<div id="some_element"  data-total-height="<?= $value ?>"></div>

You could Query something like this with jQuery $("#some_element").attr("data-total-height")

CodePudding user response:

try using window["variable_name"] do this:

echo '<script>window["' . $attrname . '"]=' . $attrval

then in your js:

let this_var = window[attrname]
  • Related