I have blog post list and that post have comments. Posts and comments i loop with foreach
from database.So i have problem when i want to create new comment via ajax. I have form and one hidden field for holding post id.
When from jquery i try to access to that element post_id
is all time the some. I try on submit to debug with alert to see witch post_id
will be returned. All time return 270. And when i click to other post comment submit id is not changed.
Posts and comments
<?php foreach($posts as $post): ?>
<h1><?= $post->title; ?></h1>
<p><?= $post->text; ?></p>
<?= if($comments = postComments($post->id): ?>
<?= foraech($comments as $comment): ?>
<form id="post_add">
<input type="text" placeholder="Say somthing..." name="comment">
<input type="hidden" name="pid" class="pid" value="<?= $post->id">
<input type="submit">
</form>
<?= endforeach; ?>
<?= endif; ?>
<?= endforeach; ?>
submiteComment: function() {
var comment_form = $("#comment_add");
var comment_text = $(".comment_text");
var pid = $(".pid"); // post id
$("body").on("submit", comment_form, function(e) {
e.preventDefault();
alert(pid.val()); // debug all time return 270 for all comments
if($.trim(comment_text).length) {
$.ajax({
type: 'post',
url: baseurl + '/comment/create',
data: {item_id: post_id.val(), comment_text: comment_text.val()},
success: function(data) {
alert('success');
},
error: function(t, r, j) {
alert(r.responseText);
}
})
}
});