function add_comment(ele) {
event.preventDefault();
var username = "<?php echo $current_user; ?>";
var user_id = "<?php echo $current_user_id; ?>";
var post_id = $(ele).data('id');
var comments = $(ele).parent(".comment-section").find(".comment").val();
alert(comments);
if (username == "") {
alert("Please Log in to Star the Post");
window.location = "http://tobbyandscooby.com/log.php";
return;
}
$.ajax({
type: 'POST',
url: 'add_comment.php',
data: {
postid: post_id,
uname: username,
uid: user_id,
comment: comments
},
success: function(response) {
//alert("Successfully Comment is Added! ");
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="comment-section">
<textarea id="<?php echo $post_id; ?>" class="comment" value="" data-id="<?php echo $post_id; ?>"></textarea>
<button id="btn" class="btn-default" data-id="<?php echo $post_id; ?>" onclick="add_comment(this);">Comment</button>
<div class="comment-show"></div>
</div>
<?php
include("connect.php");
$username = $_POST['uname'];
$post_id = $_POST['postid'];
$user_id = $_POST['uid'];
$comments = $_POST['comment'];
$sql = "INSERT INTO comments (user_id,username,post_id,comment) VALUES ($user_id,'$username',$post_id,'$comment')";
$result = $db->query($sql);
?>
I am trying to make a comment system with Ajax. I have done similar thing like favourite, down vote, upvote with Ajax. But now with this above code, I couldn't enter the data into the DB and also on clicking comment button the page refreshes even though I have used *preventDefault();
I know I have made some mistake but couldn't debug it. Also please suggest me how to add the entered comment into div .comment-show using the success in ajax.
**NOTE: I could get the alert(comments); working when preventDefault(); function is removed! I have added the XHR requests for other elements which are working fine! **
The problem is the preventDefault().
You now pass this with that function call in onClick.
To solve it, make the button a submit-button by adding <button type="submit" ..
and pass event with your function call: ...onClick="add_comment(event);"
// complete line:
<button type="submit" id="btn" class="btn-default" data-id="<?php echo $post_id; ?>" onclick="add_comment(event);">Comment</button>
But now you need to rewrite pieces of the function, because ele is now the event, not the element anymore:
Change every $(ele) to $('#id')
And obviously in the beginning of the function the variable name for the passed-in event needs to match:
function add_comment(e) { // whatever you wanna name it, e has to be the same
e.preventDefault(); // as this e
Another solution would be to keep the button just a normal button, remove the onClick there, and add onSubmit="add_comment(event);" to your <form..>
Related
I am building a basic commenting system for a website: Comments can be made and users can reply on every comment. I am using ajax for submitting and retrieving/displaying the comments and replies. I have successfully coded the comments part, but need assistance on the replies part.
Every comment stored in the database has a unique id (comment_id) associated with it. And I use that id to associate replies to each respective comment.
The form for the comments, which is in index.php:
<div id="showComments"></div> <!--div where comments are inserted by AJAX-->
<div style="text-align:center;">
<form action="" method="post" id="commentForm">
<textarea name="comment" id="comment" rows="1"></textarea><BR>
<button type="submit" name="new_comment" onClick="submitComment()">Comment</button>
</form>
<div id="message"></div> <!--div where a status (comment submitted successfully or failed) is inserted by AJAX-->
</div>
The JavaScript for submitting the comment and displaying the comments, also in index.php.
<script>
$(document).ready(function() {
showComments();
});
function submitComment(){
var commentText = document.getElementById('comment').value;
var commentString = 'comment=' + commentText;
event.preventDefault();
$.ajax({
url: "insert_com.php",
method: "POST",
data: commentString,
dataType: "JSON",
success: function(response) {
if (!response.error) {
$("#commentForm")[0].reset();
$("#message").html(response.message);
showComments();
} else if (response.error) {
$("#message").html(response.message);
}
}
});
}
function showComments() {
$.ajax({
url: "get_com.php",
method: "POST",
success: function(response) {
$("#showComments").html(response);
}
});
}
</script>
The file insert_com.php, which submits the comment to the database, to where AJAX posts in the submitComment() function:
<?php
if(!empty($_POST["comment"])){
$new_com_date = date('Y-m-d H:i:s');
$insertComment = "INSERT INTO comments (text, date) VALUES ('".$_POST["comment"]."', '".$new_com_date."')";
mysqli_query($connect, $insertComment) or die("database error: ". mysqli_error($connect));
$message = '<label>Comment posted Successfully.</label>';
$status = array(
'error' => 0,
'message' => $message
);
} else {
$message = '<label>Error: Comment not posted.</label>';
$status = array(
'error' => 1,
'message' => $message
);
}
echo json_encode($status);
?>
And the file get_com.php, which retrieves and displays the comments but also retrieves the replies and contains the form for submitting the replies
<?php
require 'php/connect.php';
$comment = mysqli_query($connect, "SELECT * FROM `comments` ORDER BY `date` DESC");
$string ="";
foreach($comment as $item) {
$date = new dateTime($item['date']);
$date = date_format($date, 'M j, Y | H:i:s');
$comment = $item['text'];
$comment_id = $item['id'];
$string .= '<div style="text-align:center;">'
.'<div id="'.$comment_id.'" style="text-align:center;">'
.'<span><b>'.$comment.'</b></span> '
.'<span><b>'.$date.'</b></span> '
.'<span><b>'.$comment_id.'</b></span>'
.'</div>';
$reply = mysqli_query($connect, "SELECT * FROM `replies` WHERE `comment_id`='$comment_id' ORDER BY `date` DESC");
foreach($reply as $com) {
$reply_date = new dateTime($com['date']);
$reply_date = date_format($reply_date, 'M j, Y | H:i:s');
$reply_com = $com['text'];
$com_id = $com['comment_id'];
$string.= '<div>'
.'<span>'.$reply_com.'</span> '
.'<span class="time">'.$reply_date.'</span> '
.'<span><b>'.$com_id.'</b></span>'
.'</div>';
}
$string .=
'<div>'
.'<form action="" method="post" id="replyForm">'
.'<textarea name="new-reply" id="new-reply" rows="1"></textarea>'
.'<input type="hidden" id="com_id" name="com_id" value="'.$comment_id.'"/>'
.'<button type="submit" id="form-reply" name="new_reply" onClick="submitReply()">Reply</button> '
.'<span><b>'.$comment_id.'</b></span>'
.'</form>'
.'<span id="replymessage"></span>'
.'</div>'
.'</div>'
.'<hr style="width:300px;">';
}
echo $string;
?>
Now, here is where the problem comes in. I want to use AJAX to submit a reply to a particular comment with an id $comment_id. I want to get this id from the hidden input contained in the reply form (The form with id replyForm.
I wrote the following JavaScript to retrieve the id belonging to a particular comment:
<script>
function submitReply(){
var replyText = document.getElementById('new-reply').value; console.log(replyText);
var commId = document.getElementById('com_id').value; console.log(commId);
event.preventDefault();
...
</script>
As you can see, I log the form text (the reply) and the comment id to the console to see whether I am capturing the correct data, but it always returns the id of the last comment submitted. (i.e the reply form works for the last comment. The JavaScript logs the correct text and comment id for a reply on the last comment, but for all other replies it returns the text of the reply on the last comment and the id of the last comment.
I know it's quite a lot of code, so if anyone more experience could assist me it would certainly be appreciated.
You have more than one element with id="com_id". id should be unique. What you can do is when you are generating the DOM in get_com.php, instead of
'<input type="hidden" id="com_id" name="com_id" value="'.$comment_id.'"/>'
'<button type="submit" id="form-reply" name="new_reply" onClick="submitReply()">Reply</button> '
You can call submitReply() with the right ID, like so:
'<button type="submit" id="form-reply" name="new_reply" onClick="submitReply('.$comment_id.')">Reply</button> '
Then, the comment ID would be the argument of your submitReply method and you wouldn't need to read it from the input field.
<script>
function submitReply(commId){
var replyText = document.getElementById('new-reply').value;
console.log(replyText);
console.log(commId);
event.preventDefault();
...
</script>
Your <textarea> has the same issue as well.
I suggest to assign a unique ID to your <textarea> as well, something like "reply-'.$comment_id.'". Then, when submitReply(comment_id) gets called, you know which comment ID is the call for, so you can construct the unique ID for the exact same textarea, and get the value of the desired element.
<script>
function submitReply(commId){
var replyText = document.getElementById('reply-' + commId).value;
console.log(replyText);
console.log(commId);
event.preventDefault();
...
</script>
I posted two javascript variables to a php file aswell as a html form using Ajax separately. I want to use the two javascript variables with the posted form values but I'm not sure how to go about this.
<script>
$(document).ready(function() {
var aucid = "<?php echo $auctionID; ?>";
var userid = "<?php echo $userID; ?>";
$.ajax({
url: "JqueryPHP/HighestBid.php",
method: "POST",
data: {'auctionid': aucid, 'userid' : userid },
success: function (result) {
$('#price').html(result);
}
});
$('form').bind('submit', function (event) {
event.preventDefault();// using this page stop being refreshing
$.ajax({
type: 'POST',
url: 'JqueryPHP/HighestBid.php',
data: $('form').serialize(),
success: function () {
alert('form was submitted');
}
});
});
});
I posted the two javascript variables separately to the form.
<form>
<input type="number" min="<?php echo $startingprice ?>" step="any" style="width: 10em;" size="35" name="newbid" id="newbid" tabindex="1" class="form-control" placeholder="New Bid €" value="" required>
<input type="submit" name="submit" id="submit" tabindex="2" class="form-control btn btn-login" style="width: 14em" value="submit">
</form>
<h4 class="price">Highest bid : <span id="price"></span></h4>
When I echo the value of userID into the span class, you can see it has a value of 2.
//JqueryPHP/HighestBid.php'
$auctionid;
$userID;
$auctionid = $_POST['auctionid'];
$userID = $_POST['userid'];
echo $userID;
if (isset($_POST['newbid']))
{
$newbid=$_POST['newbid'];
$conn = new mysqli('localhost', 'root', '', 'auctionsite');
$sql = 'INSERT INTO auction (useridhighestbid)VALUES("'.$userID.'")';
if(#$conn->query($sql)){ //execute the query and check it worked
return TRUE;
}
}
however when I try use the userID when the form is submitted and try insert it into the database for testing purposes, the value is 0.
How would I go about posting the form value with the javascript variables so I can use an update statement to update my database?
Set two hidden inputs to save aucid and userid like this:
<form>
<input type="number" min="<?php echo $startingprice ?>" step="any" style="width: 10em;" size="35" name="newbid" id="newbid" tabindex="1" class="form-control" placeholder="New Bid €" value="" required>
<input type="submit" name="submit" id="submit" tabindex="2" class="form-control btn btn-login" style="width: 14em" value="submit">
<input name='aucid' style="display:none"/>
<input name='userid' style="display:none"/>
</form>
<script>
$(document).ready(function() {
$("input[name='aucid']").val("<?php echo $auctionID; ?>");
$("input[name='userid']").val("<?php echo $userID; ?>");
.......................
});
</script>
Send your form to a php script. When the user logs in, retrive his ID from DB and put it in session like this
switch(isset($_POST['login'])):
case 'Register':
$email = htmlspecialchars(trim($_POST['em']), ENT_QUOTES, 'UTF-8');
$password = htmlspecialchars(trim($_POST['pw']), ENT_QUOTES, 'UTF-8');
// check if the combination fname/lname/email is already used
include('./Models/log_check.php');
unset($_SESSION['ID'],$_SESSION['role']);
$_SESSION['ID'] = $row['ID'];
$_SESSION['role'] = $row['role'];
So you can use ID in your Model/query:
<?php
/* Jointure sama RDV des vets */
$query =
"SELECT
appointment.start,
appointment.app_day,
patients.pet_name,
patients.breed,
patients.ID,
clients.last_name,
clients.first_name,
appointment.type,
appointment.canceled
FROM appointment
JOIN patients
JOIN clients
WHERE clients.users_ID = patients.owner_ID
AND patients.ID = appointment.patients_ID
AND appointment.vets_ID = (SELECT ID FROM vets WHERE users_ID = :ID)
AND appointment.canceled = 'n'
AND WEEK(appointment.app_day) = WEEK(:date)
ORDER BY appointment.app_day,appointment.start";
$query_params = array(':ID' => $_SESSION['ID'],
':date' => $date);
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}catch(PDOException $ex){
die("Failed to run query: " . $ex->getMessage());
}
?>
Insert instead of SELECT
Assuming you parsed the variables correctly, you can use:
$_POST['JavaScript_variable_name_goes_here'];
or
$_GET['JavaScript_variable_name_goes_here'];
to retrieve the variables in a PHP format, depending on your AJAX method.
A direct example from your AJAX function would be:
<?php $auctionId=$_POST['auctionid']; ?>
However, what I would encourage you to do, is that once a user is logged in, you set their userId as a session variable that you can use wherever the user "goes". That way, you are not parsing a crucial data element through JavaScript, which is handled client side, meaning that it's fully editable by the user through the use of a browsers dev tools. The same goes for the auctionId. I would recommend a php session variable logic for the exact same reasons. You can always overwrite the auctionId session variable with another auctionId depending on which auction is "in use".
Another good reason to why setting userId as a session variable, is that you will never have any trouble accessing the variable anywhere, as long as you remember to set the following at the very beginning of your PHP files:
<?php session_start(); ?>
The PHP/SQL syntax for the mysqli_* extension would then be the following:
$conn=mysqli_connect("localhost", "root", "", "auctionsite");
$sql="INSERT INTO auction SET useridhighestbid='$userID'";
mysqli_query($conn, $sql);
Let me know if you need anything elaborated, or if you run into any other problems.
You can append the data with the serialize like this in ajax call
data: $("#form_id").serialize() + '&xyz=' + xyz
I am developing a webpage where multiple posts from the Database is shown one by one in a single page much like twitter or facebook.
I need to use Ajax for comments and likes. The comment system should be nested as well.
The problem I am having is each post is having a unique post_id and I need to transfer it through Ajax for inserting the comments into the DB.
The below HTML is inside a PHP for loop for getting the posts from Database. So I have given post_id as every comment element's id to get the unique post comment.
<script>
function addcomment(abc) {
var temp1 = abc;
var post_id = temp1.value; // POST ID
var comment = document.getElementById(post_id).value;
$.ajax({
type: "POST",
url: "addcomment.php",
data: {
post_id:post_id,
comment:comment
},
success: function(response) {
document.getElementsByClassName(post_id).innerHTML = response;
}
});
}
</script>
<div class="comment_section" id="comment_section">
<textarea type="text" id="<?php echo($post_id); ?>" placeholder="comment Here..." value=""></textarea>
<button id="comment_button" value="<?php echo ($post_id); ?>" onclick="return addcomment(this);">Comment</button>
<br>
<span class="<?php echo($post_id); ?>"></span>
</div>
And the addcomment.php looks like this:
<?php
include("connect.php");
$postid = $_POST['post_id'];
$comment = $_POST['comment'];
$sql1 = "INSERT INTO comments (name,comment) VALUES ('$postid','$comment')";
$result = $db->query($sql1);
$sql = "SELECT * FROM comments ORDER BY id DESC LIMIT 0,1";
$result1 = $db->query($sql);
while($row = $result1->fetch_assoc()) {
$post = $row['name'];
$comment_op = $row['comment'];
?>
<?php echo $comment_op; ?>
<br>
<?php echo $post; ?>
<?php } ?>
How can I get the comment when the Comment button clicked and store it in the DB and return the Comment below the comment area using AJAX ?
For display comments on specific post first you create comment section and use
<section id="comments-post_id"></section>
when you successfully add comment via above ajax request code get the response and create comment html and append in your comment section.
$("#comments-post_id").html($response);
make sure you have already create your comment HTML in controller or in ajax file where you get the response.
and for the rendering all post data user inside loop or recursive function to get all comments of your specific post
Need more help feel free and ask :)
I´m trying to call a function into a href, my function is on functions.php
and my href is on views/something.php
so, this is my function:
function discount($connection, $us){
$discount = $conexion->prepare("UPDATE postule SET seen = 1 WHERE id = $us");
$discount->execute();
return $discount;
}
and my link button is on an <li> (not in a form):
<?php foreach ($total_notu as $notu) : ?>
<li><a onClick="<?php discount() ?>" href="notificaciones.php"> Notificaciones <span class="badge "><?php echo "$notu[0]"; ?></span></a></li>
<?php endforeach; ?>
(Do not pay attention to the foreach)
You'll need to change this to use an ajax call or form post to call the PHP function.
Here's a really basic example which should point you in the right direction
discount.php
<?php
// Load $connection from somewhere
// Get user, it's better to get this from a cookie or session rather than GET
$user = $_GET['user']
$discount = $connection->prepare("UPDATE postule SET seen = 1 WHERE id = :user");
$discount->bindParam(':user', $user);
$result = $discount->execute();
// Throw error if something went wrong with the update, this will cause $.ajax to use the error function
if (!$result) {
http_response_code(500);
}
html, assuming $notu[0] contains the user id
<?php foreach ($total_notu as $notu) : ?>
<li><a onClick="return callDiscount('<?php echo "$notu[0]"; ?>');" href="#"> Notificaciones <span class="badge "><?php echo "$notu[0]"; ?></span></a></li>
<?php endforeach; ?>
js, requires jquery
function callDiscount(user_id)
{
// Perform ajax call to discount.php
$.ajax({
url: '/discount.php?user=' + user_id,
error: function() {
alert('An error occurred');
},
success: function(data) {
// Redirect user to notificaciones.php
document.location = '/notificaciones.php';
}
});
// Prevent link click doing anything
return false;
}
Okay So I have a div on my page that has some code for display option groups in a select input. And then on the other side displaying the options in that group after the selection is made. My html/php code for this is below:
<div class="row">
<div class="col-lg-6">
<label class="control-label" for="productOptions">Select your
product options</label> <select class="form-control" id=
"productOptions">
<option>
Select an Option Group
</option><?php foreach($DefaultOptions as $option): ?>
<option value="<?php echo $option['GroupID']; ?>">
<?php echo $option['GroupName']; ?>
</option><?php endforeach; ?>
</select>
</div>
<div class="col-lg-6" id="groupOptions">
<label class="control-label">Group Options</label>
<?php if($GroupOptions): ?>
<?php foreach ($GroupOptions as $optionValue): ?>
<?php echo $optionValue['optionName']; ?> <?php endforeach; ?>
<?php endif; ?>
</div>
</div>
By default on the original page load, $GroupOptions does not exist in the form, because it is set after the user selects the Group they wish to choose from. I call the php script by using ajax to avoid page reload
$("#productOptions").change(function(){
var GroupID = $(this).val();
var dataString = 'GroupID=' + GroupID;
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "#",
data: dataString,
success: function() {
$("#groupOptions").html(dataString);
}
});
return false;
});
Then the ajax goes to a php call that gets the options that match the groups id in the database.
if(isset($_POST['GroupID']))
{
$GroupID = $_POST['GroupID'];
$sql = "SELECT * from `KC_Options` WHERE GroupID=$GroupID";
$GroupOptions = $db->query($sql);
}
Now I want to refresh the div #GroupOptions to display the results from the query above, and make <?php if($GroupOptions): ?> set to true.
I managed to refresh the div with $("#groupOptions").html(dataString); in the success function of the ajax call. But that only returns well the dataString. (obviously). Is there a way to truly refresh just the div. Or a way to pass the info from the php call into the success function?
UPDATE:
You have 4 problems in your current code:
Problem #1 and Problem #2 - In your separate PHP script you are not echoing anything back to the Ajax. Anything you echo will go back as a variable to the success function. Simply the add echo statement(s) according to the format you want. Your 2nd problem is that you are trying to echo it in the HTML part, where $GroupOptions does not even exist (the Ajax simply returns an output from the PHP script, it's not an include statement so your variables are not in the same scope).
if(isset($_POST['GroupID']))
{
$GroupID = $_POST['GroupID'];
$sql = "SELECT * from `KC_Options` WHERE GroupID=$GroupID";
$GroupOptions = $db->query($sql);
//this is where you want to iterate through the result and echo it (will be sent as it to the success function as a variable)
if($GroupOptions):
foreach ($GroupOptions as $optionValue):
echo $optionValue['optionName'];
endforeach;
endif;
}
In your Ajax, add a variable named data to the success function, which will receive the output from the PHP script. Also notice that your url is incorrect, you need to post to an actual external file such as my_custom_script.php.:
$.ajax({
type: "POST",
url: "your_external_script.php",
data: dataString,
success: function(data) {
if (data && data !== '') {
//data will equal anything that you echo in the PHP script
//we're adding the label to the html so you don't override it with the new output
var output = '<label class="control-label">Group Options</label>';
output += data;
$("#groupOptions").html(output);
} else {//nothing came back from the PHP script
alert('no data received!');
}
}
});
Problem #4 - And on your HTML, no need to run any PHP. Simply change:
<div class="col-lg-6" id="groupOptions">
<label class="control-label">Group Options</label>
<?php if($GroupOptions): ?>
<?php foreach ($GroupOptions as $optionValue): ?>
<?php echo $optionValue['optionName']; ?> <?php endforeach; ?>
<?php endif; ?>
</div>
to
<div class="col-lg-6" id="groupOptions">
</div>
Hope this helps
You have to take the response in yout success callback function and actually give a response in your oho function
$("#productOptions").change(function(){
var GroupID = $(this).val();
var dataString = 'GroupID=' + GroupID;
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "#",
data: dataString,
success: function(dataString) { //take the response here
// convert dataString to html...
$("#groupOptions").html(newHtml);
}
});
return false;
});
PHP:
if(isset($_POST['GroupID']))
{
$GroupID = $_POST['GroupID'];
$sql = "SELECT * from `KC_Options` WHERE GroupID=$GroupID";
$GroupOptions = $db->query($sql);
echo json_encode($GroupOptions ); //give a response here using json
}