Just ran into a problem I thought I’d document here as I will innevitably hit it again and would rather not waste an hour trying to solve it again!
When viewing an individual message, you have a comment form at the bottom so you can reply to the message (just like in these posts). I then want to submit the form via AJAX and have the textarea replaced with the response.
The relevant Javascript code should have simply been
$('#message-comment-form').submit(function(event) {
event.preventDefault();
$.ajax({
type: 'POST',
data:$(this).serialize(),
url: SITE_URL+'messages/ajax/add_comment',
success: function(response) {
console.log(response);
$('#comment-form').html(response);
}
});
});
But that wasn’t working, and when I received the post array in the controller, the body (of the comment) was always null.
This is because I was using the NicEdit WYSIWYG editor for comments, and it doesn’t actually store the contents of what you write in the text editor, but instead in a div overlaying the textarea, so I had to get the contents of this div and manually create the serialized form contents as follows
$('#message-comment-form').submit(function(event) {
event.preventDefault();
$.ajax({
type: 'POST',
data: 'body='+$('.nicEdit-main').text(),
url: SITE_URL+'messages/ajax/add_comment',
success: function(response) {
console.log(response);
$('#comment-form').html(response);
}
});
});
Unfortunately, this loses the inline styles (for bold, underline, italics etc) which kind of defeats the point of the WYSIWYG editor. If anyone has any thoughts how to solve that part I’d appreciate it.
Does changing
data: ‘body=’+$(‘.nicEdit-main’).text(),
to
data: ‘body=’+$(‘.nicEdit-main’).html(),
solve the problem?