0

Okay, First off, I know that PHP works on the server side and that javascript works on the client side.

That being said, is there a way to use a javascript variable as a replacement the field name when trying to get_meta?

I'm currently combining some jquery and php on the woocommerce single product page (possibly bad practice but I don't see any other way of doing what I need to). the code I have is:

function get_format_price() {
  let selected_format = get_print_format();

  if (get_print_format() == 'original') {
    let print_price = <?php echo $product-> 
    get_meta('price_print_original_size') ?>; 
    return print_price;
  }
}

Which works just fine in terms of doing what I want it to do. The trouble is that there are six of these fields (xl size, lg size etc etc). I could of course do a series of if else's but that's a bit bloated.

What I'd like to do is use the js var "selected_format" in place of the field name so that i had something like this:

let print_price = <?php echo $product->get_meta(' + selected_format + ') ?>;

I've played around with this but not really got anywhere in terms of making it work.

My question is a. is this possible and b. if so, what syntax should I use?

Stef
  • 359
  • 1
  • 4
  • 21
  • Why are you don't use a RESTful architecture? It is the cleanest solution. `I could of course do a series of if else's but that's a bit bloated.` - You want nice code? Don't use PHP or PHP with JavaScript in one file. Use a clean architecture. – Daniel Däschle Nov 21 '18 at 11:00
  • Because I don't know how to and at this point don't have the time to learn. – Stef Nov 21 '18 at 11:04
  • You need to grab all the possible values using PHP, then output JSON to set a JS object: https://ideone.com/gFU4O3 Now you can grab the price using `return prices[get_print_format()];` –  Nov 21 '18 at 11:09
  • Note that this is a dirty quick fix; the official way (calling server-side PHP in a JS function via AJAX) is documented here: https://codex.wordpress.org/AJAX_in_Plugins –  Nov 21 '18 at 11:22
  • Thank Chris - have gone for the boring if else solution - simply because of time limits on this project. I've saved off your link and will look at it when this is all done and dusted. – Stef Nov 21 '18 at 17:14

0 Answers0