Passing Variable from jQuery to PHP in Magento 1.9

jquerymagento-1.9

I am creating a page that will contain 2 selects/dropdowns. One will have the name of the configurable product, based on this drop down the second drop down will populate all of the colors available within the simple products associated to the configurable.

Problem: I'm not sure on how to pass the ID of the product that is selected, into a variable in php.

<script>
jQuery(document).ready(
    function(){

        jQuery('#frame').on('change', function() {

            jQuery('.lens').html(this.value); // this is just for me to see if its showing the right ID
            <?php
            $productId = 1164; //how do i set this to be this.value
            $product = Mage::getModel('catalog/product')->load($productId);
            $configurable= Mage::getModel('catalog/product_type_configurable')->setProduct($product);
            $simpleCollection = $configurable->getUsedProductCollection()->addAttributeToSelect('*')->addFilterByRequiredOptions();

             ?>

            <?php foreach($simpleCollection as $simpleProduct): ?>

            jQuery("#swcolors").append('<option value="<?php echo $simpleProduct->getAttributeText('color'); ?>"><?php echo $simpleProduct->getAttributeText('color'); ?></option>');

            <?php endforeach;?>

        });



    });

Best Answer

The issue here is that Javascript is executed on the client side (in the browser) while the PHP is processed on the server side. In other words, by the time your Javascript is handled the PHP will already be processed and can't change anymore.

To overcome this problem you can rely on AJAX. You would send the this.value value via an AJAX call to a PHP script that returns the result of the PHP part of your code snippet.

The basics of AJAX in Magento you can read about on the Atwix blog.

But actually I think the module Easylife_Switcher can already do what you are looking for. You can read more about it on the feature page.

Related Topic