Remove item from session onClick - javascript

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
}

Related

Creating a unique variable for data

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!

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.

Changing PHP function to Javascript/AJAX validation

I want to use AJAX/Javascript with PHP to carry out this following function and not have it all done by PHP itself. I have created a function which deletes an item from the MySQL database. It gives a validation to the user if they want to remove it by selecting Yes or No.
However, how would i change this so that it does the same function but the validation appears as a popupbox, and when Yes or OK is pressed it deletes the item from the database and reloads the page to show it has been removed.
I have provided the PHP code which relates to this function, but i want to specifically change this to using AJAX/Javascript as well in accordance with PHP.
<?php
// Delete Item Question to Admin, and Delete Product if they choose
if (isset($_GET['deleteid'])) {
echo 'Do you really want to delete product with ID of ' . $_GET['deleteid'] . '? Yes | No';
exit();
}
if (isset($_GET['yesdelete'])) {
// remove item from system and delete its picture
// delete from database
$id_to_delete = $_GET['yesdelete'];
$sql = mysqli_query($link,"DELETE FROM products WHERE id='$id_to_delete' LIMIT 1") or die (mysql_error());
// unlink the image from server
// Remove The Pic -------------------------------------------
$pictodelete = ("../inventory_images/$id_to_delete.jpg");
if (file_exists($pictodelete)) {
unlink($pictodelete);
}
header("location: inventory_list.php");
exit();
}
?>
<?php
// This block grabs the whole list for viewing
$product_list = "";
$sql = mysqli_query($link,"SELECT * FROM products ORDER BY date_added DESC");
$productCount = mysqli_num_rows($sql); // count the output amount
if ($productCount > 0) {
while($row = mysqli_fetch_array($sql)){
$id = $row["id"];
$product_name = $row["product_name"];
$price = $row["price"];
$stock = $row["stock"];
$date_added = strftime("%b %d, %Y", strtotime($row["date_added"]));
$product_list .= "Product ID: $id - <strong>$product_name</strong> - £$price - Stock: $stock - <em>Added $date_added</em> <a href='inventory_edit.php?pid=$id'>edit</a> • <a href='inventory_list.php?deleteid=$id'>delete</a><br />";
}
} else {
$product_list = "You have no products listed in your store yet";
}
?>
Your JS-File
$(document).ready(function() {
$('.delete').click(function() {
event.preventDefault();
var deleteId = $(this).parent().attr('id').val();
$.get('path/to/you/phpfile', {deleteId: deleteid}, function(data) {
var confirm = confirm(data);
if (confirm==true) {
$.get('path/to/you/phpfile', {yesdelete: 1});
}
});
});
});
In your PHP-File you have to remove header('Location: ...') and the block which grabs the list, wrap it in a function or etract it to another php file to call it with the a simliar ajax-command I used above. And you have to change th $product_list in the while-loop.
Product ID: <div id="$id">$id - <strong>$product_name</strong> - £$price - Stock: $stock - <em>Added $date_added</em> <a href='inventory_edit.php?pid=$id'>edit</a> • <div class="delete">Delete</div></div><br />
jQuery get the id-value of his parent-div. It´s actually not the best way, but something like this should work.

Using ajax to display new database inputs without refreshing the page

