I have a save feature on my website so that the user can save an item. On the first click it updates and saves fine because it went through the PHP file, but what I am having trouble with is getting the ajax to update the link when clicked the second time since the link is created in the jquery code for updating it with AJAX. (passing the proper ID's is the problem) It should update the heart to red or green and add or remove the word 'Save'. I need to get the proper id updated on the second, third, etc. click.
Here is the jquery code:
I have 2 functions. saveLink and deleteLink.
This is my javascript file:
$(document).on("click", '.del-button', function () {
var savId = $(this).attr('data-sav-id');
deleteLink(savId);
});
$(document).on("click", '.sav-button', function () {
var delId = $(this).attr('data-del-id');
saveLink(delId);
});
function saveLink( saveID ){
var id = saveID;
$.ajax({
method: "POST",
url: "saveLink.php",
dataType: "json",
data: {
'id' : id,
},
success: function(returnID){
var returnID = $.trim(returnID);
if(returnID){
$('#showSaved' + id).html('<span id="removeSaved('+ id +');"><i class="fa fa-heart" style="color:#d52917;"></i></span>');
}
}
});
}
function deleteLink( deleteID ){
var deletedID = deleteID;
$.ajax({
method: "POST",
url: "deleteLink.php",
dataType: "json",
data: {
'deletedID' : deletedID,
},
success: function(deleteIDFunc){
var deleteIDFunc = $.trim(deleteIDFunc);
if(deleteIDFunc){
$('#removeSaved' + deletedID).html('<span id="showSaved('+ deletedID +');">Save <i class="fa fa-heart"></i></span>');
}
else {
alert('Your saved post was not removed. Please try again');
}
}
});
}
Here is the PHP code that handles the initial click:
$query = "SELECT
count(replies.reply_topic) as replyCount,
topics.topic_id,
topics.topic_subject,
topics.topic_date,
topics.topic_cat,
topics.topic_creator,
topics.topic_likes,
users.user_id,
users.username,
profile.profile_id,
profile.profile_pictureMain,
profile.profile_users,
savelink.saveLink_id,
savelink.saveUser_id,
savelink.link_id
FROM
topics
LEFT JOIN
users
ON
topics.topic_creator = users.user_id
LEFT JOIN
replies
ON
replies.reply_topic = topics.topic_id
LEFT JOIN
profile
ON
profile.profile_users = users.user_id
LEFT JOIN
savelink
ON
savelink.link_id = topics.topic_id
GROUP BY
topics.topic_id
ORDER BY
topics.topic_date DESC
LIMIT ?, ?
";
$stmt = $conn->prepare($query);
$stmt->bindParam(1, $start, PDO::PARAM_INT);
$stmt->bindParam(2, $limit, PDO::PARAM_INT);
$stmt->execute();
$returnAmt = $stmt->fetchAll();
if($stmt->rowCount() > 0){
$returnValues = "";
foreach($returnAmt as $row){
$returnValues .=
if(isset($_SESSION['user_session']) && $row['saveUser_id'] == $_SESSION['user_session']){
$returnValues .= '<span id="removeSaved'.$row['saveLink_id'].'"><i class="fa fa-heart" style="color:#d52917;"></i></span>';
}
else if(isset($_SESSION['user_session'])){
$returnValues .= '<span id="showSaved'.$row['topic_id'].'">Save <i class="fa fa-heart"></i></span>';
}
else{
$returnValues .= '</i>';
}
$returnValues .= '</div></div></span></div>
}
echo $returnValues;
Here is the html code for displaying the results:
<div role="tabpanel" class="tab-pane active" id="Top">
<div id="rowDisplayResults">
<!--Display results here-->
</div>
</div>
This is what I would like the save feature to look like. A red heart when saved and green when not.
Should I be adding another variable to the save and delete link functions to pass the proper ID's after the second click?
Any help would be much appreciated. thanks.
Change your code like this. Also change the html for this logic
$(document).on("click", '.del-button', function () {
var savId = $(this).attr('data-sav-id');
deleteLink(savId);
});
$(document).on("click", '.sav-button', function () {
var delId = $(this).attr('data-del-id');
saveLink(delId);
});
function saveLink( saveID ){
var id = saveID;
$.ajax({
method: "POST",
url: "saveLink.php",
dataType: "json",
data: {
'id' : id,
},
success: function(returnID){
var returnID = $.trim(returnID);
if(returnID){
$('#showSaved' + id).html('<span id="removeSaved('+ id +');"><a href="javascript:void();" class="del-button pull-right"'+
' data-sav-id=' + returnID + '"><i class="fa fa-heart" style="color:#d52917;"></i></a></span>');
//onclick="deleteLink('+ returnID +');
}
}
});
}
function deleteLink(deleteID) {
var deletedID = deleteID;
$.ajax({
method: "POST",
url: "deleteLink.php",
dataType: "json",
data: {
'deletedID': deletedID,
},
success: function (deleteIDFunc) {
var deleteIDFunc = $.trim(deleteIDFunc);
if (deleteIDFunc) {
$('#removeSaved' + deletedID).html('<span id="showSaved(' + deletedID + ');"><a href="javascript:void();" '+
'class="pull-right sav-button" data-del-id=' + deleteIDFunc + '">Save <i class="fa fa-heart"></i></a></span>');
}
//onclick="saveLink(' + deleteIDFunc + ');
else {
alert('Your saved post was not removed. Please try again');
}
}
});
}
Related
I'm facing an issue that I can't seem to fix... I wrote some PHP and JavaScript code to be able to like posts on my web application. It works BUT for some pictures when I try to like or dislike the picture it likes or dislikes twice. I don't know why it does that, but because of this I get the error: 500 (internal server error) - Duplicate entry for key 'likes.PRIMARY'.
Here you can see my Likes table [![likes table][1]][1]. Both columns have Primary Key and Not Null. I'm using MySQL Workbench.
The HTML structure for the likes on every post on the page:
<div class="like_container">
<?php if (in_array($newpost->observationID,array_column($likedposts,'liked_obs_id'))): ?>
<button class="like_button" rel="<?= $newpost->observationID?>" >
<img class="icon_like liked" id="icon_like" src="<?= base_url()?>/public/images/heart.svg" style="height: 22px">
</button>
<p class="like_counts" id="like_counts" style="font-size: 18px"><?=$newpost->likes?></p>
<?php else: ?>
<button class="like_button" rel="<?= $newpost->observationID?>" >
<img class="icon_like" id="icon_like" src="<?= base_url()?>/public/images/heart.svg" style="height: 22px">
</button>
<p class="like_counts" id="like_counts" style="font-size: 18px"><?=$newpost->likes?></p>
<?php endif; ?>
</div>
The PHP functions to handle the Likes are as follows:
private $db;
public function __construct()
{
$this->db = \Config\Database::connect();
}
public function clickLike($user, $observation)
{
$query_text = "INSERT INTO a20ux3.likes (userID, observationID)
VALUES (:userID:, :observation:)";
$query_addLike = "UPDATE a20ux3.observations
SET likes = likes + 1
WHERE observationID = :observation:";
$this->db->query($query_addLike, ['observation' => $observation]);
$this->db->query($query_text, ['userID' => $user, 'observation' => $observation]);
}
public function removeLike($user, $observation)
{
$query_text = "DELETE FROM a20ux3.likes
WHERE userID = :userID:
AND observationID = :observation:";
$query_removeLike = "UPDATE a20ux3.observations
SET likes = likes - 1
WHERE observationID = :observation:";
$this->db->query($query_removeLike, ['observation' => $observation]);
$this->db->query($query_text, ['userID' => $user, 'observation' => $observation]);
}
And the JavaScript looks like this:
$(".like_button").click(function (e){
e.preventDefault();
const button = $(this);
let num = button[0].nextElementSibling;
const base_url = '<?php echo base_url();?>';
let obs_id = button.attr("rel");
let icon = button[0].firstElementChild;
if(icon.classList.contains('liked')){
$.ajax({
type: "POST",
url: base_url +"/public/LikeController/removeLike",
data: {ObsID: obs_id},
success: function (result) {
console.log("Removed");
icon.classList.remove("liked");
if ((parseInt(num.innerText) - 1) < 0){
num.innerText = parseInt("0");
}
else {
num.innerText = parseInt(num.innerText) - 1;
}
},
error: function (result) {
console.error("Unliked unsuccessful",result);
}
});
}
else {
$.ajax({
type: "POST",
url: base_url +"/public/LikeController/likePost",
data: {ObsID: obs_id},
success: function (result) {
console.log("Liked");
icon.classList.add('liked');
num.innerText = parseInt(num.innerText) + 1;
},
error: function (result) {
console.error("Liked unsuccessful",result);
}
});
}
});
Again I want to point out that this error only happens when I try to like some posts on the page, not all of them. Hopefully someone can help me out. Many thanks
[1]: https://i.stack.imgur.com/bHF1l.png
I need it to fit and I click on a file to increase the number to 1 and saved in the database
I already have the database created and part of the AJAX code ready, in addition to the number YA INCREMENTA, the issue is that I have an update of the page manually instead of only updating the div
Number to update
<span id="'.$rowRE[id_reclamo].'" class="badge badge-primary badge-pill like">'.$rowRE[positivo].'</span>
Function with ajax
$(document).ready(function () {
$('.like').on('click', function () {
var reclamoID = $(this).attr('id');
if (reclamoID) {
$.ajax({
type: 'POST'
, url: 'like.php'
, data: 'reclamo_id=' + reclamoID
, success: function () {}
});
}
else {
alert("error");
}
});
});
php code
$reclamoID=$_POST['reclamo_id'];
$query = $db->query("UPDATE reclamos SET positivo = positivo +1 WHERE id_reclamo = $reclamoID");
//Count total number of rows
$rowCountTabla = $query->num_rows;
I need you NOT to recharge the entire page if not ONLY THE NUMBER
Return the count in the same request you make when you post your data. Something along the lines of:
PHP:
$reclamoID = pg_escape_string($_POST['reclamo_id']);
$results = $db->query("SELECT positivo FROM reclamos WHERE id_reclamo = '".$reclamoID."'");
// Whatever DB wrapper you're using here... this is just a guess.
$count = $results[0]['positivo'];
echo json_encode(array(
'id' => $reclamoID,
'count' => $count
));
Javascript:
$('.like').on('click', function () {
var element = $(this);
var reclamoID = element.attr('id');
if (reclamoID) {
$.post(
'like.php',
{
reclamo_id: reclamoID
},
function (responseData) {
element.text(responseData.count);
},
'json'
);
}
});
ALWAYS sanitize posted data, to prevent injections and other malicious code.
I have implemented search module with jqueryUI autocomplete in which search suggestions are rendered with their category.
Now i want to make those suggestions clickable,I've already tried select function but its not working,now i stuck in it
My Jquery Code is
$( function() {
$.widget("custom.catcomplete", $.ui.autocomplete, {
_renderMenu: function(ul, items) {
var that = this,
currentCategory = "";
$.each(items, function(index, item) {
if (item.category != currentCategory) {
ul.append("<li class='ui-autocomplete-category'>" + item.category + "</li>");
currentCategory = item.category;
}
that._renderItemData(ul, item);
});
}
});
$( "#search" ).catcomplete({
source : function(request,response){
var term = $("#search").val();
$.ajax({
type : "GET",
url : "ajax/auto_search.php",
dataType : "json",
data : {term : term},
success : function(data)
{
console.log(data);
response($.map(data.list, function(item) {
return {
value: item.content_title,
label: item.content_title,
category: item.category_name,
url : item.url
}
}))
},
select: function( event, ui ) {
//main problem is with item.content_title unable to get its value
window.location.href = 'search.php?mode=content_type&query='+item.content_title;
}
});
}
});
});
php code is
<?php
include '../includes/dbconfig.php';
header('Content-Type: application/json');
$searchTerm = $_GET['term'];
$sql = "SELECT distinct content_title, c.content_title,p.category_name,c.content_url from content_ref_table c inner join category_ref_table p on p.category_id = c.category_id where c.content_title LIKE '%".$searchTerm."%' ORDER BY c.content_title ASC LIMIT 0,10";
$result = mysqli_query($conn,$sql) or die(mysqli_error($conn));
$data_array = array();
while($row = mysqli_fetch_array($result))
{
$data_array['list'][] = array("content_title" => $row['content_title'], "category_name" => $row['category_name'],"url" => $row['content_url'] );
}
echo json_encode($data_array);
?>
**EDIT: how Can I store the item.content_title in a global variable?i think if i'm able to store the item.content_title in variable then it can solve my problem **
I got a problem with blank space and special characters during a POST action using this AJAX function:
function comments(id,postId,user_id) {
var user_comments = encodeURIComponent($("#commentsId_"+id).val());
if(user_comments!=''){
var img = $("#img_"+id).val();
var username = "<?php echo $this->session->userdata('username'); ?>"
$.ajax({
type: "POST",
url: "<?php echo base_url() ?>social/userscomment/" +user_id+"/"+postId+"/"+user_comments,
data:{ user_comments : user_comments},
success: function(data) {
$("#commentsId_"+id).val('');
var $sparkLines = $('.comments_body_'+id);
$("#comments_add_"+id).append('<div id="id' + ($sparkLines.length + 1) + '" class="comments_body_"'+id+'><div class="feed-element comments_body_"'+id+'><a class="pull-left"><strong>'+username+' <i class="fa fa-comment-o"></i></strong></a><div class="media-body">'+user_comments+'<br></div><div class="col-lg-12"><a id="span_'+postId+'" onclick="callajaxcommcool('+postId+')" class="btn btn-xs btn-white"><i class="fa fa-star"></i><span id="span1_'+postId+'" style="display:none;">1</span> Cool </a></div></div></div></div>');
}
});
}
}
The PHP controller:
public function userscomment($comment_id,$post_id,$user_comments){
$this->load->model('comments');
$user_comments = utf8_decode(trim(mysql_real_escape_string($_POST['user_comments'])));
if(!empty($user_comments)){
$data = array("user_id" => $this->session->userdata('user_id'),
"comment_user_id" => $comment_id,
"comments" => $user_comments,
"post_id" => $post_id,
"username" => $this->session->userdata('username')
);
$this->comments->insertComments($data);
//logged user
$userRow = $this->register->get_login($this->session->userdata('user_id'));
redirect('social/userprofile/'.$userRow[0]['username']);
}
}
When an user post a comment like: "a b c d" the results showed in the view is: a%20b%20c%20d, if an user try to wrote a special characters like € i got this results %E2%82%AC
How can i prevent this problem?
EDIT:
Solved the problem was in the AJAX success function, i miss the
'+decodeURIComponent(user_comments)+'
success: function(data) {
$("#commentsId_"+id).val('');
var $sparkLines = $('.comments_body_'+id);
$("#comments_add_"+id).append('<div id="id' + ($sparkLines.length + 1) + '" class="comments_body_"'+id+'><div class="feed-element comments_body_"'+id+'><a class="pull-left"><strong>'+username+' <i class="fa fa-comment-o"></i></strong></a><div class="media-body">'+decodeURIComponent(user_comments)+'<br></div><div class="col-lg-12"><a id="span_'+postId+'" onclick="callajaxcommcool('+postId+')" class="btn btn-xs btn-white"><i class="fa fa-star"></i><span id="span1_'+postId+'" style="display:none;">1</span> Cool </a></div></div></div></div>');}
Edit2: I've performed the code because encodeURIComponent don't allow this characters ~!*()'" , i've used replace functionality to bypass this limit, hope can be helpful.
function subcomments(id,postId,user_id) {
var user_comments = encodeURIComponent($("#commentsId_"+id).val()).replace(/\-/g, "%2D").replace(/\_/g, "%5F").replace(/\./g, "%2E").replace(/\!/g, "%21").replace(/\~/g, "%7E").replace(/\*/g, "%2A").replace(/\'/g, "%27").replace(/\(/g, "%28").replace(/\)/g, "%29");
if(user_comments!=''){
var img = $("#img_"+id).val();
var username = "<?php echo $this->session->userdata('username'); ?>"
$.ajax({
type: "POST",
url: "<?php echo base_url() ?>social/userscommentcool/" +user_id+"/"+postId+"/"+user_comments,
data:{ user_comments : user_comments },
success: function(data) {
$("#commentsId_"+id).val('');
var $sparkLines = $('.comments_body_'+id);
$("#comments_add_"+id).append('<div id="id' + ($sparkLines.length + 1) + '" class="comments_body_"'+id+'><div class="feed-element comments_body_"'+id+'><a class="pull-left"><strong>'+username+' <i class="fa fa-comment-o"></i></strong></a><div class="media-body">'+decodeURIComponent(user_comments)+'<br></div><div class="col-lg-12"><a id="span_'+postId+'" onclick="callajaxcommcool('+postId+')" class="btn btn-xs btn-white"><i class="fa fa-star"></i><span id="span1_'+postId+'" style="display:none;">1</span> Cool </a></div></div></div></div>');
}
});
}
}
Don't use encodeURIComponent when you pass the parameter in an object. You only need that if you're constructing the URL-encoded string yourself. jQuery automatically encodes the parameters in the object, and the result is that it's being encoded twice. So just do:
var user_comments = $("#commentsId_"+id).val();
You should use javascript decodeURI("a%20b%20c%20d") convert it to "a b c d" again in your view.
Using php:
In your view, in the line that you put the encoded value, just use it:
echo urldecode("your_encoded_value");
This question already exists:
Database values are not updating?
Closed 8 years ago.
I am using this code to call ajaxvote.php
$('.vote').click(function(){
$.ajax({
url: 'ajaxvote.php',
type: 'POST',
cache: 'false',
success: function () { alert("Success!"); } ,
error: function () { alert("Error!"); }});
var self = $(this);
var action = self.data('action');
var parent = self.parent().parent();
var postid = parent.data('postid');
var score = parent.data('score');
if (!parent.hasClass('.disabled')) {
if (action == 'up') {
parent.find('.vote-score').html(++score).css({'color':'orange'});
self.css({'color':'orange'});
$.ajax({data: {'postid' : postid, 'action' : 'up'}});
}
else if (action == 'down'){
parent.find('.vote-score').html(--score).css({'color':'red'});
self.css({'color':'red'});
$.ajax({data: {'postid' : postid, 'action' : 'down'}});
};
parent.addClass('.disabled');
This is the code from my webpage
<div class="item" data-postid="<?php echo $rows['ID'] ?>" data-score="<?php echo $rows['VOTE'] ?>">
<div class="vote-span">
<div class="vote" data-action="up" title="Vote up"><i class="fa fa-camera-retro"></i></div>
<div class="vote-score"><?php echo $rows['VOTE'] ?></div>
<div class="vote" data-action="down" title="Vote down"><i class="fa fa-camera-retro"></i></div>
</div>
This is my php code
if ($_SERVER['HTTP_X_REQUESTED_WITH']) {
if (isset($_POST['postid']) && (isset($_POST['action']))) {
$postId = $_POST['postid'];
if (isset($_SESSION['vote'][$postId])) return;
$query = $mysqli - > query("SELECT VOTE from stories WHERE ID = $postId LIMIT 1");
while ($rows = mysqli_fetch_array($query)) {
if ($_POST['action'] === 'up') {
$vote = ++$rows['VOTE'];
} else {
$vote = --$rows['VOTE'];
}
$mysqli - > query("UPDATE stories SET VOTE = $vote WHERE ID = $postId ");
$_SESSION['vote'][$postId] = true;
}
}
}
I know I can connect to database because I can login. I also get the alert success I have set up above, However, the values are not updating in Database.
EDIT
I have added more Ajax code that I had already written.
When posting via ajax, you need to send through the data you actually want to post.
var postData = {name:"Mister",lastName:"Frodo"}; //Array
$.ajax({
url : "ajaxvote.php",
type: "POST",
data : postData,
success: function(data, textStatus, jqXHR)
{
//Handle response
},
error: function (e) {
// Handle error
}
});
In this case, the post ID and score needs to be grabbed. You also need to grab what kind of action is clicked (typically through a click event bind on the divs with class="vote". For example purposes, let's just set it to "up" for now:
var postId = $('div.item').attr('data-postid').val();
var score = $('div.item').attr('data-score').val();
var postData = {postId: postId, score: score, action: 'up'}
You can now post that "postData" to your ajaxvote.php.
Also, you can use jQuery's $.POST method
$.post("ajaxvote.php", { name: "Mister", lastName: "Frodo" } );
Now for parsing your form, have a look at jQuery's serialize which goes through your form takes each input's [name] attribute along with the value to create a data-string.
Example
name=Mister&lastName=Frodo
This is ideal for sending through with the "data" attribute in $.ajax. Have a look at this answer for more regarding jQuery's serialize.