I have been working on Like and Unlike feature with jQuery, AJAX and PHP. I am getting jQuery post request from indirect page. For example I have 2 PHP pages, viewProfile.php and LikeMail.php. LikeMail.php is being called by AJAX function in viewProfile.php.
Here is Section of viewProfile.php page's description
-----------------
| Like/Unlike |
-----------------
Here is button which actually comes from LikeMail.php by this AJAX function:
function like()
{
var req = new XMLHttpRequest();
req.onreadystatechange = function()
{
if(req.readyState==4 && req.status==200)
{
document.getElementById('like1').innerHTML=req.responseText;
}
}
req.open('POST','LikeMail.php','true');
req.send();
}
setInterval(function(){like()},1000);
HTML:
<div id="like1"></div>
Output is being shown here in this div. Button above may be Like or Unlike depends on the condition in LikeMail.php which will be described below in LikeMail.php description section.
When one of them (buttons) Like or Unlike is clicked. It then calls respective jQuery click function which sends post request to LikeMail.php.I have mentioned Indirect page in title because Like or Unlike buttons actually exists in LikeMail.php page. But due to AJAX call these buttons are being shown in viewProfile.php page. So I then send post requests through viewProfile.php to actual page LikeMail.phpIt is jQuery post for Unlike button
$(document).ready(function(){
$('#Unlike').unbind().click(function(){
$.post("LikeMail.php",
{Unlike: this.id},
function(data){
$('#response').html(data);
}
);
});
});
It is jQuery post or Like button
$(document).ready(function(){
$('#Like').unbind().click(function(){
$.post("LikeMail.php",
{Like: this.id},
function(data){
$('#response').html(data);
}
);
});
});
End of description section of viewProfile.php page
Here is Section of LikeMail.php page's description
Like or Unlike button is shown in viewProfile.php page depends upon this code:
$check_for_likes = mysqli_query($conn, "SELECT * FROM liked WHERE user1='$user1' AND user2='$user2'");
$numrows_likes = mysqli_num_rows($check_for_likes);
if (false == $numrows_likes) {
echo mysqli_error($conn);
}
if ($numrows_likes >= 1) {
echo '<input type="submit" name="Unlike" value="Unlike" id="Unlike" class="btn btn-lg btn-info edit">';
}
elseif ($numrows_likes == 0) {
echo '<input type="submit" name="Like" value="Like" id="Like" class="btn btn-lg btn-info edit">';
}
Button depends upon these two above conditions.
Now when Like button is clicked, post request from viewProfile.php comes here.
if(isset($_POST['Like'])) //When Like button in viewProfile.php is clicked then this peace of code inside if condition should run and insert some record in database
{
$total_likes = $total_likes+1;
$like = mysqli_query($conn, "UPDATE user SET user_Likes = '$total_likes' WHERE user_id = '$user2'");
$user_likes = mysqli_query($conn, "INSERT INTO liked (user1,user2) VALUES ('$user1','$user2')");
$query3 = "INSERT INTO notification (user1, user2, alert, notificationType) VALUE ('$user1','$user2','unchecked','like')";
if (mysqli_query($conn, $query3)) {
echo "Like";
} else {
echo mysqli_error($conn);
}
}
Similarly when Unlike button is clicked. This peace of code should run.
if(isset($_POST['Unlike'])) //This is the condition for Unlike button. It should delete record from databse
{
$total_likes = $total_likes-2;
$like = mysqli_query($conn, "UPDATE user SET user_Likes='$total_likes' WHERE user_id='$user2'");
$remove_user = mysqli_query($conn, "DELETE FROM liked WHERE user1='$user1' AND user2='$user2'");
$query3 = "DELETE FROM notification WHERE user1='$user1' AND user2='$user2' AND notificationType='like'";
$check = mysqli_query($conn, $query3);
if ($check) {
echo "Unlike";
} else {
echo mysqli_error($conn);
}
}
Problem:
Main problem is that jQuery post request is not being sent from viewProfile.php to LikeMail.php. Is there any way to send jQuery post request from indirect page?
Related
Im a beginner in PHP. I want to add the Functionality to like button. Whenever a user clicks like button then the insert query is to be run to insert values in db. There are several images on home page, the corresponding productimage info(productid) must be inserted in product_likes db.`
<?php
$user_name=$_SESSION['user_name'];
$query="SELECT * FROM product_info";
$result= mysqli_query($con, $query);
while ($row = mysqli_fetch_array($result)) {
?>
<div class="w3-container"><br>
<img src="<?php echo "img/product_img/".$row['productimage'].""; ?>">
<p><b>Product Name: </b><?php echo"".$row["productname"].""?><br>
</p>
<form id="like" method="post" action="home1.php">
<button type="submit" name="like"><i class="fa fa-heart"></i> Like</button>
<?php
if(isset($_POST['like'])){
$result=mysqli_query($con,"INSERT INTO product_likes VALUES ('','".$row['productid']."','".$row1['sellerid']."','".$buyerid."')");
}
?>
</form>
</div>
<?php } ?>`
But whenever I run this the same productid, sellerid and buyerid corresponding to first image are inserted in database and only the first image is displayed. Is there a way to correct this issue?
First thing that you need to understand is, PHP is server side language, gets executed before the client, and JavaScript is client side language, gets executed after the server side has finished processing and there's no going back to the server.
When you want to do something like speaking to a server based on user's behaviour, you need to have an end-point configured and fire an AJAX call to the server. Simple example using jQuery to like a post would be:
$(function() {
$("a").click(function(e) {
e.preventDefault();
$this = $(this);
if ($(this).text().trim() == "Like") {
$.post("/posts/like", {
PostID: 1
}, function(res) {
if (res == "success")
$this.text("Unlike");
});
$this.text("Unlike");
} else {
if ($(this).text().trim() == "Unlike") {
$.post("/posts/unlike", {
PostID: 1
}, function(res) {
if (res == "success")
$this.text("Like");
});
$this.text("Like");
}
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Like
The above example kinda "works", because of the fall-back, but pretty much this is the concept. The whole PHP code that makes the "Like" or "Unlike" should be given separately and using jQuery's AJAX function, you need to fire it off.
Both the above URLs: /posts/unlike and /posts/like take in a data parameter PostID and based on that make the necessary changes in the database.
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.
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.
I am using a custom mvc framework and have added a favourite button. Once pressed this displays a 'successfully added to favourites' div, when clicked again it displays a 'successfully removed from favourites' div.
My query works fine, adding and deleting from my favourite table as it should.
What I would like to do now is change the state of the button depending on the selection. For example, if the user has the book in their favourites add btn-success class, if the user hasn't, use the btn-default class.
I'm not sure the best way to approach this. I'm new to php and js so any advice or direction is appreciated. I have tried adding toggleClass to my JS but it's not working. Do I need to perform a query/check on pageLoad?
I have included my code below for reference.
itemView.php
echo
'<td>
<button id="fav" value="'.$book->id.'" type="button" class="btn btn-default"></button>
</td>';
JS (in itemView.php)
$(document).ready(function(){
$( "#fav" ).click(function(){
book_id = $(fav).val();
$.ajax({
type: 'POST',
url: '<?php echo URL; ?>books/checkFav',
data: {book_id:book_id},
success: function () {
window.location.reload(true);
$("#fav").addClass( "btn-success" );
}//end success
});//end ajax
});
});
my checkFav function
public function checkFav($bookid,$userid)
{
$bookid=$_REQUEST['book_id'];
$userid=$_SESSION['user_id'];
$sql = "SELECT * FROM favourite WHERE book_id = :book_id AND user_id = :user_id";
$query = $this->db->prepare($sql);
$query->bindParam(':user_id', $userid);
$query->bindParam(':book_id', $bookid);
$query->execute();
$rows_found = $query->fetchColumn();
if(empty($rows_found)) {
$sql = "INSERT INTO favourite (book_id, user_id) VALUES (:book_id, :user_id)";
$query = $this->db->prepare($sql);
$query->bindParam(':user_id', $userid);
$query->bindParam(':book_id', $bookid);
$query->execute();
if ($query->rowCount() == 1) {
// successful add to favs
$_SESSION["feedback_positive"][] = FEEDBACK_ADDED_TO_FAVS;
return true;
}
} else {
$sql = "DELETE FROM favourite WHERE book_id = :book_id AND user_id = :user_id";
$query = $this->db->prepare($sql);
$query->bindParam(':user_id', $userid);
$query->bindParam(':book_id', $bookid);
$query->execute();
if ($query->rowCount() > 0) {
// successful remove from favs
$_SESSION["feedback_negative"][] = FEEDBACK_REMOVED_FROM_FAVS;
return true;
}
}
}
Use session variable in the ajax request script and using that session variable in page where button exist you can play with button css. for example:
Put this code where Button exists.
$css = "btn_default";
if($_SESSION['btnClicked'] == "success") {
$css = "btn_success";
}
Use $css variable in the button class like--
<button id="fav" value="'.$book->id.'" type="button" class="btn <?php echo $css?>"></button>
This session will manage in the ajax script where in you are adding and deleting favourite.
set session value
$_SESSION['btnClicked'] = 'success'
below the line
$_SESSION["feedback_positive"][] = FEEDBACK_ADDED_TO_FAVS;
and unset the session
unset($_SESSION['btnClicked']);
after the line.
$_SESSION["feedback_negative"][] = FEEDBACK_REMOVED_FROM_FAVS;
I've been working on a 9gag like page. I tried to integrate a voting system which has been made by another guy, because I'm not really familiar with AJAX requests, and it just doesn't want to work.
My index.php loads five posts from the mySQL database then it appends them to the main div. After you scroll down it appends five more etc. This is done by an AJAX request which works like a charm.
When I append it to the div by AJAX, I also append some variables in the div so I can then use it for another AJAX request and this is where the problem occurs. It just doesn't do any AJAX requests. After an hour of debugging I've come to question whether one can append some data to a div, which doesn't exist in the original index.php and then run AJAX requests with it.
I won't post the pagination.js and it's stuff here because it works, I'm only going to post the ajax.php request where it could go wrong:
<?php
include 'config/connection.php';
$db = "test";
$table = "posts";
$offset = is_numeric($_POST['offset']) ? $_POST['offset'] : die();
$postnumbers = is_numeric($_POST['number']) ? $_POST['number'] : die();
$run = mysqli_query($con,"SELECT * FROM $db.$table ORDER BY id DESC LIMIT ".$postnumbers." OFFSET ".$offset);
while($row = mysqli_fetch_array($run)) {
echo " <article>\n";
echo " <div id='title'><h1>".utf8_encode($row['title'])."</h1></div>\n";
echo " <div id='image'><img src='posts/".$row['dDate']."/".$row['image']."'></div>\n";
echo " <div id='text' class='item' data-postid='".$row['id']."' data-score='".$row['vote']."'>\n";
echo " <p>Beküldte: ".$row['postedBy']."\n";
echo " <div class='vote-span'><!-- voting-->\n";
echo " <div class='vote' data-action='up' title='Vote up'>\n";
echo " <i class='icon-chevron-up'></i>\n";
echo " </div><!--vote up-->\n";
echo " <div class='vote-score'>".$row['vote']."</div>\n";
echo " <div class='vote' data-action='down' title='Vote down'>\n";
echo " <i class='icon-chevron-down'></i>\n";
echo " </div><!--vote down-->\n";
echo " </div>\n";
echo " </div>\n";
echo " </article>\n";
}
?>
The output looks like this:
<article>
<div id='title'><h1>Azért azt mondtam már hogy héjhó halihó, de igazából yolo, mert nem is igaz az, hogy ez tök gáz lenne.</h1></div>
<div id='image'><img src='posts/2014-08-23/Screen Shot 2014-06-29 at 1.00.45 PM.png'></div>
<div id='text' class='item' data-postid='52' data-score='0'>
<p>Beküldte: zsombor
<div class='vote-span'><!-- voting-->
<div class='vote' data-action='up' title='Vote up'>
<i class='icon-chevron-up'></i>
</div><!--vote up-->
<div class='vote-score'>0</div>
<div class='vote' data-action='down' title='Vote down'>
<i class='icon-chevron-down'></i>
</div><!--vote down-->
</div>
</div>
</article>
But, when I inspect the resource it's not in index.php (of course) but only in an ajax.php file, which is appended to the index.php.
Here is the votingsys.js file:
$(document).ready(function(){
// ajax setup
$.ajaxSetup({
url: '../vote.php',
type: 'POST',
cache: 'false'
});
// any voting button (up/down) clicked event
$('.vote').click(function(){
var self = $(this); // cache $this
var action = self.data('action'); // grab action data up/down
var parent = self.parent().parent(); // grab grand parent .item
var postid = parent.data('postid'); // grab post id from data-postid
var score = parent.data('score'); // grab score form data-score
// only works where is no disabled class
if (!parent.hasClass('.disabled')) {
// vote up action
if (action == 'up') {
// increase vote score and color to orange
parent.find('.vote-score').html(++score).css({'color':'orange'});
// change vote up button color to orange
self.css({'color':'orange'});
// send ajax request with post id & action
$.ajax({data: {'postid' : postid, 'action' : 'up'}});
}
// voting down action
else if (action == 'down'){
// decrease vote score and color to red
parent.find('.vote-score').html(--score).css({'color':'red'});
// change vote up button color to red
self.css({'color':'red'});
// send ajax request
$.ajax({data: {'postid' : postid, 'action' : 'down'}});
};
// add disabled class with .item
parent.addClass('.disabled');
};
});
});
aaaand the vote.php file:
include('config/connection.php');
# start new session
session_start();
if ($_SERVER['HTTP_X_REQUESTED_WITH']) {
if (isset($_POST['postid']) AND isset($_POST['action'])) {
$postId = (int) mysql_real_escape_string($_POST['postid']);
# check if already voted, if found voted then return
if (isset($_SESSION['vote'][$postId])) return;
# connect mysql db
dbConnect();
# query into db table to know current voting score
$query = mysql_query("
SELECT vote
from posts
WHERE id = '{$postId}'
LIMIT 1" );
# increase or dicrease voting score
if ($data = mysql_fetch_array($query)) {
if ($_POST['action'] === 'up'){
$vote = ++$data['vote'];
} else {
$vote = --$data['vote'];
}
# update new voting score
mysql_query("
UPDATE posts
SET vote = '{$vote}'
WHERE id = '{$postId}' ");
# set session with post id as true
$_SESSION['vote'][$postId] = true;
# close db connection
dbConnect(false);
}
}
}
?>
So is it possible to use another AJAX request like this or am I doing something really wrong?
I'm using jQuery 1.4.3.
Aha, I bet I know what the problem is. You have five initial divs, which have click event handlers attached to them via this:
$('.vote').click(function(){ ... });
However, you are adding new divs via an infinite scroll device, and these do not have events attached to them. That is correct behaviour, since you are not re-running the code to attach them again.
There is a clever device in jQuery that will help you get around this. It lets you attach events to things now and in the future. To use it, try this:
$('container-selector').on('click', '.vote', function() { ... });
The on method with a 'click' parameter is just the new preferred way of attaching events in jQuery, and if you add your handler as a second parameter it will just do the same as now. However if you add the new parameter, '.vote', it will attach the event to anything matching this inside the overall container selector, even if it did not exist at the time of attaching the event.
You can use 'body' for the container selector here, but for performance reasons it is a good idea to be more specific than that. Just use whatever CSS selector will contain all of the divs to which you wish to attach this particular event handler.