Hi
I want to use Ace to enable my users to type in a small script in the webbrowser. The script is then stored in a database.
The problem is that i can not get the text formatting to work properly with multi-line code.
To be completely honest i'm not sure if i'm doing something wrong with Ace or i do it wrong in the post/fetching the data.
I'm using nodejs with express as a webserver and ejs to create my views.
My Ace editor script looks like this:
<script>
var textarea = $('#code');
var editor = ace.edit("editor");
editor.setTheme("ace/theme/github");
editor.getSession().setMode("ace/mode/javascript");
editor.getSession().on('change', function () {
textarea.val(editor.getSession().getValue());
});
editor.getSession().setValue('<%= event_trigger.code %>');
textarea.val(editor.getSession().getValue());</script>
<%= event_trigger.code %> is the ejs way to put in the raw data from my database(postgre).
To display the data i use a div tag and a hidden textarea to put the data in a form. Whenever the code is changed in the editor it will update the textarea.
<textarea class="form-control" rows="5" id="code" name="code" style="display: none;"></textarea>
<div id="editor">
</div>
I have made a button to save the data. On click on the button i use a ajax script to send the data:
<script type="text/javascript">
$("#saveCode").click(function(){
$.ajax({
type: "POST",
async: true,
url: "/checkins/saveTriggerCode",
data: JSON.stringify({
id : $("#eventTriggerId").val(),
code : $("#code").val()
}),
dataType: "json",
contentType: "application/x-www-form-urlencoded; charset=utf-8",
success: function (msg)
{ $.toast({
heading: 'Success',
text: 'Device information updated',
showHideTransition: 'slide',
position: 'top-right',
icon: 'success'})},
error: function (err)
{
console.log({err})
$.toast({
heading: 'Error',
text: 'Code update failed \n ' + err.status,
showHideTransition: 'slide',
position: 'top-right',
icon: 'error'})}
});
});
</script>
In this case the line formatting is simply lost.
If i replace application/x-www-form-urlencoded; with application/json;
the formatting is kept in the database but when i need to display the code from the database the "\n" character causes the inserted code in editor.getSession().setValue('<%= event_trigger.code %>'); to be multi-line hence resulting in a console error.