Print HTML content from PHP to Javascript variable

0

As it says in the title, I can not do the following:

 <html>
 ......

 <script>
     var texto = " <?php echo $html; ?> ";
 </script>
 </body>
 </html>

I do not know how to make the html content that is in the PHP variable load in the javascript variable. Generate a level error in JS.

I guess it must be because maybe some of these possible expressions come into conflict when trying to print it. var text=" <html><p class = "class_one"></p></html> "; already with that example, I should give a problem to the client, but I do not know how to make that assignment.

    
asked by Islam Linarez 04.04.2017 в 05:17
source

4 answers

2

Thank you all for your help, I have found it with this:

var texto = <?php echo json_encode($articuloConsulta['contenido']); ?>;

Taken from:

link

    
answered by 04.04.2017 / 05:50
source
1

First you have to make sure that the quotes do not interfere with the JavaScript code, starting and ending the string with the single quote:

var texto = ' <?php echo $html; ?> ';

Next, you can support yourself with a regular expression replacement to remove line breaks from your html string, so that variable assignment does not fail.

preg_replace( "/\r|\n/", "", $html);

Based on your code, the complete example would be as follows:

 <html>
 ......

 <script>
     var texto = '<?php echo preg_replace( "/\r|\n/", "", $html); ?>';
 </script>
 </body>
 </html>
    
answered by 04.04.2017 в 05:46
0

Go through the quotes, what you have to do is:

 <html>
 ......

 <script>
     var texto = ' <?php echo $html; ?> ';
 </script>
 </body>
 </html>
    
answered by 04.04.2017 в 05:22
0

Identify all those characters that may be "breaking" your data to be displayed; that is, search and delete, for example:

  • jump line, return car (as I told you Francisco Javier Escoppinichi) con preg_replace( "/\r|\n/", "", $html);
  • Other characters that require \
  • Al Resultate the previous point apply htmlentities ();

Example:

<script>
 var texto = '<?php 
 $html=preg_replace( "/\r|\n/", "", $html); 
 // Ejemplo de algunos que requieren "\"
 $html=str_replace("\"", "\"", $html); 
 $html=str_replace("'", "\'", $html); 
 $html=str_replace("\", "\\", $html); 

 $html=preg_htmlentities($html);

 echo $html;
?>';
</script>
    
answered by 04.04.2017 в 05:55