multi form ajax php social comment system - javascript

I have a lot of these forms that I post with PHP. They are under every article in my page, but when I submit the form with these ajax functions it only sends to the first form of the page. Why? I want send these form separately what am I doing wrong?
<script type="text/javascript" >
$(function() {
$(".submit").click(function()
{
var name = $("#name").val();
var comment = $("#comment").val();
var post_id = $("#post").val();
var dataString = 'name='+ name + '&comment=' + comment+ '&post_id=' + post_id;
if(name=='' || comment=='')
{
alert('Please Give Valid Details');
}
else
{
$("#flash").show();
$("#flash").fadeIn(400).html('<img src="images/loading.gif" />Loading Comment...');
$.ajax({
type: "POST",
url: "commenti.php",
data: dataString,
cache: false,
success: function(html){
$("ol#update").append(html);
$("ol#update li:last").fadeIn("slow");
$("#flash").hide();
}
});
}return false;
});
});
<script>
<ol id="update" class="timeline">
</ol>
<div id="flash"></div>
<div >
<form action="#" method="post">
<input type="hidden" id="post" value="<?php echo $post_id; ?>"/>
<input type="hidden" id="name" value="<?php echo $username; ?>"/>
<textarea id="comment"></textarea><br />
<input type="submit" class="submit" value=" Submit Comment " />
</form>
</div>
<ol id="update" class="timeline">
</ol>
<div id="flash"></div>
<div >
<form action="#" method="post">
<input type="hidden" id="post" value="<?php echo $post_id; ?>"/>
<input type="hidden" id="name" value="<?php echo $username; ?>"/>
<textarea id="comment"></textarea><br />
<input type="submit" class="submit" value=" Submit Comment " />
</form>
</div>
<ol id="update" class="timeline">
</ol>
<div id="flash"></div>
<div >
<form action="#" method="post">
<input type="hidden" id="post" value="<?php echo $post_id; ?>"/>
<input type="hidden" id="name" value="<?php echo $username; ?>"/>
<textarea id="comment"></textarea><br />
<input type="submit" class="submit" value=" Submit Comment " />
</form>
</div>

