To keep my code clean I am defaulting each of the elements of a form with jQuery.
i.e My form contains elements like this..
<input name="mobile" id="mobile" type="text" />
In my separate javascript file, I read data from MySQL, then use jQuery to set it, after the form is loaded..
$('#mobile').val('07845 887766');
this value is read from MySQL and I generate the code like this, in PHP..
echo "\n $('#mobile').val('".$user['mobile']."');";
This works fine, but the problem lies when there is a textarea field..
<textarea name="notes" id="notes" ></textarea>
echo "\n $('#notes').html('TEST');";
This works fine, but when I replace it with the data from a database, which can contain newlines, I get a javascript error.
echo "\n $('#notes').html('".$user['notes']."');";
This could produce this code (Actual values…)
$("#notes").html("INSERT INTO action (
inputdate,
)
VALUES ()");
Which gives an error. “unterminated string literal”
You’re getting this message because in Javascript you can’t span literal strings across multiple lines.
What you need to do is replace newlines in
$user['notes']with the characters\r\nso all the string is on one line then the<textarea>input will correctly show each item on a new line.Let’s use
json_encodeto help us also escape any nasty characters which Javascript won’t like.