how to handle jquery events through button onclick functions - javascript

how to handle jquery events through button onclick functions
HTML CODE
<div id="comments" class="cmt" >
<img width="30px" height="30px" src="/cropphoto/<?php echo getuserPhoto($d['uid']); ?>">
<input class="commentbox" id="comment" name="comments" placeholder="Comment Here" maxlength="50" >
<input type="hidden" id="qid" name="qid " value="<?php echo $d['qid'];?>">
<button type="button" id="comq" name="compost" onclick="my(event,<?php echo $d['qid'];?>);" class="butn2" >post comment</button>
</div>
AJAX JQUERY
$(document).ready(function() {
$("#comq").click(function my(e, id) {
var comment = $("#comment").val();
var qid = $("#qid").val();
alert(qid);
$.ajax({
cache: false,
type: "post",
url: "jquery.php",
data: {
comments: comment,
qid: qid
},
success: function(data) {
$("#comment").val("");
$("").html(data);
}
});
});
});
comments not inserted into the database with the button on click function but without the button on keypress working fine What is the mistake in my code please let me know i am now in ajax

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>

first of all it looks like you are trying to send 2 arguments in your HTML:
onclick="my(event,<?php echo $d['qid'];?>);
But the function only accepts 1?
$("#comq").click (function my(e) {
I'm not sure if that solves your problem but you could start there.

oh got it just add another parameter with it
$("#comq").click (function my(e, id) {
or what I would do is I would define a function my like this
function my(e, id){
$.ajax({
cache:false,
type:"post",
url:"jquery.php",
data:{$("#comment").val(),qid:id},
success:function(data)
{
$("#comment").val("");
$("").html(data);
}
}
this looks more neat in my opinion

First, you don't need to use:
$("#comq").click (function my(e...
because you already have onclick(my(a,b)). Just create a function like:
function my(a, b){
alert(a +" "+b)
}
Does this work for you?
<html>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.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" id="comment" name="comments" placeholder="Comment Here" maxlength="50" >
<button type="button" id="comq" name="compost" onclick="my(2, 'test test')" class="butn2" >post comment</button>
</div>
<script>
function my(comment, qid){
alert(comment + " - " + qid)
$.ajax({
cache:false,
type:"post",
url:"jquery.php",
data:{comments:comment,qid:qid},
success:function(data)
{
$("#comment").val("");
}
});
}
</script>
</body>
</html>

Related

How to serialize form data by number in javascript and submit with a specific number

I'm working on a personal project, where I've more forms than one (comment forms under each post). Each form I give a number according to post id.
<form id="postCommentsForm<?php echo $ansRow['id'];?>" class="form">
<div class="input-group mb-3">
<a href="user/<?php echo $username;?>">
<img class="p-1 m-0" src="images/<?php echo $userAvatar;?>" width="35" height="35" alt="<?php echo $userAvatar;?> profile picture">
</a>
<input name="post_comment<?php echo $ansRow['id'];?>" id="add_comments" type="text" autofocus autocomplete="off" class="add_comments form-control pl-3 pr-3" placeholder="<?php echo $userFname;?>, type something" aria-label="Recipient's username" aria-describedby="button-form">
<input type="text" hidden id="question_id" name="question_id" value="<?php echo $row['id'];?>">
<input type="text" hidden id="answer_id" name="answer_id" value="<?php echo $ansRow['id'];?>">
<input type="text" hidden id="session_id" name="session_id" value="<?php echo $_SESSION['id'];?>">
<div class="input-group-append">
<button class="btn btn-secondary submit-comments" type="submit" name="submit_comment<?php echo $ansRow['id'];?>" id="postComments">Comment</button>
</div>
</div>
</form>
javascript code
$(document).ready(function() {
$("[id^=postCommentsForm]").on("submit", function(e) {
e.preventDefault();
var add_comments = $("#add_comments").val();
var question_id = $("#question_id").val();
var answer_id = $("#answer_id").val();
// var session_id = $("#session_id").val();
if(add_comments == "" ){
$("#error-message").html("All fields are required!").slideDown();
$("#success-message").slideUp();
}else{
//Ajax
$.ajax({
url: "include/forms-data/comments.php",
type: "POST",
data: {
add_comments: add_comments,
question_id: question_id,
answer_id: answer_id
},
success: function(data) {
if (data != 0) {
$("[id^=postCommentsForm").trigger("reset");
$("#success-message").html("Question Added Successfully!").slideDown();
$("#error-message").slideUp();
} else {
//alert("Can't save record");
$("#error-message").html("Something went wrong!").slideDown();
$("#success-message").slideUp();
}
}
});
}
});
});
How I can fetch #comments(postID here), and submit form data successfully under the postID?
I hope I define well the question.
Jquery's "starts with selector" can help. check out here
$(document).ready(function() {
$("[id^=comments]").click(function(e) {
var element_id = this.getAttribute("id");
});
});
Live Demo:
$(document).ready(function() {
$("[id^=comments]").click(function(e) {
console.log($(this).attr('id'));
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id='comments1'>b</button>
<button id='comments2'>a</button>

Unique comment section per dynamic modal

I have a webpage with dynamically loaded cards that pop up into individual modals to display more data. These modals all have their unique id in order to pop up the correct one.
I am attempting to put a unique comment section for each modal. What I have implemented works only for the first modal & doesnt even show the comments on the second modal onwards.
I would appreciate some direction in how to make them display per modal & how to make them unique. I am assuming I echo $test[id] just like I used for the modals. Need a little assistance in script side of things.
<div id="myModal<?php echo $test['id']; ?>" class="modal">
<div class="modal-content">
<div class="container">
<form method="POST" id="comment_form">
<input type="hidden" id="id" name="id" value="<?php echo $test['id']; ?>">
<div class="form-group">
<input type="text" name="comment_name" id="comment_name" class="form-control" placeholder="Enter Name" />
</div>
<div class="form-group">
<textarea name="comment_content" id="comment_content" class="form-control" placeholder="Enter Comment" rows="5"></textarea>
</div>
<div class="form-group">
<input type="hidden" name="comment_id" id="comment_id" value="0" />
<input type="submit" name="submit" id="submit" class="btn btn-info" value="Submit" />
</div>
</form>
<span id="comment_message"></span>
<br />
<div id="display_comment<?php echo $test['id']; ?>"></div>
</div>
</div>
</div>
<script>
var data = 1;
$(document).ready(function(){
$('#comment_form').on('submit', function(event){
event.preventDefault();
var form_data = $(this).serialize();
$.ajax({
url:"add_comment.php",
method:"POST",
data:form_data,
dataType:"JSON",
success:function(data)
{
if(data.error != '')
{
$('#comment_form')[0].reset();
$('#comment_message').html(data.error);
$('#comment_id').val('0');
load_comment();
}
}
})
});
load_comment();
function load_comment()
{
$.ajax({
url:"fetch_comment.php",
method:"POST",
success:function(data)
{
$('#display_comment').html(data);
}
})
}
$(document).on('click', '.reply', function(){
var comment_id = $(this).attr("id");
$('#comment_id').val(comment_id);
$('#comment_name').focus();
});
});
</script>
UPDATE:
Going with the response received, I made certain changes & noticed that even though the comment form is visible on all modals, the posted comments itself
only appear on the first modal. With a bit of hardcoding I am able to tell that the display_comment(id) in html & script needs to be same. The HTML id updates as per console, but I am unable to pass the correct id to $('#display_comment'+myData1).html(data); (it is always 1).
<div id="myModal<?php echo $test['id']; ?>" class="modal">
<div class="modal-content">
<div class="container">
<form method="POST" id="comment_form">
<input type="hidden" id="id" name="id" value="<?php echo $test['id']; ?>">
<div class="form-group">
<input type="text" name="comment_name" id="comment_name" class="form-control" placeholder="Enter Name" />
</div>
<div class="form-group">
<textarea name="comment_content" id="comment_content" class="form-control" placeholder="Enter Comment" rows="5"></textarea>
</div>
<div class="form-group">
<input type="hidden" name="comment_id" id="comment_id" value="0" />
<input type="submit" name="submit" id="submit" class="btn btn-info" value="Submit" />
</div>
</form>
<span id="comment_message"></span>
<br />
<div id="display_comment<?php echo $test['id']; ?>"></div>
</div>
<div id="dom-target" style="display: none;" data-id="<?php echo htmlspecialchars($test['id']);?>">
<?php
echo htmlspecialchars($test['id']);
?>
</div>
</div>
<script>
$(document).ready(function(){
$('#comment_form').on('submit', function(event){
event.preventDefault();
var form_data = $(this).serialize();
$.ajax({
url:"add_comment.php",
method:"POST",
data:form_data,
dataType:"JSON",
success:function(data)
{
if(data.error != '')
{
$('#comment_form')[0].reset();
$('#comment_message').html(data.error);
$('#comment_id').val('0');
load_comment();
}
}
})
});
load_comment();
function load_comment()
{
var myData1 = $("#dom-target").data("id");
console.log('#display_comment'+myData1);
$.ajax({
url:"fetch_comment.php",
method:"POST",
success:function(data)
{
$('#display_comment'+myData1).html(data);
}
})
}
$(document).on('click', '.reply', function(){
var comment_id = $(this).attr("id");
$('#comment_id').val(comment_id);
$('#comment_name').focus();
});
});
</script>
I have also tried the following & simply receive undefined as the value in console for myData2:
$.ajax({
url:"fetch_comment.php",
method:"POST",
data: {
myData2: $("#dom-target").data("id")
},
you should loop all the content according to your $test['id'].
each loop will generate each $test['id'], modals, form.
therefore, you will have multiple form according to each modals.
regarding the name of the input box (name="comment_id","comment_name" etc), just use the same name, as this will affect your backend on how you will process those input ($_POST['']).
this shouldn't be an issue if you area using same input name as user can only submit 1 form on each request.
just the value will be changing based on the form.

jquery onclick function not defined

I have an ajax script and I am trying to post from a function. I am using a onlick href but its not coming up as undefined. This is using wordpress. I have tried to move the code around inside and outside the scope but I still cant seem to get it to work.
<div id="live">
<div class="container">
<?php the_content(); ?>
<div id="comment-display">
<form method="post" action="index.php" id="comments_submit">
<input type="hidden" id="nameBox" value="<?php echo $_SESSION['name'] ?>" name="name"/>
<input type="hidden" id="emailBox" name="email" value="<?php echo $_SESSION['email']; ?>"/>
<textarea id="chatBox" placeholder="Ask a question or make a comment" name="comment" class="form-control"></textarea>
Submit Comment
</form>
<br />
<div id="displayComments"></div>
</div>
</div>
</div>
<script type="text/javascript">
jQuery(function($) {
setInterval(function(){
$.ajax({
method: "GET",
url: "<?php echo get_template_directory_uri()?>/get_chat.php"
}).done(function(html){
$('#displayComments').html(html);
});
}, 2000);
function submitComment(){
$.ajax({
method: "POST",
url: "template-live.php",
data: {submitComment:$('#chatBox').val(),submitName:$('#nameBox').val(),submitEmail:$('#emailBox').val()}
}).done(function(html){
alert('Your comment has been submitted, and will be displayed after approval.');
$('#chatBox').val('');
});
}
});
</script>
Thank you :)
When you do javascript:submitComment() that's calling a the global function submitComment. Since the submitComment is defined in the jQuery(function($) { ... }) function, it is not a global. Therefore, window.submitComment is undefined (hence undefined is not a function).
The globals are stored in the window object.
Therefore, you can expose that submitComment as a global:
window.submitComment = function () {...}
Note that you should avoid using globals as much as possible. In this case you can do that by adding:
$("#submit").click(submitComment);
// In this case, you shouldn't declare submitComment as a global anymore
And since you are in a form, you want to stop the default browser behavior when clicking the a element, by using return false at the end of the function.
Alternatively to #Ionică Bizău's solution.
You could use onclick="submitComment()" instead of href.
<a onclick="submitComment()" type="submit" id="submit" name="submit" class="btn cardh-bg text-white text-bold margin-top-5"> Submit Comment </a>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<div id="live">
<div class="container">
<?php the_content(); ?>
<div id="comment-display">
<form method="post" action="index.php" id="comments_submit">
<input type="hidden" id="nameBox" value="<?php echo $_SESSION['name'] ?>" name="name" />
<input type="hidden" id="emailBox" name="email" value="<?php echo $_SESSION['email']; ?>" />
<textarea id="chatBox" placeholder="Ask a question or make a comment" name="comment" class="form-control"></textarea>
<a onclick="submitComment()" type="submit" id="submit" name="submit" class="btn cardh-bg text-white text-bold margin-top-5"> Submit Comment </a>
</form>
<br />
<div id="displayComments"></div>
</div>
</div>
</div>
<script type="text/javascript">
jQuery(function($) {
setInterval(function() {
$.ajax({
method: "GET",
url: "<?php echo get_template_directory_uri()?>/get_chat.php"
}).done(function(html) {
$('#displayComments').html(html);
});
}, 2000);
window.submitComment = function(){
console.log('submitComment called!');
$.ajax({
method: "POST",
url: "template-live.php",
data: {
submitComment: $('#chatBox').val(),
submitName: $('#nameBox').val(),
submitEmail: $('#emailBox').val()
}
}).done(function(html) {
alert('Your comment has been submitted, and will be displayed after approval.');
$('#chatBox').val('');
});
}
});
</script>

jQuery openPopup modal doesn't close after submit

I've put a modal popup box for getting inputs and then stores via ajax. It's inserted values succesfully.. but the popup stills after submittion. i've try everything like window.close(); ... ('#modalname').hide(); but nothing works for me. please help me to fix this bug.
Here's my part of working code,
<!--css for display subject in row (starts)-->
<span class="b-messages__subject">
<span>
<a href="index.php?subject=<?php echo $results[$result]['subject']; ?>&username=<?php echo $results[$result]['username']; ?>#openModal" onclick="fetch_select(<?php echo $results[$result]["id"]; ?>);">
<?php echo "Reply"; ?>
</a>
</span>
</span>
<!--css for display subject in row (ends)-->
and then modal div is,
<!--Modal box starts-->
<div id="openModal" class="modalDialog" align="center">
<div>
X
<h2><strong>Reply Message</strong></h2>
<br>
<label><strong>Enter Your Message Here</strong></label>
<br>
<label><b>From:</b> <?php echo $user; ?></label>
<span id="content-info" class="info"></span>
<br/>
<!--set session username for hidden-->
<input type="hidden" name="username" id="username" value="<?php echo $user; ?>">
<textarea name="content" id="content" class="demoInputBox"></textarea>
<!--send fusername with hidden-->
<input type="text" name="fusername" id="fusername" value="<?php echo $_GET["username"] ?>">
<!--send subject with hidden-->
<input type="text" name="subject" id="subject" value="<?php echo $_GET["subject"] ?>">
<!--status init="0"-->
<input type="hidden" name="status" id="status" value="0">
<!--time-->
<input type="hidden" name="created" id="created" value='<?php echo date("Y-m-d H:i:s"); ?>'>
<br><br>
<input type="button" name="submit" id="but-sub" value="Send Message" onClick="add();" />
</div>
</div>
<!--Modal box ends-->
My js file contains:
function add() {
/*initialize valid and assign to function validate()*/
var valid = validate();
//alert(valid); returns true
//if function validate() returns valid.. then go away
if (valid){
$.ajax({
url: "add.php",
type: "POST",
data: {
username: $("#username").val(),
fusername: $("#fusername").val(),
subject: $("#subject").val(),
content: $("#content").val(),
status: $("#status").val(),
created: $("#created").val()}
});
}
}
I am not sure if you are using JSON, but you should definitely be checking the response for pass or fail. Try adding success after your data like this (doesn't include check for pass or fail, but should close modal upon success response of the AJAX):
$.ajax({
url: "add.php",
type: "POST",
data: {
username: $("#username").val(),
fusername: $("#fusername").val(),
subject: $("#subject").val(),
content: $("#content").val(),
status: $("#status").val(),
created: $("#created").val()
},
success: function (returndata) {
//try this first
$("#openModal").modal('hide');
//try this second and uncomment if you aren't using jquery/bootstrap modal
//$("#openModal").hide();
}
});
Put your form elements in a <form></form>.
The modal should close if form is submited.

Ajax - How to submit one by one input value - Codeigniter

Sorry for my english is not so good. And i'm newbie :)
I want to update one-by-one input value with ajax in Codeigniter, but it not work right.. only one save button (one form) work, others form not work .. please help me edit below code
Here's the demo code:
View:
<script>
$(function(){
$(".submit45").click(function(){
dataString = $("#prod_upd").serialize();
$.ajax({
type: "POST",
url: "<?=PREFIX?>admin/update/change_ppx3/",
data: dataString,
success: function(data){
console.log(data);
document.getElementById('dd').innerHTML=data;
}
});
return false;
});
});
</script>
<?$i=0;if(count($PPX) > 0)foreach($PPX as $item){$i++;?>
<form name="prod_upd" id="prod_upd" method="post" >
<input type="text" name="p_ppx" id="p_ppx" size="8" value="<?= number_format($item['p_ppx'],0,'','')?>" class="i_ppx">
<input type="hidden" name="ids_p" id="ids_p" size="8" value="<?=$item['id']?>" class="i_ppx">
<input type="button" name="sub" id="sub" class="submit45" value="Save4" />
<div id="dd" style="float: left;">hello</div>
</form>
<?}else{?>
<div class="no_data">Nothing here</div>
<?}?>
Controller:
function change_ppx3(){
$id_p = $_POST['ids_p'];
$rs = $this->ppx->get_ppx_by_id($id_p);
$ppx_value = $_POST['p_ppx'];
$this->ppx->update_ppx(array("id"=>$id_p),array("ppx_r"=>$ppx_value));
if($_POST['p_ppx']):
echo "done: ";
print_r($_POST['ids_p']);
echo "-";
print_r($_POST['p_ppx']);
return true;
endif;
}
because every form has the same id="prod_upd".
test this
<script>
$(function(){
$(".prod_upd").submit(function(){
var $this = $(this), dataString = $this.serialize();
$.ajax({
type: "POST",
url: "<?=PREFIX?>admin/update/change_ppx3/",
data: dataString,
success: function(data){
console.log(data);
$this.find('.dd').html(data);
}
});
return false;
});
});
</script>
<?$i=0;if(count($PPX) > 0)foreach($PPX as $item){$i++;?>
<form name="prod_upd" class="prod_upd" method="post" >
<input type="text" name="p_ppx" size="8" value="<?= number_format($item['p_ppx'],0,'','')?>" class="i_ppx">
<input type="hidden" name="ids_p" size="8" value="<?=$item['id']?>" class="i_ppx">
<input type="submit" class="submit45" value="Save4" />
<div class="dd" style="float: left;">hello</div>
</form>
<?}else{?>
<div class="no_data">Nothing here</div>
<?}?>

Categories

Resources