Creating a unique variable for data - javascript

Hi guys so i have created a simple comment box for my site now. It works perfectly, however the problem i am having is that i have different pages which are going to require different comment box. I cant seem to figure out how to get the comment box to be unique for every page. So right now my database holds this :
Called comments:
id
comment
comment1
comment_date
Now my idea is that everything was stored into comment, so i added comment1 for other page to store the info. However i have no clue how to edit the php file to get it to work with comment1. Any help on this would be great.
HTML:
<div class="comment_container">
<div class="comments">
<?php
include_once("comments.php");
?>
</div>
<div class="comments_form">
<table>
<tr><td><textarea id="comment_text"></textarea></td>
<td><input type="button" id="comment_process" value="Post Comment"/></td></tr>
</table>
</div>
</div>
JS:
$(document).ready(function() {
$('#comment_process').click(function() {
if ($('#comment_text').val() != "") {
$.post("comments.php?action=post", {
comment: $('#comment_text').val()
}, function(data) {
$('.comments').html(data);
$('#comment_text').val("");
});
}
});
});
PHP:
include_once("connect.php");
function convert ($date) {
$converteddate = date("F j, Y g:ia", strtotime($date." +1day"));
return $converteddate;
}
function getComments(){
$comments = "";
$sql = mysql_query("SELECT * FROM comments") or die(mysql_error());
if(mysql_num_rows($sql) == 0){
$comments = "<div class='each_comment'>There are no comments</div>";
} else {
while($row = mysql_fetch_assoc($sql)){
$comments .= "<div class='each_comment'><small><em>".convert($row['comment_date'])."</em></small><br />".$row['comment']."</div>";
}
}
return $comments;
}
function postComments($comment){
$comment = mysql_real_escape_string(strip_tags($comment));
$sql = mysql_query("INSERT INTO comments (comment, comment_date ) VALUES ('".$comment."', now())");
return true;
}
if((isset($_GET['action'])) && ($_GET['action']== "post")){
postComments($_POST['comment']);
}
echo getComments();
Thanks again for the help

DISCLAIMER
For future visitors:
Don't copy this code, as it has several issues that go beyond answering the question.
What you need to add is an identifyer for the type of comment. (Type could be replaced with something more suitable to your case like 'product', 'user', ... whatever the difference is/what they are related to)
So in your database add that new column:
comments
--------
id
comment
type
comment_date
Now you need to pass around that type through all your calls, and it shall be specified in your 'HTML'-Page (which actually is php...).
<div class="comment_container">
<div class="comments">
<?php
// specify the type needed on that page
$type = 1;
include_once("comments.php");
echo getComments($type);
?>
</div>
<div class="comments_form">
<table>
<tr><td><textarea id="comment_text"></textarea></td>
<td><input type="button" id="comment_process" value="Post Comment"/></td></tr>
</table>
</div>
</div>
<script>
// specify the type in javascript
var type=1;
$(document).ready(function() {
$('#comment_process').click(function() {
if ($('#comment_text').val() != "") {
// add the type here:
$.post("comments.php", {
comment: $('#comment_text').val(),
type: type,
action: 'post'
}, function(data) {
$('.comments').html(data);
$('#comment_text').val("");
});
}
});
});
</script>
and in comments.php:
//....some code left out here
function getComments($type){
$comments = "";
$sql = mysql_query("SELECT * FROM comments where type=$type") or die(mysql_error());
if(mysql_num_rows($sql) == 0){
$comments = "<div class='each_comment'>There are no comments</div>";
} else {
while($row = mysql_fetch_assoc($sql)){
$comments .= "<div class='each_comment'><small><em>".convert($row['comment_date'])."</em></small><br />".$row['comment']."</div>";
}
}
return $comments;
}
function postComments($comment, $type){
$comment = mysql_real_escape_string(strip_tags($comment));
$sql = mysql_query("INSERT INTO comments (comment, comment_date, type ) VALUES ('".$comment."', now(), ".$type.")");
return true;
}
if((isset($_POST['action'])) && ($_POST['action']== "post")){
postComments($_POST['comment'], $_POST['type']);
// send all the comments back to client
echo getComments($_POST['type']);
}
// moved to html-file: echo getComments($type);
NOTE
There are several issues with that code.
First don't use mysql functions. For real. Unsecure and deprecated/deleted as of php7. Use mysqli or pdo. Furthermore your sql can be hacked with sql injection. Read about prepared statements.
The general structure of that code is not very good.
Try to seperate output and formating from getting data.
For example it would be much better if a function called 'getComments' only would get the comments from the database, then let others decide what to do with that data. The less one function does the better.
Please read about coding styles, maybe start learning object oriented programming.
I hope this still helps you to get a clue of where to go!

Related

how to have different comments from you in different pages