First of all, as has been said in the comments, don't use repetead IDs. If you don't intend to use Ids as a unique identifier, use classes.
<ol class="timeline update">
<div id="flash"></div>
<div >
<form action="#" id="form" method="post">
<input type="hidden" class="post" value="<?php echo $post_id; ?>"/>
<input type="hidden" class="name" value="<?php echo $username; ?>"/>
<textarea class="comment"></textarea><br />
<input type="submit" class="submit" value=" Submit Comment " />
</form>
</div>
</ol>
In your javascript code, you are trying to get the id name with var name = $('#name'), right? What name?
Also, try to send your requeste with an array rather than a string.
Something like this:
$(".submit").click(function()
{
var name = $(this).parents('form:input.name').val();
var comment = $(this).parents('form:input.comment').val();
var post_id = $(this).parents('form:input.post').val();
var data = {'name': name,
'comment': comment,
'post_id':post_id},
$.ajax({
type: "POST",
url: "commenti.php",
data: data,
success: function(html){
//do stuff
}
}
Access your variable in PHP with $_POST['varName'];
Hope it helps.

Related

Can I target a specific form for commenting with jquery

I have created a news system on my web page where I use while loop to echo my news on a page. With news I created a form for news where I target it by name and I want to use jquery to process the results. When I use php it works fine but I want to avoid reloading page with submitting form and immediate post comment to page.
my form looks like this:
<form action="" method="post" enctype="multipart/form-data" class="comments" id="comments">
<textarea id="comment_area" class="comment-area" name="comment" placeholder="Dodajte svoj komentar tukaj..."></textarea>
<input type="hidden" id="news_id" name="news_id" value="' . $row['news_id'] . '">
<input type="hidden" id="type" name="type" value="0">
<input type="submit" id="comment_btn" class="comment-btn" name="comments<php echo $row['news_id'] ?>" value="Objavi">
</form>'
my php code looks like this:
if (isset($_POST['comments' . $row['news_id'] . '']) === true && empty($_POST['comment']) === false) {
global $user_data;
$user_id = $user_data['user_id'];
$connect_id = $_POST['news_id'];
$type = $_POST['type'];
$time = date('Y-m-d H:i:s');
$comment = $_POST['comment'];
$comment = sanitize($comment);
mysql_query("INSERT INTO `comments` (`user_id`, `connect_id`, `type`, `time`, `comment`) VALUES ('$user_id', '$connect_id', '$type', '$time', '$comment')");
}
If I try to do somethink like this:
$(".comment-btn").click(function(e) {
e.preventDefault();
var text = $('.comment-area').val();
console.log(text);
$('.comment-area').val('');
});
It targets only the form where is the first news and doesn't target all the forms.
Is there any way to do this differently???
Thanks for helping.
You could try something like the following:
$(".comment-btn").each(function(){
$(this).click(function(e) {
e.preventDefault();
var commentArea = $(this).siblings(".comment-area");
var text = commentArea.val();
console.log(text);
commentArea.val('');
});
});
The problem is that while this $(".comment-btn") returns an array of all the button in the forms you mentioned, this $(".comment-btn").click(... attaches a click event handler only for the first item of the array.
$(function(){
$(".comment-btn").each(function(){
$(this).click(function(e){
e.preventDefault();
var commentArea = $(this).siblings(".comment-area");
var text = commentArea.val();
console.log(text);
commentArea.val('');
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" method="post" enctype="multipart/form-data" class="comments" id="comments">
<textarea id="comment_area" class="comment-area" name="comment" placeholder="Dodajte svoj komentar tukaj..."></textarea>
<input type="hidden" id="news_id" name="news_id" value="' . $row['news_id'] . '">
<input type="hidden" id="type" name="type" value="0">
<input type="submit" id="comment_btn" class="comment-btn" name="comments<php echo $row['news_id'] ?>" value="Objavi">
</form>'
<form action="" method="post" enctype="multipart/form-data" class="comments" id="comments">
<textarea id="comment_area" class="comment-area" name="comment" placeholder="Dodajte svoj komentar tukaj..."></textarea>
<input type="hidden" id="news_id" name="news_id" value="' . $row['news_id'] . '">
<input type="hidden" id="type" name="type" value="0">
<input type="submit" id="comment_btn" class="comment-btn" name="comments<php echo $row['news_id'] ?>" value="Objavi">
</form>'
<form action="" method="post" enctype="multipart/form-data" class="comments" id="comments">
<textarea id="comment_area" class="comment-area" name="comment" placeholder="Dodajte svoj komentar tukaj..."></textarea>
<input type="hidden" id="news_id" name="news_id" value="' . $row['news_id'] . '">
<input type="hidden" id="type" name="type" value="0">
<input type="submit" id="comment_btn" class="comment-btn" name="comments<php echo $row['news_id'] ?>" value="Objavi">
</form>'
You could use jQuery on function to bind "click" event to all buttons with comment-btn class. However, it'll be important to then identify which comment-area you want to refer to. If that is not done, it'll simply erase the values of all fields / textareas with class comment-area.
$(".comment-btn").on("click", function(e) {
e.preventDefault();
var text = $(this).parent().find('.comment-area').val();
console.log(text);
$(this).parent().find('.comment-area').val('');
});
Working example with the only change being that input type for buttons is changed from "submit" to "button":
https://jsfiddle.net/L87n4Ljo/
Likewise, if you'd like to submit a particular form when the button is clicked, you'll have to do so by specifically identifying that form by using parent() function.
Try this, here we are blocking the default form submit which i think you will need if you don't want to reload the page.
$(".comments").on("submit", function(e) {
e.preventDefault();
var text = $(this).find('.comment-area').val();
console.log(text);
$(this).find('.comment-area').val('');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" method="post" enctype="multipart/form-data" class="comments" id="comments">
<textarea id="comment_area" class="comment-area" name="comment" placeholder="Dodajte svoj komentar tukaj..."></textarea>
<input type="hidden" id="news_id" name="news_id" value="' . $row['news_id'] . '">
<input type="hidden" id="type" name="type" value="0">
<input type="submit" id="comment_btn" class="comment-btn" name="comments<php echo $row['news_id'] ?>" value="Objavi">
</form>'

jQuery on click fade in hidden element in while loop

I have a form in while loop which activates when I click on Reply button. This I can do simply but its in while loop and requires a unique ID. With my code its working till now but it works only for the first result. When I click on the other results nothing happens. Even though I have already assigned a unique ID its not working. My code is given below:
jQuery part:
$(document).ready(function() {
$("#reply").on('click', 'a.click', function() {
var rowid = $(this).attr("data-rowid");
$(".reply-comment-holder[data-rowid='" + rowid + "']").fadeToggle(800),
$(this).toggleClass(".reply-comment-holder[data-rowid='" + rowid + "']");
});
});
PHP HTML part:
<?php while($fetch_cmts = $get_cmtq->fetch()){ extract($fetch_cmts); ?>
<div id="reply">Reply</div>
<div class="reply-comment-holder" data-rowid="<?php echo $cmt_id?>" style="display:none;">
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" class="full-width cmtform" id="cmt_form_id_<?php echo $cmt_id?>">
<input type="hidden" name="status_id" value="<?php echo $cmt_id; ?>" id="cmtsid_<?php echo $cmt_id?>" />
<textarea name="comment" placeholder="Give a reply..." class="reply-comment-field commentarea" id="replycomment_<?php echo $cmt_id?>"></textarea>
</form>
</div>
<?php } ?>
Please help with jQuery/Ajax.
HTML
<div class="reply">Reply</div>
<div class="reply-comment-holder" data-rowid="1" style="display:none;">
<form method="post" action="#" class="full-width cmtform" id="cmt_form_id_1">
<input type="hidden" name="status_id" value="1" id="cmtsid_1" />
<textarea name="comment" placeholder="Give a reply..." class="reply-comment-field commentarea" id="replycomment_1"></textarea>
</form>
</div>
<div class="reply">Reply</div>
<div class="reply-comment-holder" data-rowid="2" style="display:none;">
<form method="post" action="#" class="full-width cmtform" id="cmt_form_id_2">
<input type="hidden" name="status_id" value="2" id="cmtsid_2" />
<textarea name="comment" placeholder="Give a reply..." class="reply-comment-field commentarea" id="replycomment_2"></textarea>
</form>
</div>
javascript
$(document).ready(function() {
$(".reply").on('click', 'a.click', function() {
var rowid = $(this).attr("data-rowid");
$(".reply-comment-holder[data-rowid='" + rowid + "']").fadeToggle(800),
$(this).toggleClass(".reply-comment-holder[data-rowid='" + rowid + "']");
});
});
jsbin is listed in comments above.

Post Ckeditor data to mysql

My Ckeditor post variable returns as having the input I need. When I insert it into the column everything inserts, BUT the ckeditor data.
This is my function to insert:
public function SubmitReply() {
$query = <<<SQL
INSERT INTO {$this->tprefix}posts(guid,poster,content,postdate)
VALUES(:guid,:poster,:content,:postdate)
SQL;
$resource = $this->db->db->prepare( $query );
$resource->execute( array (
':guid' => $_POST['guid'],
':poster' => $_POST['poster'],
':content' => htmlspecialchars($_POST['editor1']),
':postdate' => $_POST['postdate'],
));
return $resource->rowCount();
}
And my form has:
<form id="reply" method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="hidden" name="process" id="process" value="DEF_FORUM_SUBMIT_REPLY">
<input type="hidden" name="guid" id="guid" value="<?php DEF_TOPIC_NAME($_GET['topic']); ?>">
<input type="hidden" name="poster" id="poster" value="<?php echo $_SESSION['key']['userid']; ?>">
<input type="hidden" name="postdate" id="postdate" value="<?php echo gmdate('Y-m-d H:i:s'); ?>">
<textarea name="editor1" id="editor1" rows="10" cols="80"></textarea>
</form>
<p style="text-align:center; margin-top:10px;">
<input type="submit" class="btn btn-success" value="Post Reply" id="submit_reply">
</p>
It seems that the post for editor1 actually isn't passing now. I have no clue as to why at this point.

Why doesn't the preventDefault function work always?

I'm trying to create a quiz with PHP and Javascript.
After a user clicked for an answer, an ajax request starts and the result is been given in the response. If it was true, the clicked button gets a 'success' class and if false, a 'wrong' class.
After this the buttons are disabled and the user can click to the next question.
But the problem is, that after one or two questions, the javascript function doesn't work and the default action of the form is being called.
$(document).ready(function(){
// Get the form.
var form = $('#bilderquiz');
// Set up an event listener for the contact form.
$(form).submit(function(e) {
// Stop the browser from submitting the form.
// Serialize the form data.
var formData = $(form).serialize();
// Submit the form using AJAX.
e.preventDefault();
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
, async: false
})
.done(function(response) {
var submittedAnswer = $("input[type=submit][clicked=true]");
var allAnswers = document.querySelectorAll( ".answerButton" );
alert(response);
if(response == 'trueAnswer'){
submittedAnswer.removeClass('wrongAnswer');
submittedAnswer.addClass('trueAnswer');
$(".answerButton").attr('disabled', true);
} else{
submittedAnswer.removeClass('trueAnswer');
submittedAnswer.addClass('wrongAnswer');
$(".answerButton").attr('disabled', true);
}
})
.fail(function(data) {
// Set the message text.
if (data.responseText !== '') {
$(formMessages).text(data.responseText);
} else {
$(formMessages).text('Oops! An error occured and your message could not be sent.');
}
});
});
});
function setClicked(input){
$(input).parents("form").removeAttr("clicked");
$(input).attr("clicked", "true");
}
<div class="answerChar">A</div>
<form id="bilderquiz" action="includes/functions.php" method="post">
<button class="answerButton" type="submit" id="selection" name="selection" value="0" onclick="setClicked(this)">
<?php echo $questionData['answerButtons'][0] ;?>
</button>
</form>
</div>
<div class="col-sm-6">
<div class="answerChar">B</div>
<form id="bilderquiz" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<button class="answerButton" type="submit" id="selection" name="selection" value="1" onclick="setClicked(this)">
<?php echo $questionData['answerButtons'][1];?>
</button>
</form>
</div>
</div>
<div class="row">
<div class="col-sm-6">
<div class="answerChar">C</div>
<form id="bilderquiz" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<button class="answerButton" type="submit" id="selection" name="selection" value="2" onclick="setClicked(this)">
<?php echo $questionData['answerButtons'][2];?>
</button>
</form>
</div>
<div class="col-sm-6">
<div class="answerChar">D</div>
<form id="bilderquiz" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<button class="answerButton" type="submit" id="selection" name="selection" value="3" onclick="setClicked(this)">
<?php echo $questionData['answerButtons'][3];?>
</button>
</form>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<form id="bilderquiz" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<button class="submitButton" type="submit" id="selection" name="selection" value="4" onclick="setClicked(this)">Nächste Frage</button>
</form>
</div>
</div>
My second problem is, that this lines also doesn't work:
submittedAnswer.removeClass('wrongAnswer');
submittedAnswer.addClass('trueAnswer');
Your forms need unique IDs, right now they are all id="bilderquiz"
Or you could use classes.
The php:
<form class="capture-me">...</form>
<form class="capture-me">...</form>
The JS:
$('form.capture-me').on('submit',function(e){ .....

Ajax form submission reloads the page

Page reloads after form submission, and i want it not to reload.
Update: With answers below i came up With the code below. What happens is form submits correctly, but the page reloads.
Before, this line of code worked fine:
$(document).ready(function() {
$('#poll').ajaxForm(function() {
$("#polling_id").load("poll_results.php");
});
});
Today i have added .htaccess to remove .php extensions. Could that have affected this someway?
HTML
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></SCRIPT>
</head>
<div class="polling" id="polling_id">
<br><br>
<form id="poll_form" method="POST" action="process-vote.php" />
<div class="poll_objects">
<input type="hidden" name="o1" value="<?php echo $option1; ?>" />
<input type="hidden" name="o2" value="<?php echo $option2; ?>" />
<input type="hidden" name="o3" value="<?php echo $option3; ?>" />
<span class="footer_font"><input type="radio" name="radio_1" value="<?php echo $option1;?>" id="radio" /><label for="radio"><?php echo $option1;?></label> </span><br><br>
<span class="footer_font"><input type="radio" name="radio_1" value="<?php echo $option2;?>" id="radio2" /><label for="radio2"><?php echo $option2;?></label></span><br><br>
<span class="footer_font"><input type="radio" name="radio_1" value="<?php echo $option3;?>" id="radio3" /><label for="radio3"><?php echo $option3;?></label></span><br><br>
<div class="float_buttons">
<input type="submit" name="submit_vote" value="Vote!" class="button" />
<input type="submit" name="results" value="Poll Results" class="button"/>
</div>
</div>
</div>
</form>
jQuery:
<script>
$(document).ready(function() {
$.ajax({
$('#poll_form').submit(function(e) {
e.preventDefault();
// note where the e comes from.
var a = $(this).serialize();
$("#polling_id").load("poll-results.php");
});
});
});
</script>
It doesn't look like you are capturing an event.
$('#poll_form').submit(function(e) {
e.preventDefault();
// note where the e comes from.
var a = $(this).serialize();
// now do your ajax stuff here.
});
You can also put :
<script>
function validate()
{
...
blablabla
...
return false; // This cause the submit function to be stopped.
}
</script>
<form onClick="validate()">

Categories