Kaleb
Kaleb

Reputation: 17

PHP within javascript for dropdown menu

I have been trying to solve my issue of creating a dropdown menu within a javascript, but using PHP data. I know that you can't "run" PHP within a javascript, but have not been able to solve my issue. My goal is to give the ability to add more items to a form on the fly. I have it working just fine without the dropdown menu, so below is all the code that I think it needed. This is what I started with and I have tried multiple fixes, without any luck.

Thank you for your input!

    newdiv.innerHTML = "<div style=\"float:left; width:200px;\"><select name=\"Room_Type\" style=\"width:200px;\" tabindex=\""+counter+"\">";

              newdiv.innerHTML .= "<option value=\"\" selected=\"selected\">Select one</option>";
<?php
        if ($Total_Rows != 0) {

            $Run_Cnt = 0;

            while ($Run_Cnt < $Total_Rows): ?>

                newdiv.innerHTML .= "<option value=\""+<?=$Room_Type_List[$Run_Cnt]['ID']; ?>+"\">"+<?= stripslashes($Room_Type_List[$Run_Cnt]['Type_Name']); ?>+"</option>";<?php
            $Run_Cnt++;  
            endwhile;

        } ?>
        newdiv.innerHTML .= "</select></div>";

Upvotes: 0

Views: 57

Answers (1)

Brad
Brad

Reputation: 163272

Never concatenate data directly into a script. It must be escaped properly for it work. stripslashes() is not enough. In your code, you are outputting data from PHP into JavaScript, and then in JavaScript into HTML. This will only lead to headache.

In your case, I think you will find it best to send your room type data to JavaScript, and then assemble your elements in JavaScript client-side.

<script>
  // Use JSON-encoding, which is compatible with JavaScript
  var roomTypes = <?php echo json_encode($Room_Type_List); ?>;

  // Now, all of your room data is available to use directly within JavaScript
  console.log(roomTypes);

  // Build your HTML here

</script>

Now, when you build your HTML, be sure to set the attributes and text. Never concatenate data in as HTML, unless that data actually is HTML. Use el.setAttribute() and el.textContent(). Text can be tricky, so I usually just use jQuery's .text().

Upvotes: 1

Related Questions