Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append a string with quotes from PHP to jQuery

Tags:

jquery

css

php

i want to append a sting with quotes (eg. < span class='MyClass'> ) to some jQuery Elements, which are stored in a database. This snippet works as i want.

<script>
  $(document).ready(function() {
    <?php 
      $result = mysql_query("SELECT concat(year(`wann`), lpad(month(`wann`),2,0), lpad(day(`wann`),2,0)) as wann, `wieviel` FROM `zecken`");
      while($row = mysql_fetch_array($result)) {
        for($i=1; $i <= $row["wieviel"]; $i++) {
    ?>

$('#<?php echo $row["wann"]; ?>').append("<span class='descr bg-danger'>1</span>");

    <?php 
        } 
      } 
    ?>
  });
</script>

I just want to write in completely in PHP, and it also works if i delete the css-classes "descr bg-danger" from the span. Without css-classes my solution would be:

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

    <?php 
      $result = mysql_query("SELECT concat(year(`wann`), lpad(month(`wann`),2,0), lpad(day(`wann`),2,0)) as wann, `wieviel` FROM `zecken`");
      while($row = mysql_fetch_array($result)) {
        for($i=1; $i <= $row["wieviel"]; $i++) {

          // How to add a class to this appended span ?????
          echo "$('#".$row["wann"]."').append('<span >1</span>'); ";        
        } 
      } 
    ?>

  });
</script>

If i have to escape some quotes, how do i have to do this? It's like i would need a third pair of different quotes for the span: ;)

echo "$('#".$row["wann"]."').append('<span class='''descr bg-danger'''>1</span>'); ";
like image 362
tim99 Avatar asked Jul 07 '26 17:07

tim99


1 Answers

echo "$('#".$row["wann"]."').append('<span class=\\'descr bg-danger\\'>1</span>'); ";

or, as @Andi North mentioned:

echo "$('#".$row["wann"]."').append('<span class=\"descr bg-danger\">1</span>'); ";

(The difference between the two is that one outputs class=\'... and one outputs class=".... Either should be perfectly valid JavaScript.)

like image 183
user94559 Avatar answered Jul 09 '26 08:07

user94559