1

I want to add a PHP script which has HTML tags, inside a javascript. Below you can see the code I tried. But It's not working and stating that there is an error

<script type='text/javascript'>
//<![CDATA[
 $(document).ready(function() {
  var currentItem = 11;
  $('#addnew').click(function(){
   currentItem++;
   $('#items').val(currentItem);
var strToAdd = '<tr><td><select class="form-control select2" name="product'+currentItem+'" id="product'+currentItem+'" style="width: 100%">'+
                <?php foreach ($productData as $product) { echo "<option value='" . $product->product_id . "'>" . $product->product_name . "</option>"; }?>+
                '</select> </td><td><input class="form-control" name="quantity'+currentItem+'" id ="quantity'+currentItem+'"type="text" /></td> 
                <td><input class="form-control"  name="freeIssue'+currentItem+'" id="freeIssue'+currentItem+'" type="text" /></td>
                 <td align="center"><button  class="btn btn-danger" name="close" id="close" onclick="SomeDeleteRowFunction(this)"><i class="fa fa-close"></i></button></td></tr>';



   $('#data').append(strToAdd);

  });

  $('#remove').on("click", function(){
    $('#data tr:last').remove();
})

 });

//]]>
</script>

This is the error I get:

enter image description here

3
  • 1
    You can view your rendered source code by pressing Ctrl+u what can you see in that in ur javascript ? Commented Sep 20, 2018 at 5:36
  • Your quotes are off. If you echo a string from PHP, you need to wrap the result in ', like this: '<?php .... ?>' or it will print HTML directly into the javascript block and the browser will try and parse the html as js. Commented Sep 20, 2018 at 5:39
  • 1
    I would always suggest that you generate content before echo it like this, its unnecessary complex and at this level is irrelevant for the page speed. So use a extra variable. To the main question, you should check your quotation there are a few problem due the fact that you closed the string syntax and open it again to late. So Javascript tries to evaluate part of the String which causes the Error you are seeing. Commented Sep 20, 2018 at 5:57

1 Answer 1

1

You need to put an extra ' after echo " otherwise you do not get the desired javascript string like '<option... >' but you get an <option... > which means nothing in a js code.

 echo "'<option value='" . $product->product_id . "'>'" 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.