I'm creating a comment facility for a blog post using PHP and ajax to post the comment so the page does not refresh after a comment is posted.
This is the code that displays the comments when the page is visited. If there are no comments for the post it displays a notice. This all works.
$stmt = $conn->prepare("SELECT comm.comment, comm.comment_date, m.member_screen_name
FROM comments comm
JOIN members m
ON comm.member_id = m.id
WHERE comm.entry_id = ?
ORDER BY comm.comment_date DESC");
$stmt->bind_param("i", $post_id);
$stmt->execute();
$stmt_result = $stmt->get_result();
if ($stmt_result->num_rows > 0) {
while($row = $stmt_result->fetch_assoc()) {
$comment = $row["comment"];
$comment_date = date_create($row['comment_date']);
$comment_date = date_format($comment_date, ' l jS F Y H:i');
$comment_author = $row["member_screen_name"];
$comments .= "<div class='comment_div'><div class='small'><p class='text-info'>posted by $comment_author on $comment_date</p>$comment<hr /></div></div>";
}
}else{
$comments = "<div class='alert alert-primary' role='alert'>Be the first to comment</div>";
}
When the comment form is submitted it calls this function.
$('#submit').click(function (e) {
e.preventDefault();
if (!$('#summernote').summernote('isEmpty')) {
var comment = document.getElementById("summernote").value;
var member_id = 1;
var post_id = 1;
$.ajax ({
type: 'post',
url: 'post_comment.php',
data: {
comment:comment,
member_id:member_id,
post_id:post_id,
},
success: function (response) {
document.getElementById("all_comments").innerHTML=response+document.getElementById("all_comments").innerHTML;
$("#summernote").summernote("reset");
},
});
}else {
alert('Please enter a comment');
}
return false;
});
This is the post_comment.php page
if(isset($_POST['comment'])){
$comments = "";
$comment=$_POST['comment'];
$member_id =$_POST['member_id'];
$post_id =$_POST['post_id'];
if(isset($comment)) {
$stmt = $conn->prepare("INSERT INTO comments (entry_id, member_id, comment) VALUES (?, ?, ?)");
$stmt->bind_param("iis", $post_id, $member_id, $comment);
$stmt->execute();
$entry_id = mysqli_insert_id($conn);
$stmt = $conn->prepare("SELECT comm.comment, comm.comment_date, m.member_screen_name
FROM comments comm
JOIN members m
ON comm.member_id = m.id
WHERE comm.entry_id = ?
AND comm.id = $entry_id
ORDER BY comm.comment_date DESC");
$stmt->bind_param("i", $post_id);
$stmt->execute();
$stmt_result = $stmt->get_result();
if ($stmt_result->num_rows > 0) {
while($row = $stmt_result->fetch_assoc()) {
$comment = $comment;
$comment_date = date_create($row['comment_date']);
$comment_date = date_format($comment_date, ' l jS F Y H:i');
$comment_author = $row["member_screen_name"];
$comments .= "<div class='comment_div' style='background:red'><div class='small'><p class='text-info'>posted by $comment_author on $comment_date</p>$comment<hr /></div></div>";
echo $comments ;
};
exit;
}
}
}else {
header("location: /blog");
exit;
}
If you are the first to comment on a post the comment displays but the "Be the first to comment" notice is still displaying until the page is refreshed.
Try return the response from the server as json. Plus remove the exit and header on your server side.
<script type="text/javascript">
$('#submit').click(function (e) {
e.preventDefault();
if (!$('#summernote').summernote('isEmpty')) {
var comment = document.getElementById("summernote").value;
var member_id = 1;
var post_id = 1;
$.ajax ({
type: 'post',
url: 'post_comment.php',
data: {
comment:comment,
member_id:member_id,
post_id:post_id,
},
dataType : "json",
encode : true,
success: function (data) {
$.each(data, function(index, element){
$('#all_comments').append("<div class='comment_div' style='background:red'><div class='small'><p class='text-info'>posted by " +element.comment_author + "on " + element.post_date+"</p>"+element.comment+"<hr /></div></div>");
});
$("#summernote").summernote("reset");
$('.alert').empty();
},
});
}else {
alert('Please enter a comment');
}
return false;
});
</script>
Then your server side.
<?php
if (isset($_POST['comment'])) {
$comment = $_POST['comment'];
$member_id = $_POST['member_id'];
$post_id = $_POST['post_id'];
$commentsArray = array();
$stmt = $conn->prepare("INSERT INTO comments (entry_id, member_id, comment) VALUES (?, ?, ?)");
$stmt->bind_param("iis", $post_id, $member_id, $comment);
$stmt->execute();
$entry_id = mysqli_insert_id($conn);
$stmt = $conn->prepare("SELECT comm.comment, comm.comment_date, m.member_screen_name
FROM comments comm
JOIN members m
ON comm.member_id = m.id
WHERE comm.entry_id = ?
AND comm.id = ?
ORDER BY comm.comment_date DESC");
$sql->bind_param("ii", $post_id, $entry_id);
$sql->execute();
$sql_result = $sql->get_result();
if ($stmt_result->num_rows > 0) {
while ($row = $stmt_result->fetch_assoc()) {
$comment_date = date_create($row['comment_date']);
$commentsArray[] = array(
'comment' => $comment,
'post_date' = date_format($comment_date, ' l jS F Y H:i');
'comment_author' => $row['member_screen_name']
);
}
}
echo json_encode($commentsArray);
}
Also use the network tab on your browser console to see the response coming from the server.
it is normal for him to behave like this, and at no time will you ask the notification not to appear after the comment.
update your code after the success
$('.alert-primary').hide()
Related
When I send an ajax post request to my getMessages.php file it doesn't return anything.
I've tried manually setting the array values and printing them in the console and that seems to work.
getMessages.php
<?php
require_once "mysqli.php";
$data = array();
if (isset($_POST['getChat']) && !empty($_POST['getChat'])) {
$username = $_SESSION["username"];
$result = mysqli_query($conn, "SELECT msg_startuser, msg, time
FROM messages
WHERE msg_startuser = '{$username}' and msg_enduser = 'mariokiller470'
UNION
SELECT msg_startuser, msg, time
From messages
WHERE msg_startuser = 'mariokiller470' and msg_enduser = '{$username}'
order by time;
");
while ($row = mysqli_fetch_array($result)) {
$data['startuser'] = $row['msg_startuser'];
$data['msg'] = $row['msg'];
}
}
echo json_encode($data);
exit;
?>
js ajax
function getChat() {
$.ajax({
url: 'getMessages.php',
type: 'POST',
data: {getChat: 'yes'},
dataType: 'JSON',
success: function(data) {
// testing
console.log(data.startuser, data.msg);
}
})
}
I want it to print out in the console for testing.
Hi you can try this way:
The php script :
<?php
require_once "mysqli.php";
session_start();// start the session
$data = array();
if (isset($_SESSION["username"])) {
if (isset($_POST["endUser"]) && isset($_POST["action"])) {
$case = $_POST["action"];
$endUser = $_POST["endUser"];
$username = $_SESSION["username"];
switch (case) {
case 'getChat':
$result = mysqli_query($conn, "SELECT msg_startuser, msg, time
FROM messages
WHERE msg_startuser = '{$username}' and msg_enduser = '{$endUser}'
UNION
SELECT msg_startuser, msg, time
From messages
WHERE msg_startuser = '{$endUser}' and msg_enduser = '{$username}'
order by time;
");
while ($row = mysqli_fetch_assoc($resultado)) {
if (isset($row['msg_startuser']) && isset($row['msg'])) {
$temp = array(
"user"=>$row['msg_startuser'],
"msg"=>$row['msg']
);
}
$data[] = $temp;
}
echo json_encode($data);
break;
}
}
}else {
echo "error-403";
}
?>
The javascript :
function getChat() {
return $.ajax({
url: 'getMessages.php',
type: 'POST',
data: {action: 'getChat',endUser:'mariokiller470'},
dataType: 'JSON'
})
}
getChat()
.done(function(response){
console.log(response);
})
Hope it Helps
data is overwritten in the loop again and again, I guess you would like to do something like this:
$x = 0;
while ($row = mysqli_fetch_array ($result)) {
$data[$x]['startuser'] = $row['msg_startuser'];
$data[$x]['msg'] = $ row['msg'];
$x++;
}
Ooops!
I forgot to start the session!
Thanks PatrickQ!
This will solve the problem since you are returning response as objects
An Updates:
You will need to initialize session
and data parameters for an array should be inside the the if statements
Try code below
<?php
require_once "mysqli.php";
session_start();
if (isset($_POST['getChat']) && !empty($_POST['getChat'])) {
$username = $_SESSION["username"];
$data = array();
$result = mysqli_query($conn, "SELECT msg_startuser, msg, time
FROM messages
WHERE msg_startuser = '{$username}' and msg_enduser = 'mariokiller470'
UNION
SELECT msg_startuser, msg, time
From messages
WHERE msg_startuser = 'mariokiller470' and msg_enduser = '{$username}'
order by time;
");
while ($row = mysqli_fetch_array($result)) {
$startuser = $row['msg_startuser'];
$msg = $row['msg'];
$data = array("startuser" =>$startuser, "msg" =>$msg);
}
echo json_encode($data);
exit;
}
?>
so in ajax console. this line of code will work fine
console.log(data.startuser, data.msg);
i wanna have like for my blog posts, it should work like this: user will click on something and it increase that number by +1 and store it in data base, i have a column named post_like in my db. but after increase 0 to 1 (when i try to increase from 1 to 2 or more) i get error.
jquery:
$("#insert_like").click(function(e){
alert('s')
var like = $("#insert_like").val();
like += 1;
var post_id = $("#post_id").val();
$.post("./inc/like.php", {
like: like,
post_id: post_id
}, function(data, status){
$("#insert_like").text(data);
like = 0;
});
});
php:
<?php
if (isset($_POST['like'])) {
require_once 'db.inc.php';
$like = $_POST['like'];
$post_id = $_POST['post_id'];
$q = "UPDATE posts set post_like = ? WHERE post_id=? LIMIT 1";
$stmt = $conn->prepare($q);
$stmt->bind_param('ii', $like, $post_id);
$stmt->execute();
if ($stmt->affected_rows == 1) {
echo "$like";
} else {
echo "error: $stmt->error";
}
$stmt->close();
$conn->close();
} else {
header('Location: ../home.php');
}
html:
<p>Post like: <span id="insert_like" style="cursor: pointer"><?php echo $post_like ?></span> </p>
You can pass the Post Id from javascript and update the likes in the backend. Consider below example:
$("#insert_like").click(function(e){
$.post("./inc/like.php", {
post_id: $("#post_id").val()
}, function(data, status){
$("#insert_like").text(data);
like = 0;
});
});
and in the backend
<?php
if (isset($_POST['like'])) {
require_once 'db.inc.php';
$post_id = $_POST['post_id'];
$q = "UPDATE posts SET post_like = (post_like + 1) WHERE post_id = ?";
$stmt = $conn->prepare($q);
$stmt->bind_param('i', $post_id);
$stmt->execute();
if ($stmt->affected_rows == 1) {
// get the updated likes and return as response.
} else {
echo "error: $stmt->error";
}
$stmt->close();
$conn->close();
} else {
header('Location: ../home.php');
}
Hope this helps.
I have a form in that I am trying to do inline editing and adding using AJAX call.
Firstly I am displaying data in HTML table. And then if enter data into text boxes and click on add button record adding displaying data in HTML table. After I click edit button data showing in the textboxes fine.
But I am getting the ajax response as null.
I couldn't figure it out.
This is my AJAX code PHP file:
$(function() {
$(".scrollingTable tbody a").click(function() {
//debugger;
var link = $(this).attr('href');
var arr = link.split('=');
var id = arr[1];
//alert(id);
$.ajax({
url: "insertgr.php",
type: "POST",
data: {
cntid: id
},
success: function(datas) {
var data = $.parseJSON(datas);
$("#num").val(data.id);
$("#namegr").val(data.vndr_cntname);
$("#designation").val(data.designation);
$("#mobilegr").val(data.vndr_cntmobile);
$("#maildgr").val(data.vndr_cntmail);
}
});
});
});
$(function() {
$('.txtcbt a').click(function() {
debugger;
var cntname, designation, mobile, email, vndrid, id, cid;
cid = $("#num").val();
cntname = $("#namegr").val();
designation = $("#designation").val();
mobile = $("#mobilegr").val();
email = $("#maildgr").val();
vndrid = "<?php echo $selectid; ?>";
//alert(cid);
if (cntname == "" || designation == "" || mobile == "" || email == "") {
alert("fields should not be empty");
} else {
$.ajax({
url: "insertgr.php",
type: "POST",
data: {
id: cid,
name: cntname,
dgnation: designation,
mobileno: mobile,
emailid: email,
vid: vndrid
},
success: function(html) {
var dat = $.parseJSON(html);
alert(html);
alert("it came to success");
$("#num").val("");
$('#namegr').val("");
$('#designation').val("");
$('#mobilegr').val("");
$('#maildgr').val("");
}
});
}
});
});
This is file AJAX is calling:
<?php
require('Assests/connection/connection.php');
error_reporting(0);
$vcntlist = "";
if (!empty($_POST['cntid'])) {
$id = $_POST['cntid'];
$result = mysqli_query($conn, "SELECT `id`, `vndr_cntname`, `designation`, `vndr_cntmobile`, `vndr_cntmail`,`vndr_id` FROM `vndr_cntdtls`where id=$id");
$rowcount = mysqli_num_rows($result);
if ($rowcount > 0) {
$row = mysqli_fetch_array($result);
$vcntid = $row['id'];
$cntname = $row['vndr_cntname'];
$cntdesignation = $row['designation'];
$cntmobile = $row['vndr_cntmobile'];
$cntmail = $row['vndr_cntmail'];
}
}
if (!empty($_POST['name']) && !empty($_POST['dgnation']) &&
!empty($_POST['mobileno']) && !empty($_POST['emailid']) &&
!empty($_POST['vid'])) {
$id = $_POST['id'];
$name = $_POST['name'];
$degination = $_POST['dgnation'];
$mobile = $_POST['mobileno'];
$email = $_POST['emailid'];
$vndrid = $_POST['vid'];
if (empty($_POST['id'])) {
$query = mysqli_query($conn, "INSERT INTO `vndr_cntdtls`(`vndr_cntname`, `designation`, `vndr_cntmobile`, `vndr_cntmail`, `vndr_id`) VALUES ('$name','$degination','$mobile','$email',$vndrid)");
} else {
$update1 = mysqli_query($conn, "UPDATE `vndr_cntdtls` SET `vndr_cntname`='$name',`designation`='$degination',`vndr_cntmobile`='$mobile',`vndr_cntmail`='$email' WHERE id=$id") or die(mysqli_error($conn));
}
$result = mysqli_query($conn, "SELECT DISTINCT `id`, `vndr_cntname`, `designation`, `vndr_cntmobile`, `vndr_cntmail`,vc.vndr_id FROM `vndr_cntdtls` vc INNER JOIN vendors v ON vc.vndr_id=$vndrid") or die(mysqli_error($conn));
$rowcount = mysqli_num_rows($result);
if ($rowcount > 0) {
while ($row = mysqli_fetch_array($result)) {
$vcntid = $row['id'];
$cntname = $row['vndr_cntname'];
$cntdesignation = $row['designation'];
$cntmobile = $row['vndr_cntmobile'];
$cntmail = $row['vndr_cntmail'];
}
}
}
echo json_encode($row);
?>
There could be a lot of ways it is not working.
First:
You need to put a application/json in your php so it can be compatible with the browser you are using.
header('Content-Type: application/json');
echo json_encode($row);
Second:
Why are you doing a while loop and assigning it into an unused variable?
You can simplify it by doing:
$row = mysqli_fetch_array($result);
header('Content-Type: application/json');
echo json_encode($row);
Unless it is multiple rows then:
$rowcount = mysqli_num_rows($result);
$rows = array();
if ($rowcount > 0) {
while ($row = mysqli_fetch_array($result)) {
$rows[] = $row;
}
}
header('Content-Type: application/json');
echo json_encode($row);
Third
null values usually appears when a variable you are trying to use is not initialized. By having the error_reporting turned off it does not display the error.
error_reporting(true);
Fourth
Check also the logs for database error, I assume it has something to do with MySQL query not having to reach the $row initialization.
Fifth
I believe you need to have it fetched as associative array for it to be useful
$row = mysqli_fetch_assoc($result);
I am building a simple messaging system for my website and it seems to be slow and sometimes crashes the browser. Below is the code.
First i wrote an ajax request to get all user chat from database
setInterval(function () {
$.ajax({
type: "GET",
url: "get_chat.php",
dataType: "html",
success: function (response) {
$(".msgView").html(response);
if (response !== lastResponse) {
var audio = new Audio('audio/solemn.mp3')
audio.play()
}
lastResponse = response
}
});
}, 2000);
here is get-chat.php
<?php
$us_id = $_SESSION['log_id'];
//echo empty($_SESSION['hash']) ? 'not set' : $_SESSION['hash'];
$hasher = $_SESSION['hash'];
$mesql =<<<EOF
SELECT from_id, message FROM messager WHERE group_hash = '$hasher';
EOF;
$meret = $db->query($mesql);
while ($merow = $meret->fetchArray(SQLITE3_ASSOC))
{
$from_id = $merow['from_id'];
$messages = $merow['message'];
$usql =<<<EOF
SELECT * FROM users WHERE userid = '$from_id';
EOF;
$uret = $db->query($usql);
while ($urow = $uret->fetchArray(SQLITE3_ASSOC)) {
$from_fname = $urow['fname'];
$from_img = $urow['profimages'];
if ($from_id != $_SESSION['log_id']) {
echo '
<div class="recMsgBubble">
<div class="recBubbleImg"><img src="'.$from_img.'"></div>
<div class="recBubbleMsg">'.$messages.'</div>
</div>';
//<div class='from_bubble'><div class='from_img'><img src='$from_img'></div><p>$messages</p></div><br>
} else {
echo '
<div class="userMsgBubble">
<div class="userBubbleImg"><img src="'.$from_img.'"></div>
<div class="userBubbleMsg">'.$messages.'</div>
</div>';
//<div class='rep_bubble'><div class='rep_img'><img src='$from_img'></div><p>$messages</p></div><br>
}
}
$csql =<<<EOF
SELECT * FROM banks WHERE bname = '$from_id';
EOF;
$cret = $db->query($csql);
while ($crow = $cret->fetchArray(SQLITE3_ASSOC)) {
$from_fname = $crow['bname'];
$from_img = $crow['banklogo'];
if ($from_id = $from_fname) {
echo '<div class="recMsgBubble">
<div class="recBubbleImg"><img src="'.$from_img.'">
</div>
<div class="recBubbleMsg">'.$messages.'</div>
</div>';
} else {
echo '<div class="userMsgBubble">
<div class="userBubbleImg"><img src="'.$from_img.'">
</div>
<div class="userBubbleMsg">'.$messages.'</div>
</div>';
}
}
}
?>
Also to send the chat, an ajax request is used as below
$("#msgSender").submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "send_chat.php",
data: $(this).serializeArray(),
dataType: "json",
success: function(response) {
console.log(response);
},
error: function(response) {
}
});
$('#userMsgField').val("");
});
Here is send_chat.php
<?php
require_once ("db.php");
$db = new MyDB();
session_start();
if (isset($_POST['userMsgField']) && !empty($_POST['userMsgField']) || isset($_POST['hash']) && !empty($_POST['hash']))
{
$my_id = $_SESSION['log_id'];
$rep_msg = $_POST['userMsgField'];
$hash = $_SESSION['hash'];
$flag = 0;
$sql =<<<EOF
SELECT * FROM connect WHERE (user_one = '$my_id' AND hash = '$hash') OR (user_two = '$my_id' AND hash = '$hash');
EOF;
$ret = $db->query($sql);
while ($row = $ret->fetchArray(SQLITE3_ASSOC))
{
$user_one = $row['user_one'];
$user_two = $row['user_two'];
if ($user_one == $my_id)
{
$to_id = $user_two;
}
else
{
$to_id = $user_one;
}
$isql =<<<EOF
INSERT INTO messager (message, group_hash, from_id, flag, to_id) VALUES (:message, :group_hash, :from_id, :flag, :to_id);
EOF;
$bsql =<<<EOF
INSERT INTO chatportal (message, group_hash, from_id, flag, to_id)
VALUES (:message, :group_hash, :from_id, :flag, :to_id);
EOF;
$stmt = $db->prepare($isql);
$bstmt = $db->prepare($bsql);
$stmt->bindValue(':message', $rep_msg, SQLITE3_TEXT);
$stmt->bindValue(':group_hash', $hash, SQLITE3_INTEGER);
$stmt->bindValue(':from_id', $my_id, SQLITE3_INTEGER);
$stmt->bindValue(':flag', $flag, SQLITE3_INTEGER);
$stmt->bindValue(':to_id', $to_id, SQLITE3_TEXT);
$bstmt->bindValue(':message', $rep_msg, SQLITE3_TEXT);
$bstmt->bindValue(':group_hash', $hash, SQLITE3_INTEGER);
$bstmt->bindValue(':from_id', $my_id, SQLITE3_INTEGER);
$bstmt->bindValue(':flag', $flag, SQLITE3_INTEGER);
$bstmt->bindValue(':to_id', $to_id, SQLITE3_TEXT);
$result = $stmt->execute();
$bresult = $bstmt->execute();
if ($reuslt && $bresult)
{
echo "GHood";
}
}
}
I think the reason for it being slow is that it tries to get the messages every 2 seconds. If this is the issue, please how do i fix?
If not what is the solution to this problem? Thanks in advance.
PHP messaging system is slow if you build it from scratch. I use JQuery before but after ES7 and ES8 I starting using the native javascript and it was faster than jquery. There are 3 things you can do to at-least speed it up:
Do not use the jQuery Ajax use the native Ajax, since jQuery is a very large library to load and risky, to begin with.
Buy or use a faster server.
Prevent retrieving the entire message conversation every time the user inputs a message. Use a script that would only get the values that were added during the conversation and limit the message history per view.
You can search the ajax syntax from here https://blog.garstasio.com/you-dont-need-jquery/ajax/
I've got a Rating function that does as follows: Once a user clicks the +1 button, the rating goes up by 1, and saves to MySQL. What I'd like for it to do is once clicked, it changes
the background to a different color as shown below..
( What I'd like for it to do is the "once clicked" ) at the current moment it just updates the number with the background being white)
NOTE: I'm just asking for suggestions or some way to lead me in the right direction, thank you in advance.
Without being clicked:
Once clicked:
php/html form: to submit the +1
<div class="up vote" name="voteUp" id="<?php echo $post_iD;?>">
<div class="wrapper">+<?php echo $VoteRate;?></div>
</div>
AJAX: to update the button
$(function()
{
$(".vote").click(function()
{
var id = $(this).attr("id");
var name = $(this).attr("name");
var dataString = 'id='+ id ;
var parent = $(this);
if (name=='voteUp')
{
$.ajax(
{
type: "POST",
url: "voting/up_vote.php",
data: dataString,
cache: false,
success: function(html)
{
parent.html(html);
}
});
}
return false;
});
});
up_vote.php: submit from the ajax
$ip = $_SERVER['REMOTE_ADDR'];
if($_POST['id'])
{
$sth = $db->prepare("SELECT add_iP FROM PostsRating WHERE post_iD_fk = :id AND add_iP = :ip");
$sth->execute(array(':id' => $_POST['id'], ':ip' => $ip));
if( $sth->fetchColumn() == 0)
{
$sth = $db->prepare("UPDATE posts set voteUp = voteUp+1 where post_iD = :id");
$sth->execute(array(':id' => $_POST['id']));
$sth = $db->prepare("INSERT into PostsRating (post_iD_fk, add_iP) VALUES (:id, :ip)");
$sth->execute(array(':id' => $_POST['id'], ':ip' => $ip));
} else {
$sth = $db->prepare("UPDATE posts set voteUp = voteUp-1 where post_iD = :id");
$sth->execute(array(':id' => $_POST['id']));
$sth = $db->prepare("DELETE FROM PostsRating WHERE post_iD_fk = :id AND add_iP = :ip");
$sth->execute(array(':id' => $_POST['id'], ':ip' => $ip));
}
$sth = $db->prepare("SELECT voteUp FROM posts WHERE post_iD = :id");
$sth->execute(array(':id' => $_POST['id']));
$row = $sth->fetch();
echo $row['voteUp'];
}
In your success callback, why not just set a class to the parent and then update the .wrapper?
success: function(html)
{
parent.addClass("blue");
parent.find(".wrapper").html("+ " + html);
}
When the user refreshes the page and you want to continue to show the blue, you would simply:
<?php
$ip = $_SERVER['REMOTE_ADDR'];
$sth = $db->prepare("SELECT add_iP FROM PostsRating WHERE post_iD_fk = :id AND add_iP = :ip");
$sth->execute(array(':id' => $post_iD, ':ip' => $ip));
$class = ($sth->fetchColumn()) ? " blue" : "";
?>
<div class="up vote<?php echo $class; ?>" name="voteUp" id="<?php echo $post_iD;?>">
<div class="wrapper">+<?php echo $VoteRate;?></div>
</div>
You can change the success function to add the color with .css("background-color","blue") or if you want to have it always blue if the vote_counter is higher than you can add this to the top of your code:
if (parseInt($("#"+id).children(".wrapper").text()) >= 1) {
$("#"+id).children(".wrapper").css("background-color","blue");
}
First of all, you can not have a class name with a space in it - it will be interpreted as two classes, up and vote.
Within the php you can echo something along the lines of (be sure to set dataType to json)
echo(json_encode(array("success"=>true)));
exit();
After which the jquery can handle the response:
function(result) {
var result_string = jQuery.parseJSON(result);
if(result_string.success) {
$(this).children(".wrapper").css("background-color", "blue")
}
}