Reputation: 853
I am trying to trigger a post request when a user clicks the submit button for a comment. Right now clicking the submit button triggers nothing, I even tried to console.log($(this)) I got no output. The first code below is the jQuery event code and ajax code. The block of code below that is the html button. thanks for the help.
$('#submitComment').on('click', '#content', function() {
$.ajax({
url: 'http://localhost:3000/comments',
type: 'POST',
data: data = { comment: {
body: $(this).find('input[name="createComment"]').val(),
user_id: 1,
image_set_id: 2}
}
}).done(function(response) {
console.log(response);
});
});
the button I am trying to target with jQuery event
<div class="container">
<div id="content">
//the code between comments is in a Handelbar template
<input name="createComment">
<button type="submit" id="submitComment">Create Comment</button>
//end of handelbar template
</div>
</div>
Upvotes: 1
Views: 50
Reputation: 388316
You need to bind the delegated handler to an ancestor(#content
) of the target element(submitComment
)
$('#content').on('click', '#submitComment', function () {
$.ajax({
url: 'http://localhost:3000/comments',
type: 'POST',
data: data = {
comment: {
body: $(this).find('input[name="createComment"]').val(),
user_id: 1,
image_set_id: 2
}
}
}).done(function (response) {
console.log(response);
});
});
Upvotes: 1