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>'
Related
I have a page with two registration forms individual and business type and individual type form is set as default the other form is hidden, it works fine. but when I switch it to second form and click on submit button it submits second form but returns to first form after submition even on errors it return to first form.
I want it to stay on second form on errors and after submition.
Here is my php :
if (isset($_POST["btnRegister"])) {
echo "Done";
}elseif (isset($_POST["btnbusiness"])) {
echo "Done";
}
HTML and js codes in my page:
function swapConfig(x) {
var radioName = document.getElementsByName(x.name);
for(i = 0 ; i < radioName.length; i++){
document.getElementById(radioName[i].id.concat("Settings")).style.display="none";
}
document.getElementById(x.id.concat("Settings")).style.display="initial";
}
<div class="col-10 clmiddle">
<label for="production"><b>Individual</b></label>
<input type="radio" onchange="swapConfig(this)" name="urlOptions" id="production" checked="checked" />
<label for="development"><b> Business</b></label>
<input type="radio" onchange="swapConfig(this)" name="urlOptions" id="development" />
</div>
First Form :
<div id="productionSettings" class="col-12">
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<div class="col-6">
<input type="text" class="form-control" name="fname" placeholder="Name..." required>
<button type="submit" name="btnRegister" class="btn btn-primary right">Send</button>
</div>
</form>
</div>
Second Form :
<div id="developmentSettings" style="display:none" class="col-12">
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<div class="col-6">
<input type="text" class="form-control" name="fname" placeholder="Name..." required>
<button type="submit" name="btnbusiness" class="btn btn-primary right">Send</button>
</div>
</form>
</div>
EDIT: I changed JS to php, Here is the solution.
PHP codes (which get url):
$path = $_SERVER['REQUEST_URI'];
$Aurl = explode(",",$path);
for ($i=0; $i<count($Aurl);$i++){
$Burl = str_replace("?", "/", trim($Aurl[$i]));
}
$url = htmlspecialchars(basename($Burl));
$FormPostUrl = basename($path);
Html part :
Checkbox :
<div class="col-10 clmiddle" style="margin-top: 20px;">
<label for="production"><b>Individual</b></label>
<input type="checkbox" value="<?php echo htmlspecialchars("register.php"); ?>" name="checket"
onClick="if (this.checked) { window.location = this.value; }" <?php if($url === htmlspecialchars("register.php")){ echo 'checked="checked"';}?>>
<label for="development"><b>Business</b></label>
<input type="checkbox" value="<?php echo htmlspecialchars("register.php?business");?>"
name="checket"
onClick="if (this.checked) { window.location = this.value; }" <?php if($url === htmlspecialchars("business")){ echo 'checked="checked"';}?>>
</div>
First Form :
<?php if($url === htmlspecialchars("register.php")){?>
<div id="productionSettings" class="col-12">
<form action="<?php echo htmlspecialchars($FormPostUrl); ?>" method="post">
<div class="col-6">
<input type="text" class="form-control" name="fname" placeholder="Name..." required>
<button type="submit" name="btnRegister" class="btn btn-primary right">Send</button>
</div>
</form>
</div>
Second form:
<?php } elseif($url === htmlspecialchars("business")){ ?>
<div id="developmentSettings" class="col-12">
<form action="<?php echo htmlspecialchars($FormPostUrl); ?>" method="post">
<div class="col-6">
<input type="text" class="form-control" name="fname" placeholder="Name..." required>
<button type="submit" name="btnbusiness" class="btn btn-primary right">Send</button>
</div>
</form>
</div>
<?php } ?>
You can use PHP to control whether display:none is added to your divs or not. Use an if statement (or a ternary operator might be neater syntax in the context) to make the decision about what to echo. Since the default is to display the production settings form, we only need to check whether the other form has been submitted or not, in order to know whether to change that.
e.g. something like this (untested):
<input type="radio" onchange="swapConfig(this)" name="urlOptions" id="production" <?php echo (isset($_POST["btnRegister"]) ? "" : 'checked="checked"'); ?> />
and
<input type="radio" onchange="swapConfig(this)" name="urlOptions" id="development" <?php echo (isset($_POST["btnRegister"]) ? 'checked="checked"' : ""); ?> />
and
<div id="productionSettings" class="col-12" <?php echo (isset($_POST["btnbusiness"]) ? "style='display:none'" : ""); ?>>
and
<div id="developmentSettings" class="col-12" <?php echo (isset($_POST["btnbusiness"]) ? "" : "style='display:none'"); ?>>
P.S. Unless you've massively simplified these forms for the purpose of your example, they appear to be basically identical. It's questionable whether you actually need two separate forms at all. The only difference appears to be the choice between "individual" and "business" - that could be handled by a single form with a radio button to choose the type, which would then simplify how you handle the postback as well, and reduce the amount of duplicated code and HTML. Of course if you're actually capturing more distinct fields for these forms than you've shown, then these remarks don't really apply.
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.
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.
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.
Stumped, var-dump($_POST) always returns array[0] {} PHP mail though always succeeds. Variables in html side are what I expect when viewed in the debugger. Fails with both register_globals on and off.
<!-- html code (in contact.php) -->
<form name="hhcform" method="POST" action="sendmail.php" onsubmit="return ValidateForm();" enctype="text/plain">
First Name: <input type="text" name="firstname" value="" size="25">
<span id="firstnameErr" style="color:red">*</span>
<br><br>
Last Name: <input type="text" name="lastname" value="" size="25">
<span id="lastnameErr" style="color:red">*</span>
<br><br>
Email Address: <input type="text" name="emailaddress" value="" size="25">
<span id="emailErr" style="color:red">*</span>
<br><br>
Select a Topic: <span id="topicErr" style="color:red">*</span><br>
<div class="radio-block">
<input type="radio" name="topic" value="Insurance"> Accepted Insurance<br><br>
<input type="radio" name="topic" value="Hours"> Office Hours<br><br>
<input type="radio" name="topic" value="Refills"> Prescription Refills<br><br>
<input type="radio" name="topic" value="Patients"> Accepting New Patients<br><br>
<input type="radio" name="topic" value="Website"> Website Issues<br><br>
<input type="radio" name="topic" value="Other"> Other<br><br>
</div>
Comments: <span id="commentErr" style="color:red">*</span><br>
<textarea name="comments" rows="10" cols="25"></textarea><br><br>
<input type="submit" value="Send">
<input type="reset" value="Reset" onclick="ClearErrors();"><br><br>
</form>
PHP code (in sendmail.php)
<?php
var_dump($_POST);
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['emailaddress'];
$topic = $_POST['topic'];
$comments = $_POST['comments'];
$recipient = "emailaddress#domainbame.com";
$mailheader = "From: " . $email . "\r\n";
if(mail($recipient, $topic, $comments, $mailheader))
{
echo "Email Sent, Thank You!" . " -" . "<a href='contact.php'
style='text-decoration:none;color:#ff0099;'> Return to Contact Us Form</a>";
}
else
{
echo "Email failed to send" . "-" . "<a href='contact.php'
style='text-decoration:none;color:#ff0099;'> Return to Contact Us Form</a>";
}
?>
Take out
enctype="text/plain" in the form, this should fix the issue.
The issue might be with your enctype
enctype="text/plain"
Try
enctype="multipart/form-data"
instead, unless you have a good reason for using text/plain.