mmoscosa
mmoscosa

Reputation: 397

php if inside javascript

I am trying to use the bootstrap typehead plugin.

The idea is:

  1. I have a Manufacturer Option
  2. I Have a Model Option
  3. Only once the Manufacturer option is selected, the model option is enabled.
  4. The model option is filtered by manufacturers.

CakePHP Controller is sending me a 'findall' array of both Manufacturer and Models (Which I call Variety instead of Model for naming convention)

model_source = [];
$('#manufacturer').typeahead({
        source: [
            <?php
                foreach($manufacturers as $manufacturer):
                    if($manufacturer['Manufacturer']['bow'] == true):
            ?>
                "<?php echo $manufacturer['Manufacturer']['manufacturer']; ?>",
            <?php
                    endif;
                endforeach;
            ?>
        ]
    });
    $('#manufacturer').live("change", function(){
        if($(this).val()){
            $('#model').attr('disabled', false);
            manufacturer = $(this).val();
            <?php
                foreach($varieties as $model):
                    if($model['Variety']['bow'] == true):
            ?>
                model_source.push("<?php if($model['Variety']['manufacturer_id'] == "+manufacturer+"){echo $model['Variety']['model'];}else{ continue; } ?>");
            <?php
                    endif;
                endforeach;
            ?>
        }else{
            $('#model').attr('disabled', true);
        }
    });

The problem I am having is where I try to do

    model_source.push("<?php if($model['Variety']['manufacturer_id'] == "+manufacturer+"){echo $model['Variety']['model'];}else{ continue; } ?>");

If I hardcode the manufacturer variable to be all in one line of PHP then it works (without the else statement, that is also giving me problems I get an ILEGAL error on my console)

Any idea in why when I concatenate the php string with the javascript variable it then doesn't work?!

http://jsfiddle.net/mmoscosa/Y6hEA/

Thank you!

Upvotes: 2

Views: 1679

Answers (1)

robonerd
robonerd

Reputation: 198

Your javascript variable happens to be between <?php ?> tags. You can't use javascript manufacturer variable in your if statement. PHP is server side, JavaScript is client side.

Upvotes: 5

Related Questions