I am creating a website that contains different movies, every movie has a specific id_movie, i have added a comment box where the user can add a comment about the movie, however, every movie i click on, they all show the same comments that have been entered, I want every movie to have its own comments, I will be happy if you can help me with that. thanks
comments.php
<body>
<br />
<h2 align="center"><p >Add Comment</p></h2>
<br />
<div class="container">
<form method="POST" id="comment_form">
<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"></div>
</div>
</body>
<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()
{
$.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>
add_comment.php
<?php
$con = new PDO('mysql:host=localhost;dbname=db_movie', 'root', '');
$error = '';
$comment_name = '';
$comment_content = '';
if(empty($_POST["comment_name"]))
{
$error .= '<p class="text-danger">Name is required</p>';
}
else
{
$comment_name = $_POST["comment_name"];
}
if(empty($_POST["comment_content"]))
{
$error .= '<p class="text-danger">Comment is required</p>';
}
else
{
$comment_content = $_POST["comment_content"];
}
if($error == '')
{
$query = "
INSERT INTO tbl_comment
(parent_comment_id, comment, comment_sender_name, movie_id)
VALUES (:parent_comment_id, :comment, :comment_sender_name)
";
$statement = $con->prepare($query);
$statement->execute(
array(
':parent_comment_id' => $_POST["comment_id"],
':comment' => $comment_content,
':comment_sender_name' => $comment_name
)
);
$error = '<label class="text-success">Comment Added</label>';
}
$data = array(
'error' => $error
);
echo json_encode($data);
?>
fetch_comment.php
<?php
//fetch_comment.php
$con = new PDO('mysql:host=localhost;dbname=db_movie', 'root', '');
$query = "
SELECT * FROM tbl_comment
WHERE parent_comment_id = '0'
ORDER BY comment_id DESC
";
$statement = $con->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$output = '';
foreach($result as $row)
{
$output .= '
<div class="panel panel-default">
<div class="panel-heading">By <b>'.$row["comment_sender_name"].'</b> on <i>'.$row["date"].'</i></div>
<div class="panel-body">'.$row["comment"].'</div>
<div class="panel-footer" align="right"><button type="button" class="btn btn-default reply" id="'.$row["comment_id"].'">Reply</button></div>
</div>
';
$output .= get_reply_comment($con, $row["comment_id"]);
}
echo $output;
function get_reply_comment($con, $parent_id = 0, $marginleft = 0)
{
$query = "
SELECT * FROM tbl_comment WHERE parent_comment_id = '".$parent_id."'
";
$output = '';
$statement = $con->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$count = $statement->rowCount();
if($parent_id == 0)
{
$marginleft = 0;
}
else
{
$marginleft = $marginleft + 48;
}
if($count > 0)
{
foreach($result as $row)
{
$output .= '
<div class="panel panel-default" style="margin-left:'.$marginleft.'px">
<div class="panel-heading">By <b>'.$row["comment_sender_name"].'</b> on <i>'.$row["date"].'</i></div>
<div class="panel-body">'.$row["comment"].'</div>
<div class="panel-footer" align="right"><button type="button" class="btn btn-default reply" id="'.$row["comment_id"].'">Reply</button></div>
</div>
';
$output .= get_reply_comment($con, $row["comment_id"], $marginleft);
}
}
return $output;
}
?>
and here when I click on each movie:
<?php include('header.php');
$qry2=mysqli_query($con,"select * from tbl_movie where movie_id='".$_GET['id']."'");
$movie=mysqli_fetch_array($qry2);
?>
<div class="content">
<div class="wrap">
<div class="content-top">
<div class="section group">
<div class="about span_1_of_2">
<h3><?php echo $movie['movie_name']; ?></h3>
<div class="about-top">
<div class="grid images_3_of_2">
<img src="<?php echo $movie['image']; ?>" width="180px" height="280px" alt=""/>
<?php include('ratte.php'); ?>
</div>
<div class="desc span_3_of_2">
<p class="p-link" style="font-size:15px">Type: <?php echo $movie['type']; ?></p>
<p class="p-link" style="font-size:15px">Price: £<?php echo date($movie['price']); ?></p>
<p style="font-size:15px"><?php echo $movie['desc']; ?></p>
Watch Trailer
</div>
<div class="clear"></div>
</div>
<?php $s=mysqli_query($con,"select DISTINCT theatre_id from tbl_shows where movie_id='".$movie['movie_id']."'");
if(mysqli_num_rows($s))
{?>
<table class="table table-hover table-bordered text-center">
<?php
while($shw=mysqli_fetch_array($s))
{
$t=mysqli_query($con,"select * from tbl_theatre where id='".$shw['theatre_id']."'");
$theatre=mysqli_fetch_array($t);
?>
<tr>
<td>
<?php echo $theatre['name'].", ".$theatre['place'];?>
</td>
<td>
<?php $tr=mysqli_query($con,"select * from tbl_shows where movie_id='".$movie['movie_id']."' and theatre_id='".$shw['theatre_id']."'");
while($shh=mysqli_fetch_array($tr))
{
$ttm=mysqli_query($con,"select * from tbl_show_time where st_id='".$shh['st_id']."'");
$ttme=mysqli_fetch_array($ttm);
?>
<button class="btn btn-default"><?php echo date('h:i A',strtotime($ttme['start_time']));?></button>
<?php
}
?>
</td>
</tr>
<?php
}
?>
</table>
<div id='display_comment'></div>
<?php
}
else
{
?>
<h3>No Show Available</h3>
<div id='display_comment'></div>
<?php
}
?>
</div>
<?php include('related-movies.php');
?>
</div>
<div class="clear"></div>
</div>
<?php include('comments.php'); ?>
</div>
</div>
<?php include('footer.php'); ?>
I'll try my best, but there is a lot to cover.
comments.php
//add the target files URL as the form's action
<form method="POST" id="comment_form" action="add_comment.php" >
//add movie to the form, that way when we insert the comment we know what its for
<input type="hidden" name="movie_id" id="movie_id" value="<?php echo $movie_id; ?>" />
//.. in your JS, add the movie id to the fetch comment call
function load_comment()
{
$.ajax({
url:"fetch_comment.php",
method:"POST",
data: {movie_id : <?php echo $movie_id; ?>},
dataType: 'json',
success:function(data){
//...
})
}
//move this below the function definition
load_comment();
add_comment.php
//add movie id here to match what is in the form above
INSERT INTO tbl_comment
(parent_comment_id, comment, comment_sender_name, movie_id)
VALUES (:parent_comment_id, :comment, :comment_sender_name, :movie_id)
// add ':movie_id' => $_POST['movie_id'] to the array you have there for
// $statement->execute([ ....]). The arrays below go the same way
//add those to $statement->execute() for there respective DB calls,
You had the movie in the FIELDS part of the insert, but not the VALUES, which is probably an SQL syntax error. You may not have seen an actual error because this is called with AJAX so it would just break on the client side. You could look in the browser debug window > network [XHR] requests and look at the response. There you would probably find it or you may simply get a 500 error from the server.
fetch_comment.php
//add movie id here to match what is in the AJAX fetch comment call
SELECT * FROM tbl_comment
WHERE parent_comment_id = :parent_comment_id AND movie_id = :movie_id
ORDER BY comment_id DESC
//for execute add
['parent_comment_id'=>0, 'movie_id'=>$_POST['movie_id']]
Important prepare this query properly
$query = "
SELECT * FROM tbl_comment WHERE parent_comment_id = '".$parent_id."'
";
So it should be like this:
$query = "SELECT * FROM tbl_comment WHERE parent_comment_id = :parent_id";
//then add this to execute ['parent_id' => $parent_id]
mainpage.php (not sure the name on this one)
In the last unnamed code chunk you are using mysqli but above your using PDO it's better to use one or the other, personally I prefer PDO, its just better API wise. You are also not preparing these (so convert these to PDO). Using both just adds unnecessary complexity to your application (I think there were 2 of theses in there):
$qry2=mysqli_query($con,"select * from tbl_movie where movie_id='".$_GET['id']."'");
$movie=mysqli_fetch_array($qry2);
It looks like you include the comments.php into that last page <?php include('comments.php'); ?> So what I would do is where the query is above that I said to fix:
require_once `db.php`; //- create a separate file to do the DB connection for you
//then you can add that to the top of all the pages you need the DB for
include 'header.php'; //no need for the ( ) for any of the include* or require* calls.
/*
require will issue an error if the included file is not found
include will fail silently, for things that are required for your
page to work and not produce errors use require (like the DB)
for things you only ever include once, also like the DB stuff use *_once
then no matter how many *_once calls are stacked from including
the other page you don't have to worry about it.
as above those simple rules give us require_once for the DB.
the other pages I am not sure which would be best.
*/
//localize the movie ID - change any use of `$_GET['id']
$movie_id = isset($_GET['id']) ? $movie_id : false;
if(!$movie_id){
//do something if someone goes to this page with no ?id= in the URL
//you could redirect the page
//you could have a default movie id etc...
}
$statement = $con->prepare('select * from tbl_movie where movie_id=:movie_id');
$statement->execute(['movie_id' => $movie_id]);
$movie = $statement->fetch();
//dont forget to fix the other DB call and remove the MySqli stuff.
Above I suggest using a single file for the DB, in your case it can be quite simple,
db.php
<?php $con = new PDO('mysql:host=localhost;dbname=db_movie', 'root', '');
That is literally all you need then, at the very top of each page you use the DB, simply add this file
require_once 'db.php';
This way if you need to change the password or something like that, you can go to one place named in way that is easy to remember and change it. How it is now, you would have to dig though all your code to change it. In that page your including a file named header.php and it looks like from your MySQLi code that it may have some connection stuff in there. I would remove any MySQLi stuff there too. You want to keep the DB file separate as you may need to include it in the AJAX backend parts and any output from header.php would mess you up.
Summery
What I showed above is a simple example of what you need to do, in that AJAX call This may not be all you need to do, these are just the things that were obvious to me.
You don't have to worry about child comment's movie ID, as they inherit it from the parent comment, which wouldn't exist (on the page) if it had the wrong ID. In your current setup, I would still save it as part of the data. It's just you dont need it to get child comments if you know the parent (which you sort of have to know). I didn't add it into one thing that looked like it was for child comment. You can add it, but as I said above, it's not really needed.
Really the question is way to broad, why isn't my code working kind of question. The only reason I took the effort was that you also took the effort to provide well organized code that is relatively minimal.
So thank you for that.
The last suggestion I would make, is clean up the extra line returns in some of the SQL, and format the TABs a bit better. But that is just a readability issue, I am very picky about formatting my code and some of that could be related to creating an question on SO as it takes a bit of getting used the markdown they use.
Hope it helps you!
Update
thanks for your answer, I really dont know what i should post here and what i shouldnt, and the thing that i dont understand is that: i have a tbl_comment which stores all comments from user and this table include movie_id, and i have another tbl_movie which has movie_id as a primary key, how can i link the movie _id with the tbl_comment so that every comment is stored for a specific movie_id
I will try to explain the flow of your application, with an example. For the sake of this example lets say the movie id is 12 and our main page is www.example.com/movies?id=12:
Inserting a comment
User goes to a url with ?id=12
everything after the ? is called the query string
PHP knows to take the query string and populate the supper global $_GET
so in the main page your movie id is now $_GET['id']
We localize this (make a local variable) at the top of the page with some basic checks. $movie_id = isset($_GET['id']) ? $movie_id : false;
if movie id is set ?id=12 then put it in $movie_id
if its not www.example.com/movies then set $movie_id to false
this avoids some errors if someone goes to the page without that set
At the bottom of the page you include this file <?php include('comments.php'); ?> think of it like pasting that code into this place
In comments.php, which runs when it's included above,
if someone inserts a new comment (submits the form) weve added that same $movie_id into the form with this line
<input type="hidden" name="movie_id" id="movie_id" value="<?php echo $movie_id; ?>" />.
-So now when the form submits to add_comment.php which you need to put in the form's action.
<form method="POST" id="comment_form" action="add_comment.php" >
It will contain the id as $_POST['movie_id'] on that page. The $_POST['movie_id'] is basically the same as $_GET['id'] but the form method tells us its post instead of get. Typically Get is used to retrieve resources, Post is used to modify them.
When PHP runs the above piece of HTML it replaces the <?php echo $movie_id; ?> with it's value of 12 so you get this
<input type="hidden" name="movie_id" id="movie_id" value="12" />
Now On add_comment.php (where the form action takes us) we can take that $_POST['movie_id'] and add that to your SQL used to Insert the comment from the form in #4. into the Database.
INSERT INTO tbl_comment
(parent_comment_id, comment, comment_sender_name, movie_id)
VALUES (:parent_comment_id, :comment, :comment_sender_name, :movie_id)
As this is a prepared statement we have the place holder :movie_id in the SQL query. In PDO we can feed that to the PDOStatment object ($statement) you get back from $statment=$conn->prepare($sql) by calling it's execute method or $statement->execute([..other stuff here..., 'movie_id'=>$_POST['movie_id']]).
The query that runs looks like this after PHP is done with it
INSERT INTO tbl_comment
(parent_comment_id, comment, comment_sender_name, movie_id)
VALUES (0, 'foo', 'ArtisticPhoenix', 12) <-- see what I did there.
So you see we took the value from the original URL request, added it to our form and then we wait for user action to submit that form with the movie id embedded in it. The when the form submits it calls our add comment page, where we take it out of the Posted data, and feed it into the DB with the rest of the form data for that comment.
The other ones are exactly the same except in those we are using AJAX to submit the data so instead of a form we just add it to the AJAX call. I will give you an example of how that executes.
Showing a comment
This is the same up to #4 above
In comments.php you call load_comment(); "After" defining the function as it doesn't exist tell you do that, so you cant call it before.
This runs your AJAX request $.ajax, for the purposes of this example think of it like a fancy way to do a form. The url is the form action the method is well the method. The data is the form data, the dataType is the type of encoding in this case JSON or Javascript Object Notation. Which is a fancy way of saying structured data, as in PHP its basically an array (or data with nested elements).
The url (action) points us to fetch_comment.php, so when that runs our data: {movie_id : <?php echo $movie_id; ?>}, becomes data: {movie_id : 12}, which gets sent back to server where PHP sees it as $_POST['movie_id']
Similar to the Insert, we use that ID in our SQL query that pulls the parent comments
SELECT * FROM tbl_comment
WHERE parent_comment_id = :parent_comment_id AND movie_id = :movie_id
ORDER BY comment_id DESC
This says "Select all columns From table tbl_comment WHERE parent_comment_id IS 0 and Movie Id is 12" So it will only return comments for movie 12 that are also parents.
in your code you have just $statement->execute(); But you had the parent_comment_id hard coded as 0. This was fin until we needed to add the movie_id Once we did that it makes more senses to make it part of the prepared statement so it reads better. But like the insert, now we have place holder in place of values so we need to take that data and add it to execute for this query.
So $statement->execute(); becomes $statement->execute(['parent_comment_id'=>0, 'movie_id' => $_POST['movie_id']]); Or when PHP is done with it $statement->execute(['parent_comment_id'=>0, 'movie_id' => 12]); which the Database knows to use the keys to match the placeholders and it completes our query.
SELECT * FROM tbl_comment
WHERE parent_comment_id = 0 AND movie_id = 12
ORDER BY comment_id DESC
Then we take the results and send them back to the success handler for the AJAX with echo and in this case add it to the page with this line $('#display_comment').html(data);
So In conclusion
Your code:
load_comment();
function load_comment()
{
$.ajax({
url:"fetch_comment.php",
method:"POST",
success:function(data)
{
$('#display_comment').html(data);
}
})
}
Correct code (what I said):
//.. in your JS, add the movie id to the fetch comment call
function load_comment()
{
$.ajax({
url:"fetch_comment.php",
method:"POST",
data: {movie_id : <?php echo $movie_id; ?>},
dataType: 'json',
success:function(data){
//...
})
}
load_comment();
What you need to do
//$movie_id = $_GET['id'] in the main page that included this file.. #2 above
function load_comment()
{
$.ajax({
url:"fetch_comment.php",
method:"POST",
data: {movie_id : <?php echo $movie_id; ?>},
dataType: 'json',
success:function(data)
{
$('#display_comment').html(data);
}
});
}
load_comment();
When PHP completes the above code it sends this to the client (using 12 from our example)
//$movie_id = $_GET['id'] in the main page that included this file.. #2 above
function load_comment()
{
$.ajax({
url:"fetch_comment.php",
method:"POST",
data: {movie_id : 12}, //PHP takes the value of $movie_id and puts it here
dataType: 'json',
success:function(data)
{
$('#display_comment').html(data);
}
});
}
load_comment();
Above is what actually runs in the browser
That is pretty much the gist of it. As I said its more beneficial to you to learn how it works. Sure I can post the complete code but I have no way to test it, no way to know if that is all the errors or not. If you learn how it works, you will be better equipped to take on those challenges yourself. I would rather spend 3 or 4 times the effort teaching you how it all works, then to post some code that you have no idea how it works.
Hope that all makes some sense.

Remove item from session onClick

I'm trying to remove an item from a sort of shopping cart. The items are saved to a session when they are "saved to the shopping cart".
But now I would like to be able to remove certain items from this "shopping cart". Because I got the script from here (stackoverflow) I'm not that familiar with the code. I saw some answers on google and here that described using unset to delete the entry from the session. But I wouldn't know where to start with this one. If additional information is needed please let me know. Thanks for having a look at my question...
Here is the HTML (nothing special):
<div class="txtHint"></div>
This is my script:
$('.add-product').click(function() {
var productName = $(this).data('product');
$.post('example.com/reload.php', {productName: productName}, function(data) {
$('.txtHint').html(data);
})
});
This is my reload.php file:
<?php
session_start();
if (!array_key_exists('products', $_SESSION) || !is_array($_SESSION['products'])) {
$_SESSION['products'] = [];
}
$productName = array_key_exists('productName', $_POST) ? (string) $_POST['productName'] : '';
if ($productName) {
$_SESSION['products'][] = $productName;
}
?>
<h4>Saved Items</h4>
<?php foreach ($_SESSION['products'] as $product): ?>
<div class="echo-product"><i style="color:#F60;padding-right:20px;" class="fa fa-anchor" aria-hidden="true"></i><?php echo htmlspecialchars($product); ?></div>
<?php endforeach;?>
Updated code: As suggested by Bert Maurau (I Hope).
<?php
session_start();
if (!array_key_exists('products', $_SESSION) || !is_array($_SESSION['products'])) {
$_SESSION['products'] = [];
}
$productName = array_key_exists('productName', $_POST) ? (string) $_POST['productName'] : '';
if(isset($_GET['delparam'])){
unset($_SESSION['products'][$productName]);
}
if(isset($_GET['addparam'])){
$_SESSION['products'][] = $productName;
}
?>
If I use this it doesn't add any new items...
You should be able to do:
unset($_SESSION['products'][$productName]);
This wil unset the array_key and its values that matches your productName.
Edit: Code for using the unset
HTML:
$('.delete-product').click(function() {
var productName = $(this).data('product');
$.post('example.com/reload.php?delparam', {productName: productName}, function(data) {
})
});
Reload.php (after $productName)
if(isset($_GET['delparam'])){
unset($_SESSION['products'][$productName]);
}
if(isset($_GET['addparam'])){
//code for adding product
}

asynchronous commenting using ajax

I'm trying to create a comment system on my website where the user can comment & see it appear on the page without reloading the page, kind of like how you post a comment on facebook and see it appear right away. I'm having trouble with this however as my implementation shows the comment the user inputs, but then erases the previous comments that were already on the page (as any comments section, I'd want the user to comment and simply add on to the previous comments). Also, when the user comments, the page reloads, and displays the comment in the text box, rather than below the text box where the comments are supposed to be displayed. I've attached the code. Index.php runs the ajax script to perform the asynchronous commenting, and uses the form to get the user input which is dealt with in insert.php. It also prints out the comments stored in a database.
index.php
<script>
$(function() {
$('#submitButton').click(function(event) {
event.preventDefault();
$.ajax({
type: "GET",
url: "insert.php",
data : { field1_name : $('#userInput').val() },
beforeSend: function(){
}
, complete: function(){
}
, success: function(html){
$("#comment_part").html(html);
window.location.reload();
}
});
});
});
</script>
<form id="comment_form" action="insert.php" method="GET">
Comments:
<input type="text" class="text_cmt" name="field1_name" id="userInput"/>
<input type="submit" name="submit" value="submit" id = "submitButton"/>
<input type='hidden' name='parent_id' id='parent_id' value='0'/>
</form>
<div id='comment_part'>
<?php
$link = mysqli_connect('localhost', 'x', '', 'comment_schema');
$query="SELECT COMMENTS FROM csAirComment";
$results = mysqli_query($link,$query);
while ($row = mysqli_fetch_assoc($results)) {
echo '<div class="comment" >';
$output= $row["COMMENTS"];
//protects against cross site scripting
echo htmlspecialchars($output ,ENT_QUOTES,'UTF-8');
echo '</div>';
}
?>
</div>
insert.php
$userInput= $_GET["field1_name"];
if(!empty($userInput)) {
$field1_name = mysqli_real_escape_string($link, $userInput);
$field1_name_array = explode(" ",$field1_name);
foreach($field1_name_array as $element){
$query = "SELECT replaceWord FROM changeWord WHERE badWord = '" . $element . "' ";
$query_link = mysqli_query($link,$query);
if(mysqli_num_rows($query_link)>0){
$row = mysqli_fetch_assoc($query_link);
$goodWord = $row['replaceWord'];
$element= $goodWord;
}
$newComment = $newComment." ".$element;
}
//Escape user inputs for security
$sql = "INSERT INTO csAirComment (COMMENTS) VALUES ('$newComment')";
$result = mysqli_query($link, $sql);
//attempt insert query execution
//header("Location:csair.php");
die();
mysqli_close($link);
}
else{
die('comment is not set or not containing valid value');
}
The insert.php takes in the user input and then inserts it into the database (by first filtering and checking for bad words). Just not sure where I'm going wrong, been stuck on it for a while. Any help would be appreciated.
There are 3 main problems in your code:
You are not returning anything from insert.php via ajax.
You don't need to replace the whole comment_part, just add the new comment to it.
Why are you reloading the page? I thought that the whole purpose of using Ajax was to have a dynamic content.
In your ajax:
$.ajax({
type: "GET",
url: "insert.php",
data : { field1_name : $('#userInput').val() },
beforeSend: function(){
}
, complete: function(){
}
, success: function(html){
//this will add the new comment to the `comment_part` div
$("#comment_part").append(html);
}
});
Within insert.php you need to return the new comment html:
$userInput= $_GET["field1_name"];
if(!empty($userInput)) {
$field1_name = mysqli_real_escape_string($link, $userInput);
$field1_name_array = explode(" ",$field1_name);
foreach($field1_name_array as $element){
$query = "SELECT replaceWord FROM changeWord WHERE badWord = '" . $element . "' ";
$query_link = mysqli_query($link,$query);
if(mysqli_num_rows($query_link)>0){
$row = mysqli_fetch_assoc($query_link);
$goodWord = $row['replaceWord'];
$element= $goodWord;
}
$newComment = $newComment." ".$element;
}
//Escape user inputs for security
$sql = "INSERT INTO csAirComment (COMMENTS) VALUES ('$newComment')";
$result = mysqli_query($link, $sql);
//attempt insert query execution
mysqli_close($link);
//here you need to build your new comment html and return it
return "<div class='comment'>...the new comment html...</div>";
}
else{
die('comment is not set or not containing valid value');
}
Please note that you currently don't have any error handling, so when you return die('comment is not set....') it will be displayed as well as a new comment.
You can return a better structured response using json_encode() but that is outside the scope of this question.
You're using jQuery.html() which is replacing everything in your element with your "html" contents. Try using jQuery.append() instead.

how to send record to table after click the js link/button?

i want to make an like-unlike button below the post. registered user can give like. i have make the button, but i don't have idea how to send a record when user click the button. i guess i need like table, so this below is table and it field that i have :
user : id_user, username
posting : id_post, id_user, content
like : id_like, id_user, id_post
posting page and like button script :
<?php
include "database_connection.php";
$query=$dbc->query("select user.username, posting.content FROM posting inner join user on user.id_user = posting.id_user where id_post='$_GET[id]'");
$array= $query->fetch_array()
?>
<!doctype html>
<html>
<head>
<script type="text/javascript" src="post.js"></script>
</head>
<body>
<?php echo $array['username'];?>
<?php echo $array['content'];?>
<!--THIS IS LIKE BUTTON-->
<a class="like-button" href="#"><i class="fa fa-thumbs-up"></i></a>
<!--LIKE BUTTON END-->
</body>
</html>
post.js
$(function() {
$('.like-button').click(function(){
var obj = $(this);
if( obj.data('liked') ){
obj.data('liked', false);
obj.html('<i class="fa fa-thumbs-up"></i>');
}
else{
obj.data('liked', true);
obj.html('<i class="fa fa-thumbs-down"></i>');
}
});
});
Alright, so I've taken the time to create a basic working example for you.
I've included the workings of post.js in an inline script rather than a separate file for simplicity with including a PHP variable inside of the script.
Your HTML Page
<?php
include "database-connection.php";
$user = 1;// get your accessing user ID (not user id of poster)
$post = $_GET['id'];
// query checks whether user has liked the post or not and returns it as well
$query=$dbc->prepare("
SELECT `user`.`username`, `posting`.`content`, IFNULL(`like`.`id_like`,0) AS `id_like`
FROM `posting`
INNER JOIN `user` ON `user`.`id_user` = `posting`.`id_user`
LEFT JOIN `like` ON `like`.`id_user` = ? AND `like`.`id_post` = ?
WHERE `posting`.`id_post`=?");
// bind the parameters to avoid injection
$query->execute(array($user, $post, $post));
$array= $query->fetch(PDO::FETCH_ASSOC);
?>
<!doctype html>
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<script type="text/javascript">
// previously post.js
$(function() {
$('.like-button').click(function(e){
e.preventDefault();
var obj = $(this);
// ajax query that returns a JSON object with the result of the request
$.getJSON('likes.php',{post:obj.data('post'), user: <?php echo $user; ?>}, function(data){
//console.log(data); // uncomment for debugging
if(data.error){
// query returned error, handle it however you want
} else {
if (data.like == 1){ // user now likes the post
obj.html('<i class="fa fa-thumbs-up"></i>');
} else { // user now doesn't like the post
obj.html('<i class="fa fa-thumbs-down"></i>');
}
}
});
});
});
</script>
</head>
<body>
<?php echo $array['username'];?>
<?php echo $array['content'];?>
<!--THIS IS LIKE BUTTON-->
<?php
if ($array['id_like']==0){
// user hasn't liked the post, show thumbs down
echo '<a class="like-button" href="#" data-post="'.$post.'"><i class="fa fa-thumbs-down"></i></a>';
} else {
// user has liked the post, show thumbs up
echo '<a class="like-button" href="#" data-post="'.$post.'"><i class="fa fa-thumbs-up"></i></a>';
}
?>
<!--LIKE BUTTON END-->
</body>
</html>
likes.php (the PHP script)
<?php
include "database-connection.php";
$post = $_GET['post'];
$user = $_GET['user'];
$result = (object) ['like'=>null, 'post'=>$post, 'user'=>$user];
$q = $dbc->prepare("SELECT id_like FROM `like` WHERE id_post=? AND id_user=?");
$q->execute(array($post, $user));
$r = $q->fetch(PDO::FETCH_OBJ);
if ($q->rowCount() > 0){
$like = $r->id_like;
} else {
$like = 0;
}
if ($like == 1){
// user likes post, so we unlike it by setting id_like to 0 (for false)
$like = 0;
$u = $dbc->prepare("UPDATE `like` SET id_like = 0 WHERE id_post=? AND id_user=?");
} elseif ($q->rowCount()>0) {
// update because the record exists
$like = 1;
$u = $dbc->prepare("UPDATE `like` SET id_like = 1 WHERE id_post=? AND id_user=?");
} else {
// create the record because it doesn't exist yet
$like = 1;
$u = $dbc->prepare("INSERT INTO `like` (id_like, id_post, id_user) VALUES(1, ?, ?)");
}
if($u->execute(array($post, $user))){
// update succeeded
$result->like = $like;
} else{
// there was an error
$result->error = 'failed to execute in database';
}
// return the json object to your page
echo json_encode($result);
Again, this is just the basics of how this would work. You will have to research logins, sessions, and security for yourself to manage the user who are accessing, posting, and liking the content. But I hope this helps!
Send the request to PHP page on click of like button and handle it there to update the database.
You will need to send an Ajax request to the server and then handle in in a PHP script.
Here's a way to do that.
post.js:
$(function() {
$('.like-button').click(function(){
var obj = $(this);
if( obj.data('liked') ){
obj.data('liked', false);
obj.html('<i class="fa fa-thumbs-up"></i>');
}
else{
obj.data('liked', true);
obj.html('<i class="fa fa-thumbs-down"></i>');
}
$.post('url/to/your_script.php', {
action: 'updateLikeStatus',
status: obj.data('liked'),
post_id: obj.data('id') // ID of the object that user "liked"
});
});
});
You can read more about jQuery.post() here. And here's documentation on more general jQuery.ajax() method.
your_script.php (script that deals with Ajax requests) might look something like this:
<?php
include "database_connection.php";
if (isset($_POST['action']) && $_POST['action'] === 'updateLikeStatus') {
$id_user = $_SESSION['user_id'];
$id_post = $_POST['post_id'];
if ($_POST['status'] === true) {
// adding "like"
$query = $dbc->query("
INSERT INTO like
(id_user, id_post)
VALUES ({$id_user}, {$id_post});
");
$query->query();
} else {
// removing "like"
$query = $dbc->query("
DELETE FROM like
WHERE id_user = {$id_user}
AND id_post = {$id_post};
");
$query->query();
}
}
Note that this code is just an example, you shouldn't use it directly in the production. For one thing, you can't put variables from $_POST directly into a MySQL query, because it will create an SQL Injection type vulnerability, allowing people to perform arbitrary queries on your server. One way to avoid it is by using prepared statements.
Another problem is that you will need to deal with the user authentication and authorization. I've used $_SESSION['user_id'] in my example, but it won't work unless you initialize session and populate user_id value first. Sessions are required so that one user can't like posts on behalf of another user. You can read more about sessions here.

Can't insert into database an autofill fields?

it's my first time asking here,
I've been trying to look for something similar in other questions asked, and couldn't find it.
I have a form with Zip code line(textbox) and State line(textbox),
now, the stateboxes are auto-filled by a javascript by entering a valid US zip code.
the form itself is a bit longer.
I only show the relevant code that has been edited by me,
It was a select menu before (and everything worked just fine - data was entered into databse), and I changed it, so no select will be needed.
There is also css file, but it's irrelevant (designing isn't the issue)
So, here is my html code :
<html>
<head>some content here</head>
<body>
<form method="post" action="process.php">
<div class="title"><h2>my form title</h2></div><br>
<div align="center" class="element-name">
</span>
<span align="center" id="zipbox" class="nameFirst">
<input type="text" class="medium" pattern="[0-9]*" name="col2" id="col2" maxlength="5" placeholder="Type your ZIP code" onkeypress='validate(event)'required/>
</span>
<span align="center" id="zipbox2" class="nameLast">
<input type="text" class="medium" pattern="[0-9]*" name="col4" id="col4" maxlength="5" placeholder="Type your ZIP code" onkeypress='validate(event)'required/>
</span></div>
<div align="center" class="element-name">
<span class="required"></span>
<span align="center" id="statebox" class="nameFirst">
<input type="text" class="medium" name="col1" id="col1" placeholder="" required />
<label class="subtitle">From</label>
</span>
<span align="center" id="statebox2" class="nameLast">
<input type="text" class="medium" name="col3" id="col3" placeholder="" required />
<label class="subtitle">To</label>
</span></div>
<p align="center"><input type="reset" value="Clear"></p>
</body>
</html>
some javescript !
<script src="//code.jquery.com/jquery-1.11.1.js"></script>
<script>
$(document).ready(function() {
$("#col2").keyup(function() {
var el = $(this);
if (el.val().length === 5) {
$.ajax({
url: "http://zip.elevenbasetwo.com",
cache: false,
dataType: "json",
type: "GET",
data: "zip=" + el.val(),
success: function(result, success) {
$("#city").val(result.city);
$("#col1").val(result.state);
}
});
}
});
});
</script>
<script>
$(document).ready(function() {
$("#col4").keyup(function() {
var el = $(this);
if (el.val().length === 5) {
$.ajax({
url: "http://zip.elevenbasetwo.com",
cache: false,
dataType: "json",
type: "GET",
data: "zip=" + el.val(),
success: function(result, success) {
$("#city2").val(result.city);
$("#col3").val(result.state);
}
});
}
});
});
</script>
and php code to process the form :
- it's 13 columns, but i know for sure that the other values are correct.
- col0 represent the date.
<?php
require_once('recaptchalib.php');
$privatekey = "mycaptchakey";
$resp = recaptcha_check_answer ($privatekey,
$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]);
if (!$resp->is_valid) {
// What happens when the CAPTCHA was entered incorrectly
die ("The reCAPTCHA wasn't entered correctly. Go back and try it again." .
"(reCAPTCHA said: " . $resp->error . ")");
$process = FALSE;
} else {
// Your code here to handle a successful verification // Your code here to handle a successful verification
}
define('CONST_SERVER_TIMEZONE', 'EDT');
define('CONST_SERVER_DATEFORMAT', 'YmdHis');
$current_date = date("Y-m-d H:i:s");
$col0 = $_POST['col0'];
$col1 = strtoupper($_POST['col1']);
$col2 = strtoupper($_POST['col2']);
$col3 = strtoupper($_POST['col3']);
$col4 = strtoupper($_POST['col4']);
if ( isset($col1) && isset($col2) isset($col3) && isset($col4) && $error == FALSE ) {
$process = TRUE;
} else {
$process = FALSE;
}
$mode = "mysql";{
define ('DB_USER', 'uname');
define ('DB_PASSWORD', 'pass');
define ('DB_HOST', 'host');
define ('DB_NAME', 'dbname');
$dbc = #mysql_connect (DB_HOST, DB_USER, DB_PASSWORD) or die('Failure: ' . mysql_error() );
mysql_select_db(DB_NAME) or die ('Could not select database: ' . mysql_error() );
$query = "INSERT INTO mytable VALUES ('$current_date','$col1','$col2','$col3','$col4')";
$q = mysql_query($query);
if (!$q) {
exit("<p>MySQL Insertion failure.</p>");
} else {
mysql_close();
//for testing only
//echo "<p>MySQL Insertion Successful</p>";
}}
header( 'Location: http://mywebsite.com/index.php' );
?>
i'm not sure if i'm doing it right but here is my
mytable structure :
1 - sid - int(11) AUTO_INCREMENT
2 - col0 - date
3 - col1 - text utf8_unicode_ci
4 - col2 - text utf8_unicode_ci
5 - col3 - text utf8_unicode_ci
6 - col4 - text utf8_unicode_ci
and so on up to 12 columons.
Help please ! what is going wrong here ?
EDIT :
Thank you very much r3wt for the usefull information,
there is a lot to fix especially when it comes to the php part of it :)
ok, so i was able to fix the insertion.
i missed a critical value -
$query = "INSERT INTO mytable VALUES ('$current_date','$col1','$col2','$col3','$col4')";
should have been:
$query = "INSERT INTO mytable VALUES ('','$current_date','$col1','$col2','$col3','$col4')";
that's is because all this form info is going into a phpGrid table
and i had a hidden column 'sid' which is automatically beeing filled.
I promise that in the next time I will be prepare with some more knowledge :)
thanks again.
This waits until a second has past after they have finished typing in the element, then submits the ajax request.
$(function(){
$("#col4").keyup(function() {
var col4val = $(this).val();
clearTimeout(timer);
timer = setTimeout(function(){fillLocation(col4val)}, 1000);
});
var timer = null;
function fillLocation(value){
$.get('http://zip.elevenbasetwo.com', {zip: value} , function(data){
var result = JSON.parse(data);
$("#city2").val(result.city);
$("#col3").val(result.state);
});
}
});
also, your php code is considered to be woefully insecure because you are using mysql.
also, i just noticed a glaring error, you are missing and and operator between $col2 isset and $col3, check your ajax i guarantee you it is returning 500 internal server error:
if ( isset($col1) && isset($col2) isset($col3) && isset($col4) && $error == FALSE ) {
$process = TRUE;
} else {
$process = FALSE;
}
also, your query is wrong. its obvious you are just copy and pasting things together here. go read the mysql manual on INSERT statements and go read up on the mysqli and pdo extensions for php.
A valid mysql statement looks like:
INSERT INTO mytable (column1,column2,column3) VALUES ('val1','val2','val3')
realizing this, you could construct the statement in php like so
$query = mysql_query("INSERT INTO mytable (column1,column2,column3) VALUES ('".$val1."','".$val2."','".$val3."')");
if you continue to use mysql you will get your site hacked, its just a matter of time, especially since you don't sanitize any of your data. please make the smart choice and use mysqli or pdo to interface with the database from php.
As per the request of Dikei, i'm going to introduce you briefly to prepared statements with mysqli so that you may learn to use safe methods for interacting with the database.
$mysqli = new mysqli('host','username','password','databasename');
$mysqli->set_charset("utf8");
$stmt = $mysqli->prepare("INSERT INTO mytable (column1,column2,column3) VALUES (?,?,?)");//bind your variables in the same order!
//s for a string, d for a double floating point integer, and i for unsigned int.
$stmt->bind_param('sss',$col1,$col2,$col3);
if($stmt->execute()) {
$row = $stmt->insert_id ?: null;
if(!empty($row))
{
//query success
}else{
//query failure
}
$stmt->close();
}
$mysqli->close();
if you need more info, i provided a broader example of working with mysqli using the Object Oriented approach here(its in part two of the answer): login session destroyed after refresh

Categories