I am using ajax to post comments to a certain page, I have everything working, except for when the user posts a comment I would like it to show immediately without refreshing. The php code I have to display the comments is:
<?php
require('connect.php');
$query = "select * \n"
. " from comments inner join blogposts on comments.comment_post_id = blogposts.id WHERE blogposts.id = '$s_post_id' ORDER BY comments.id DESC";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
$c_comment_by = $row['comment_by'];
$c_comment_content = $row['comment_content'];
?>
<div class="comment_box">
<p><?php echo $c_comment_by;?></p>
<p><?php echo $c_comment_content;?></p>
</div>
<?php } ?>
</div>
</div>
<?php
}
}
and the code I have to post comments is:
<?php
$post_comment = $_POST['p_post_comment'];
$post_id = $_POST['p_post_id'];
$post_comment_by = "Undefined";
if ($post_comment){
if(require('connect.php')){
mysql_query("INSERT INTO comments VALUES (
'',
'$post_id',
'$post_comment_by',
'$post_comment'
)");
echo " <script>$('#post_form')[0].reset();</script>";
echo "success!";
mysql_close();
}else echo "Could no connect to the database!";
}
else echo "You cannot post empty comments!"
?>
JS:
function post(){
var post_comment = $('#comment').val();
$.post('comment_parser.php', {p_post_comment:post_comment,p_post_id:<?php echo $post_id;?>},
function(data)
{
$('#result').html(data);
});
}
This is what I have for the refresh so far:
$(document).ready(function() {
$.ajaxSetup({ cache: false });
setInterval(function() {
$('.comment_box').load('blogpost.php');
}, 3000);.
});
Now what I want to do is to use ajax to refresh the comments every time a new one is added. Without refreshing the whole page, ofcourse. What am I doing wrong?
You'll need to restructure to an endpoint structure. You'll have a file called "get_comments.php" that returns the newest comments in JSON, then call some JS like this:
function load_comments(){
$.ajax({
url: "API/get_comments.php",
data: {post_id: post_id, page: 0, limit: 0}, // If you want to do pagination eventually.
dataType: 'json',
success: function(response){
$('#all_comments').html(''); // Clears all HTML
// Insert each comment
response.forEach(function(comment){
var new_comment = "<div class="comment_box"><p>"+comment.comment_by+"</p><p>"+comment.comment_content+"</p></div>";
$('#all_comments').append(new_comment);
}
})
};
}
Make sure post_id is declared globally somewhere i.e.
<head>
<script>
var post_id = "<?= $s_post_id ; ?>";
</script>
</head>
Your new PHP file would look like this:
require('connect.php');
$query = "select * from comments inner join blogposts on comments.comment_post_id = blogposts.id WHERE blogposts.id = '".$_REQUEST['post_id']."' ORDER BY comments.id DESC";
$result = mysql_query($query);
$all_comments = array() ;
while ($row = mysql_fetch_array($result))
$all_comments[] = array("comment_by" => $result[comment_by], "comment_content" => $result[comment_content]);
echo json_encode($all_comments);
Of course you'd want to follow good practices everywhere, probably using a template for both server & client side HTML creation, never write MySQL queries like you've written (or that I wrote for you). Use MySQLi, or PDO! Think about what would happen if $s_post_id was somehow equal to 5' OR '1'='1 This would just return every comment.. but what if this was done in a DELETE_COMMENT function, and someone wiped your comment table out completely?

radio button update from javascript to mysql

I am working on a widget in the zend framework and i cannot get the radio button value to update the database. Could someone help. Maybe someone sees something i dont.
thanks in advance.
Here is a sample of the radio html:
<div class="vote_block">
<form class="data_form">
<ul class="input_radio_group">
<li>
<input id="mediaRating1" class="radioBtnClass" type="radio" title="Poor" value=".1" name="rating">
<label class="label_radio">Poor</label>
<div class="clear"></div>
</li>
</ul>
<button id="rateVoteButton" class="button"><span><?php echo $this->translator('send_button'); ?></span></button>
</form>
I only posted one radio button so you can get an idea of what i have.
Here is the Javascript on the page:
<script type="text/javascript">
$(document).ready(function() {
$('#rateVoteButton').click(function() {
var rating = Array();
$(this).parents('.rating_block').find('li input').each(function() {
if ($(this).attr('checked') == true) {
rating.push($(this).attr('value'));
});
if (rating.length > 0) {
var data = $.toJSON({
'set_id': '<?php echo $this->set->set_id; ?>',
'rating': '<?php # echo $this->rating; ?>'
});
}
}
});
});
Now the widget page that acts like the controller:
protected function _prepareShow()
{
$setId = $this->_request->getParam('set_id');
$rating = $this->_request->getParam('rating');
$conn = XXX_Db_Connection::factory()->getSlaveConnection();
$setDao = XXX_Model_Dao_Factory::getInstance()->setModule('media')->getSetDao();
$setDao->setDbConnection($conn);
$data = Zend_Json::encode(array('set_id' => $setId, 'rating' => $rating));
$this->_view->assign('rating', $rating);
$this->_view->assign('data', $data);
}
protected function _prepareResult()
{
$setId = $this->_request->getParam('set_id');
$rating = $this->_request->getParam('rating');
$conn = XXX_Db_Connection::factory()->getMasterConnection();
$setDao = XXX_Model_Dao_Factory::getInstance()->setModule('media')->getSetDao();
$setDao->setDbConnection($conn);
$setDao->increaseRating($rating);
$data = Zend_Json::encode(array('set_id' => $setId, 'rating' => $rating));
$this->_view->assign('rating', $rating);
$this->_view->assign('data', $data);
}
Last but not least here is the sql statement:
public function increaseRating($rating)
{
$sql = sprintf("UPDATE " . $this->_prefix . "media_set
SET rating = rating + '%s'
WHERE set_id = '%s'",
mysql_real_escape_string($rating->rating),
mysql_real_escape_string($rating->set_id));
mysql_query($sql);
return mysql_affected_rows();
}
When a radio is selected and you hit the button i do get a ?rating=.1 after the link in the address bar but no update in database.
Any suggestions will help. Thanks again.

Categories