There are two problems.
First, onclick
can only call functions that are in the global scope. Your function is defined inside $(document).ready()
, so it's not in the global scope.
Second, you're defining the function using a named function expression. The scope of this name is only the body of the function itself. See Why JavaScript function declaration (and expression)?
Since you're calling the function from onclick
, you don't need to put it inside $("#comq").click()
, or in $(document).ready()
.
Just define it as a normal function in the global scope. And since you're calling it with $d['qid']
as the second argument, you don't need to assign to qid
in the function. You also don't need the event
argument, since you never use it in the function (it was only needed before because you were calling the function from $("#comq").click()
).
You can't use the same ID multiple times, a selector for the ID will just find the first element with that ID, not the one next to the button. Pass the button as another argument to the function, and use that to get the comment box adjacent to it.
HTML:
<div id="comments" class="cmt" >
<img width="30px" height="30px" src="/cropphoto/<?php echo getuserPhoto($d['uid']); ?>">
<input class="commentbox" name="comments" placeholder="Comment Here" maxlength="50" >
<button type="button" name="compost" onclick="my(<?php echo $d['qid'];?>, this);" class="butn2" >post comment</button>
</div>
JS:
function my(qid, button) {
var comment = $(button).siblings(".commentbox").val();
alert(qid);
$.ajax({
cache: false,
type: "post",
url: "jquery.php",
data: {
comments: comment,
qid: qid
},
success: function(data) {
$("#comment").val("");
$("").html(data);
}
});
}
Here's an executable snippet that demonstrates it without AJAX:
function my(qid, button) {
var comment = $(button).siblings(".commentbox").val();
console.log("id = " + qid, " comment = " + comment);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="comments" class="cmt">
<img width="30px" height="30px" src="/cropphoto/<?php echo getuserPhoto($d['uid']); ?>">
<input class="commentbox" name="comments" placeholder="Comment Here" maxlength="50">
<button type="button" name="compost" onclick="my(1, this);" class="butn2">post comment</button>
</div>
<div id="comments" class="cmt">
<img width="30px" height="30px" src="/cropphoto/<?php echo getuserPhoto($d['uid']); ?>">
<input class="commentbox" name="comments" placeholder="Comment Here" maxlength="50">
<button type="button" name="compost" onclick="my(2, this);" class="butn2">post comment</button>
</div>