Error in Javascript string with new lines from php

Topics related to client-side programming language.
Post questions and answers about JavaScript, Ajax, or jQuery codes and scripts.
mlucicom
Posts: 34

Error in Javascript string with new lines from php

Hello! On page:
mluci.com/d/admin-index.php

- i tried to add database details from sql select into a div with javascript.
I have this php with js code:

Code: Select all

 echo '<script type="text/javascript">
var theDiv = document.getElementById("detalii");

//Here we escape single quotes in php string, to have double-quotes inside string with single-quotes in JS
theDiv.innerHTML +=\'<div id="myModal'. str_replace('"', '\"', $row2['unic2']) .'" class="modal fade" role="dialog">
  <div class="modal-dialog">

    <!-- Modal content-->
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">&times;</button>
        <h4 class="modal-title">"'. str_replace('"', '\"', $row2['locatie2']) .'"</h4>
      </div>
      <div class="modal-body">
      Proprietis:"'. str_replace('"', '\"', $row2['proprietati']) .'" <br/>
     Problems:"'. str_replace('"', '\"', $row2['probleme']) .'"<br/>
     Date:"'. str_replace('"', '\"', $row2['data']) .'"<br/>
     Image:
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>\';
</script>';
but i get some javascript error in console and code don't work.

Admin
Hello,
I think I told you in other topic, The resulted sting in javascript must be on a single line, or each new line escaped with "\".
Example:

Code: Select all

var str ='line1..<br>line2';
//or:
var str = 'line1..<br>\
line2';
- Try replace your code with this:

Code: Select all

echo '<script type="text/javascript">
var theDiv = document.getElementById("detalii");

//Here we escape single quotes in php string, to have double-quotes inside string with single-quotes in JS
theDiv.innerHTML +=\'<div id="myModal'. str_replace('"', '\"', $row2['unic2']) .'" class="modal fade" role="dialog"><div class="modal-dialog"><div class="modal-content"><div class="modal-header"><button type="button" class="close" data-dismiss="modal">&times;</button><h4 class="modal-title">"'. str_replace("'", "\\'", $row2['locatie2']) .'"</h4></div><div class="modal-body">Proprietis:"'. str_replace("'", "\\'", $row2['proprietati']) .'" <br/>Problems:"'. str_replace("'", "\\'", $row2['probleme']) .'"<br/>Date:"'. str_replace("'", "\\'", $row2['data']) .'"<br/>Image:</div><div class="modal-footer"><button type="button" class="btn btn-default" data-dismiss="modal">Close</button></div></div></div></div>\';
</script>';

Similar Topics