I’m in the midst of creating a website that includes shopping cart functionality and have run into an issue with passing variables back-and-forth from HTML/Javascript to PHP. I understand that these languages are fundamentally different and was hoping someone could provide some guidance. I’ve seen several questions on similar topics, but unfortunately have yet to find a solution that works for my situation.
I have created a multidimensional array of products in php and would like to capture the value from a dropdown menu to call a function in which the value of the dropdown corresponds to a row in the product array. My list of products appear in a HTML table. I have experimented with $_GET and $_POST, but haven’t had any luck. Plus I would like to avoid adding a submit button as the print_wp_cart_button_for_product function outputs an add to cart button. The print_wp_cart_button_for_product also creates the shopping cart on the sidebar.
<TD>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="get">
<select id="productcat1" name="productcat1">
<option value="$">--Please Select--</option>
<option value="1">Product # 1 - $1.99</option>
<option value="2">Product # 2 - $1.99</option>
<option value="3">Product # 3 - $9.99</option>
<option value="4">Product # 4 - $9.99</option>
</select>
</form>
</TD>
<TD>
<?php $currentrow = 0; ?>
<?php $currentrow = $_GET["productcat1"]; ?>
<?php echo print_wp_cart_button_for_product($products[$currentrow]["Product"], $products[$currentrow]["Price"]); ?>
</TD>
Since PHP is a server side language, it has no way of knowing what is happening in the client (i.e. what is happening live in the users browser, such as which dropdown they have selected). You will have to use javascript/ajax, either to run your function entirely, or to communicate the selected option back to the server to run the PHP function. Alternatively, you can communicate with the server without javascript/ajax by submitting the form, but you said you don’t want to do that.
Good luck!