I am facing a challenge while trying to use AJAX in Rails to POST a comment without using remote: true
. I am confused as to why my myJSON
variable is showing up as undefined, while data
is returning as expected.
Check out my code below:
function submitViaAjax() {
$("#new_comment_button").on("click", function (e) {
e.preventDefault();
url = $(this.form).attr('action')
data = {
'comment': {
'content': $("#comment_body").val()
}
};
var myJSON = JSON.stringify(data);
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
url: url,
data: myJSON,
// headers: { 'Content-Type': 'application/json' },
success: function (response) {
var $ul = $("div.comments_section ul");
$ul.append(response)
}
}).done(function(response){
debugger
var $ul = $("div.comments_section ul");
$ul.append(response)
})
})
};
Even though
var myJSON = JSON.stringify(data);
works well when run in the browser console, it seems like it's not functioning properly within my code.
I would greatly appreciate any assistance with this issue.