Check my image all comment show in one post i am pass post_id 53 56 here is 53 comment and 56 comment you see but it show 53 comment in 56 post i have post and comments system like facebook but my problem is that all comments show in last post. please check it my code i have try many method but it's not working if you have any good solution soo please help me
Controller
public function commentlist(){
$conn = mysqli_connect("localhost","root","","finance");
$memberId = 1;
$sql = "SELECT * FROM tbl_comment INNER JOIN signup ON tbl_comment.u_id = signup.id";
$result = mysqli_query($conn, $sql);
$record_set = array();
while ($row = mysqli_fetch_assoc($result)) {
array_push($record_set, $row);
}
mysqli_free_result($result);
mysqli_close($conn);
echo json_encode($record_set);
}
public function commentadd(){
$conn = mysqli_connect("localhost","root","","finance");
$u_id = $this->session->userdata('log_in')['id'];
$u_image = $this->session->userdata('log_in')['image'];
$commentId = isset($_POST['comment_id']) ? $_POST['comment_id'] : "";
$comment = isset($_POST['comment']) ? $_POST['comment'] : "";
$postID = isset($_POST['tmp']) ? $_POST['tmp'] : "";
$name = array();
$name[0] = $this->session->userdata('log_in')['f_name'];
$name[1] = $this->session->userdata('log_in')['l_name'];
$commentSenderName = implode(" ", $name);
$sql = "INSERT INTO tbl_comment(post_id, parent_comment_id,u_id,u_image,comment,comment_sender_name,date) VALUES ('" . $postID . "','" . $commentId . "','" . $u_id . "','" . $u_image . "','" . $comment . "','" . $commentSenderName . "','" . $date . "')";
$result = mysqli_query($conn, $sql);
if (! $result) {
$result = mysqli_error($conn);
}
echo $result;
}
this is my view file
View
<form id="frm-comment_<?php echo $id;?>">
<div class="input-row_<?php echo $id;?>">
<?php if($this->session->userdata('log_in')['image'] !=NULL ): ?>
<img src="<?php echo base_url(); ?>uploads/<?php echo $this->session->userdata('log_in')['image'];?>" style="height:42px; width:42px;" class="img-circle">
<?php else : ?><img src="<?php echo base_url('assets/images/generic-avatar.jpg'); ?>" style="height:42px; width:42px;" class="img-circle">
<?php endif; ?>
<input type="hidden" name="comment_id" id="commentId_<?php echo $id; ?>"/>
<input type="hidden" name="tmp" id="tmp" value="<?php echo $id;?>" />
<input class="input-field" type="text" name="comment" id="comment_<?php echo $id; ?>" placeholder="Write a Comment..">
</div>
<input type="button" class="btn-submit" id="submitButton_<?php echo $id;?>" value="Comment" >
<div id="comment-message_<?php echo $id;?>" style='display: none;'>Comments Added Successfully!</div>
<div class="output_<?php echo $id?>" ></div>
</form>
</div>
</div>
</div>
</div>
Script
<script>
$( "#com_<?php echo $id; ?>" ).click(function() {
$("#comment_<?php echo $id;?>").focus();
});
function postReply(commentId) {
$('#commentId_<?php echo $id; ?>').val(commentId);
$("#comment_<?php echo $id; ?>").focus();
}
$(document).ready(function () {
listComment();
});
$("#submitButton_<?php echo $id;?>").click(function () {
$("#comment-message_<?php echo $id;?>").css('display', 'none');
var str = $("#frm-comment_<?php echo $id;?>").serialize();
$.ajax({
url: "<?php echo base_url();?>finance/commentadd",
data: str,
type: 'post',
success: function (response)
{
var result = eval('(' + response + ')');
if (response)
{
$("#comment-message_<?php echo $id;?>").css('display', 'inline-block');
$("#comment_<?php echo $id; ?>").val("");
$("#commentId_<?php echo $id; ?>").val("");
listComment();
} else
{
alert("Failed to add comments !");
return false;
}
}
});
});
function listComment(){
$.post("<?php echo base_url();?>finance/commentlist",
function (data) {
var data = JSON.parse(data);
var comments = "";
var replies = "";
var item = "";
var parent = -1;
var results = new Array();
var list = $("<ul class='outer-comment'>");
var item = $("<li>").html(comments);
for (var i = 0; (i < data.length); i++)
{
var commentId = data[i]['comment_id'];
var post_id = data[i]['post_id'];
parent = data[i]['parent_comment_id'];
if (parent == "0")
{comments = " \ <div class='comment-row'><div class='comment-info'>\ <img src='<?php echo base_url(); ?>uploads/"+data[i]['image']+"' class='img-circle' style='height:47px; width:47px; border:1px solid white;'>\<div class='comment-text'>\ <span>" + data[i]['post_id'] + "</span><span class='posted-by'>" + data[i]['comment_sender_name'] + "</span> " + data[i]['comment'] + "</div>\
</div>\
<div>\
<a class='btn-reply' style='font-size:14px;' onClick='postReply(" + commentId + ")'> Reply</a>\
<span class='posted-at' style='font-size:12px;'>" + data[i]['date'] + "</span>\
</div>\
</div>";
var item = $("<li>").html(comments);
list.append(item);
var reply_list = $('<ul>');
item.append(reply_list);
listReplies(commentId, data, reply_list);
}
}
$(".output_<?php echo $id?>").html(list);
});
}
function listReplies(commentId, data, list) {
for (var i = 0; (i < data.length); i++)
{
if (commentId == data[i].parent_comment_id)
{
var comments = "\ <div class='comment-row'><div class='comment-info'>\ <img src='<?php echo base_url(); ?>uploads/"+data[i]['image']+"' class='img-circle' style='height:47px; width:47px; border:1px solid white;'>\
<div class='comment-text'> <span class='posted-by'>" + data[i]['comment_sender_name'] + "</span> " + data[i]['comment'] + "</div>\
</div>\
<div>\
\ <span class='posted-at' style='font-size:12px;'>" + data[i]['date'] + "</span>\
</div>\
</div>";
var item = $("<li>").html(comments);
var reply_list = $('<ul>');
list.append(item);
item.append(reply_list);
listReplies(data[i].comment_id, data, reply_list);
}
}
}
</script>
<?php }?>
I think your code is complex because there is not need to save user image ,name in comment table ,you need to use only comment id(auto increment) post id, user id , comment.
Yo get all comments for particular post you should fetch by post ir for that post.
Example :- when user click on particular post , suppose its post id is 1 then as click click on this you have to pass a request with this post id to comment table where query will match this post id in comment id if this condition true then redirect page to view with all comment and show them.
Controller
Query:- $this->model_name->function_name($id);
In model
$this->db->where('post_id', $id);
$this->db->get('comment_table')->result_array();
This query will fetch all comment for clicked post.
Related
I'm trying to create a system of photos of a product, where the administrator if he wants to add remove or change the position of the photos he does everything by the form.
Form:
<form role="form" id="editProductForm" enctype="multipart/form-data">
<div id="SubPhotos" class="mt-3" style="overflow: auto; white-space: nowrap;">
<hr>
<div class="form-group mt-0 col-md-3">
<label for="uploadPhoto" class="btn btn-primary" role="button" style="cursor:pointer">Add Photo <i class="fas fa-plus"></i></label>
<input type="file" id="uploadPhoto" onchange="readURL(this);" style="display:none;">
</div>
<div class="d-flex">
<label><span id="badgeMainPicture" class='badge badge-primary ml-2'>Main Picture</span></label>
<label class="ml-auto"><span id="badgeTotalPhotos" class='badge badge-secondary'>Amount of Photos: <?php echo count($productImages) ?> de 10</span></label>
</div>
<div id="droppable" style="display: flex;">
<?php $index = 1;
for ($i = 0; $i < count($productImages); $i++) { ?>
<div id="photo<?php echo $index ?>" class="form-group col-lg-3 draggable">
<img id="preview-img" <?php echo isset($productImages[$i]) ? 'src="' . $site . $productImages[$i]['ImagePath'] . '"' : '' ?> height="300px" width="242px" />
<button id="removerPhoto<?php echo $index ?>" class="btn btn-danger btn-removerPhoto shadow-lg" type="button" onclick="removePhoto(<?php echo $index ?>)"><i class="fas fa-times"></i></button>
</div>
<?php
$index++;
} ?>
</div>
</div>
<hr>
<div class="d-flex">
<button type="submit" id="editProduct" class="ml-auto mr-auto btn btn-primary mt-5">Modify Product</button>
</div>
</form>
Contains remove button, draggable to change positions and add photos, everything works fine CLIENT-SIDE
After submit form:
$("#editProductForm").submit(function(e) {
e.preventDefault();
var index = 1;
$(".draggable").each(function() {
var image = $(this).find("#preview-img").attr("src");
var id = $(this).attr("id").substring(4);
if (image.indexOf("https://") > -1) {
$("#photo" + id).attr("id", "photo" + index);
} else {
$("#picture" + id).attr("name", "picture" + index);
}
index++;
});
var formData = new FormData(this);
var index = 1;
$(".draggable").each(function() {
var image = $(this).find("#preview-img").attr("src");
var id = $(this).attr("id").substring(4);
if (image.indexOf("https://") > -1) {
formData.append('picture' + index, image);
} else {
$("#picture" + id).attr("name", "picture" + index);
}
index++;
});
$.post({
url: '<?php echo $site ?>/admin/painel/modifyproduct.php',
data: formData,
cache: false,
contentType: false,
processData: false,
success: function(data) {
}
});
});
Now comes the question, my code has bug and I don't know how to solve SERVER-SIDE:
function createImage($id, $productCategory)
{
global $db;
$db->query("DELETE FROM pictures WHERE ProductID='$id'");
if (!file_exists("../../../pictures/produtos/$productCategory/MTA$id/")) {
mkdir("../../../pictures/produtos/$productCategory/MTA$id/", 0777, true);
}
$position = 0;
for ($i = 1; $i <= 10; $i++) {
if (isset($_FILES['picture' . $i])) {
$file = $_FILES['picture' . $i]['tmp_name'];
$nameFile = "picture" . $position;
$patchImage = "/pictures/produtos/$productCategory/MTA$id/$nameFile.png";
move_uploaded_file($file, "../../.." . $patchImage);
saveImageInDataBase($id, $patchImage, $position);
$position++;
} else if (isset($_POST['picture' . $i])) {
$file = $_POST['picture' . $i];
$nameFile = "picture" . $position;
$oldName = "../../../" . substr($file, strpos($file, 'pictures/'));
rename($oldName, "../../../pictures/produtos/$productCategory/MTA$id/$nameFile.png");
saveImageInDataBase($id, "/pictures/produtos/$productCategory/MTA$id/$nameFile.png", $position);
$position++;
}
}
}
Bug: There is a bug that when there is already a photo in the folder with the same name (with the position) and another photo being placed with that same position (move_uploaded_file) the old photo will be replaced.
Would there be an easier way to make this photo system work well?
Before doing the move_uploaded_file() you have to check whether the file exists. If so, you'll need to create a new filename. You'll have to do those steps until you find a non-existent file.
while ( TRUE ) { // Loop until we find a non-existent destination filename
$nameFile = "picture" . $position;
$patchImage = "/pictures/produtos/$productCategory/MTA$id/$nameFile.png";
if ( ! file_exists( $patchImage ) ) { // We're good
move_uploaded_file($file, "../../.." . $patchImage);
saveImageInDataBase($id, $patchImage, $position);
break; // Get out of the loop
}
$position++; // Try next position
}
well, i've an like/unlike script.
When i click on like or unlike, the php request is executed twice.
I've tried several things but i don't understand why.
Here my php request.
$query = "SELECT * FROM like_unlike WHERE postid=".$postid." and userid=".$userid;
$req = $bdd->prepare($query);
$req->execute();
$array = $req->fetchALL();
$count = count($array);
if($count == 0){
$insertquery = "INSERT INTO like_unlike(userid,postid,type)
values(".$userid.",".$postid.",".$type.")";
$insertquery = $bdd->prepare($insertquery);
$insertquery->execute();
and here my js file
$(document).ready(function(){
// like and unlike click
$(".like, .unlike").click(function(){
var id = this.id; // Getting Button id
var split_id = id.split("_");
var text = split_id[0];
var postid = split_id[1]; // postid
// Finding click type
var type = 0;
if(text == "like"){
type = 1;
}else{
type = 0;
}
// AJAX Request
$.ajax({
url: 'likeunlike.php',
type: 'post',
data: {postid:postid,type:type},
dataType: 'json',
success: function(data){
var likes = data['likes'];
var unlikes = data['unlikes'];
var difflikes = data['likes'] - data['unlikes'];
$("#likes_"+postid).text(likes); // setting likes
$("#unlikes_"+postid).text(unlikes);
$("#difflikes_"+postid).text(difflikes); // setting unlikes
}
});
});
HTML:
<img src="<?= $chemin ?>img/up.png" value="Like" id="<?php echo $id_vote_like; ?>"
class="img_vote_up zoom <?= $class_vote_like ?> " style="" /> <?= $log_e ?>
<span id="difflikes_<?php echo $postid; ?>" class="nb_votes"><?php echo $likes_d; ?>
</span>
<?= $log_i ?>
<img src="<?= $chemin ?>img/down.png" value="Unlike" id="<?php echo
$id_vote_unlike; ?>" class="<?= $class_vote_unlike ?> img_vote_down zoom" style=""
/> <?= $log_e ?>
Anyone has an idea ?
I want to pass an array into a database but i'm getting a notice and the echo is not working to print out the string I want.
Notice: Array to string conversion on line 7 ( echo $item; )
How do I capture the data being sent into a database?
Where the arrays are sent by author and their books.
e.g.
[{"name":"Book1","books":["Book1.1"]},{"name":"Book2","books":["Book2.1","Book2.2"]}]
This is next.php where the data is being passed and not being echoed.
<?php
var_dump($_POST);
$data = json_decode(stripslashes($_POST['arr']), true);
foreach($data as $item){
echo $item;
// insert to db
}
?>
The alert is giving me the return data from next.php in the sendToServer function (see snippet).
success: function(data) {
alert(data);
}
Full code in the snippet:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<style type="text/css">
<!-- #main {
max-width: 800px;
margin: 0 auto;
}
-->
</style>
</head>
<body>
<div id="main">
<h1>Add or Remove text boxes with jQuery</h1>
<div class="my-form">
<!-- <form action="next.php" method="post">-->
<button onclick="addAuthor()">Add Author</button>
<br>
<br>
<div id="addAuth"></div>
<br>
<br>
<button onclick="submit()">Submit</button>
<!-- </form>-->
</div>
<div id="result"></div>
</div>
<script type="text/javascript">
var authors = 0;
function addAuthor() {
authors++;
var str = '<br/>' + '<div id="auth' + authors + '">' + '<input type="text" name="author" id="author' + authors + '" placeholder="Author Name:"/>' + '<br/>' + '<button onclick="addMore(\'auth' + authors + '\')" >Add Book</button>' + '</div>';
$("#addAuth").append(str);
}
var count = 0;
function addMore(id) {
count++;
var str =
'<div id="bookDiv' + count + '">'
+ '<input class="' + id + '" type="text" name="book' + id + '" placeholder="Book Name"/>'
+ '<span onclick="removeDiv(\'bookDiv' + count + '\')">Remove</span>'
+ '</div>';
$("#" + id).append(str);
}
function removeDiv(id) {
$("#" + id).slideUp(function() {
$("#" + id).remove();
});
}
function submit() {
var arr = [];
for (i = 1; i <= authors; i++) {
var obj = {};
obj.name = $("#author" + i).val();
obj.books = [];
$(".auth" + i).each(function() {
var data = $(this).val();
obj.books.push(data);
});
arr.push(obj);
}
sendToServer(arr);
//$("#result").html(JSON.stringify(arr));
}
function sendToServer(data) {
$.ajax({
type: "POST",
data: {
arr: JSON.stringify(data)
},
url: "next.php",
success: function(data) {
alert(data);
}
});
}
</script>
</body>
</html>
you are getting Notice: Array to string conversion on line 7 ( echo $item; ) because you are going to print array.
You can't print array whereas you can do a string so.
To do like that use something like this.
<?php
var_dump($_POST);
$data = json_decode(stripslashes($_POST['arr']), true);
for ($i=0;$i<count($data);$i++){
echo "Name: ".$data[$i]['name']. "<br/>";
echo "Books: ";
foreach($data[$i]['books'] as $book){
echo $book . " ";
}
echo "...............<br/>";
// insert to db example
$sql="INSERT INTO author(id, name) VALUES (NULL, '".$data[$i]['name']."')";
//execute query and get last insert id
//$author_id=last insert id
foreach($data[$i]['books'] as $book){
$sql="INSERT INTO author_books(id, author_id, book_name) VALUES (NULL,'$author_id', '$book')";
//execute query
}
}
?>
This is what you have form POST:
[
{
"name":"Book1",
"books": [
"Book1.1"
]
},{
"name":"Book2",
"books": [
"Book2.1",
"Book2.2"
]
}
]
To read the data using a foreach you need to do:
foreach($data as $item) {
echo "Name: " . $item["name"] . "<br>";
echo "Books: " . implode(", ", $item["books"]) . "<br>";
// Other way..
echo "Name: " . $item["name"] . "<br>";
echo "Books: <br>";
foreach($book as $item["books"])
echo $book . "<br>";
}
By this foreach you can manipulate your data and build your INSERT statement to input data to database.
I'm having trouble with a jQuery script for voting on posts. I have a "frontpage" with a list of posts from a mysql db. On each post there is a little votebox you can either vote up or down.
jQuery/ajax script:
<script type="text/javascript">
$(document).ready(function() {
$('.plus-button').click(function(){
var postid = <?php echo $postloopid; ?>;
$('.minus-button').removeClass('disliked');
$(this).toggleClass('liked');
alert(postid);
$.ajax({
type:"POST",
url:"php/votesystem.php",
dataType : 'html',
data:'act=like&postid='+postid,
success: function(data){
$('.plus-button').html(data);
}
});
});
$('.minus-button').click(function(){
var postid = $(this).attr('id');
$('.plus-button').removeClass('liked');
$(this).toggleClass('disliked');
$.ajax({
type:"POST",
url:"php/votesystem.php",
dataType : 'html',
data:'act=dislike&postid='+postid,
success: function(data){
$('.minus-button').html(data);
}
});
});
});
</script>
Votebox.php
<?php
// If postid is from frontpage use $postloopid as $postid
if(isset($postloopid)){
$postid = $postloopid;
}
$postid = htmlentities($postid, ENT_QUOTES);;
include("connect.php");
//For test purposes
echo $postid;
// If user logged in show votebox
if(isset($_SESSION['username'])){
$userid = $_SESSION['userid'];
$sql2 = mysqli_query($connect,"SELECT * FROM posts WHERE id='$postid' AND deleted=0");
if($sql2){
$voterow = mysqli_fetch_assoc($sql2);
$checkupvote = $voterow['upvoters'];
$checkdownvote = $voterow['downvoters'];
$checkupvote = explode(" ",$checkupvote);
$checkdownvote = explode(" ",$checkdownvote);
if($checkupvote = array_search($userid,$checkupvote) == true){
echo '<div class="plus-button liked" name="like">+ ' . $voterow['totalupvotes'] . '</div>';
echo '<div class="minus-button" name="dislike">- ' . $voterow['totaldownvotes'] . '</div>';
}
elseif($checkdownvote = array_search($userid,$checkdownvote) == true){
echo '<div class="plus-button" name="like">+ ' . $voterow['totalupvotes'] . '</div>';
echo '<div class="minus-button disliked" name="dislike">- ' . $voterow['totaldownvotes'] . '</div>';
}
else{
echo '<div class="plus-button" name="like">+ ' . $voterow['totalupvotes'] . '</div>';
echo '<div class="minus-button" name="dislike">- ' . $voterow['totaldownvotes'] . '</div>';
}
}
else {
echo 'No result <br />';
}
}
else {
echo 'Cant find user';
}
?>
Frontpage:
<?php
$sql1 = mysqli_query($connect,"SELECT * FROM posts WHERE totalupvotes < $trendmin AND deleted=0 ORDER BY added DESC LIMIT 0,10");
if($sql1){
while($row = mysqli_fetch_array($sql1)){
$postloopid = $row['id'];
?>
<div id="postlist">
<div style="width:400px; font-size:18px; font-weight:bold;">
<a target="_blank" href="post.php?id=<?php echo $row['id']; ?>"><?php echo $row['title']; ?></a>
</div><br />
<article class="slide"><?php echo nl2br($row['post']); ?></article>
<br />
<?php include("php/votebox.php"); ?>
<br />
by <a style="font-size:18px;" href="profile.php?id=<?php echo $row['submittedby']; ?>"><?php echo $row['submitteduser']; ?></a>
at <span style="font-size:12px;"><?php echo $row['added']; ?></span><span style="float:right; margin-right: 10px;"><a target="_blank" href="post.php?id=<?php echo $row['id']; ?>#commentfield"><?php echo $row['totalcomments']; ?> comments</a></span>
</div>
<?php
}
}
?>
The problem now is that when I click the votebox buttons it turns out I only get the postid from the first loaded post from the while loop. Another problem I have is that my total up- and downvotes changes in all the posts on the list, not the specific post.
Any ideas?
The Javascript code isn't in the loop, it can't reference postloopid. Or if it is, you're binding all buttons of the class every time through the loop, and clicking on them will run all the handlers, incrementing all the posts.
You should put the post ID as a data field in the button, and then access that from the Javascript:
echo '<div class="plus-button liked" data-postid="'+$postid+'" name="like">+ ' . $voterow['totalupvotes'] . '</div>';
echo '<div class="minus-button" data-postid="'+$postid+'" name="dislike">- ' . $voterow['totaldownvotes'] . '</div>';
Then your Javascript can do:
$('.plus-button').click(function(){
var postid = $(this).data('postid');
$(this).siblings('.minus-button').removeClass('disliked');
$(this).toggleClass('liked');
alert(postid);
$.ajax({
type:"POST",
url:"php/votesystem.php",
dataType : 'html',
data:'act=like&postid='+postid,
context: this,
success: function(data){
$(this).html(data);
}
});
});
I made the following changes to the JS:
Use $(this).data('postid') to get postid.
Only remove the disliked class from the sibling minus button, not all minus buttons on the page.
Put the returned HTML just in this element, not in all plus buttons. I pass this in the context: parameter, so that the success function can refer to it.
Alright lets go through your jQuery code(just the like function):
Bind click handler to all elements with the class plus-button
$('.plus-button').click(function(){
var postid = <?php echo $postloopid; ?>;
Remove disliked class from all elements with class minus-button
$('.minus-button').removeClass('disliked');
$(this).toggleClass('liked');
alert(postid);
$.ajax({
type:"POST",
url:"php/votesystem.php",
dataType : 'html',
data:'act=like&postid='+postid,
success: function(data){
Set inner html of all elements with class plus-button
$('.plus-button').html(data);
}
});
});
What you want is to store the postid as an attribute on the posts, then use
var postid = $(this).attr('postid')
only remove the disliked class from the current element
$(this)
.parents('{element containing plus and minus button}')
.find('.minus-button')
.removeClass('disliked')
;
store reference to the clicked element
var $this = $(this); // Cool guys do this right in the beginning and use only this variable instead of $(this)
then in your ajax success handler you want to set only the html of the button you clicked, so you may use the reference you stored in the parent function scope
$this.html(data);
EDIT in regards to infinite scroll script
When parts of your page are dynamic, you want to bind the click handler to a static parent element of the dynamic content using:
$("#postsParent").on('click', '.plus-button', function () {/*handler*/})
Hey i have a problem on my website i want to display a image with a rating under and then when i rate the image it should change to the next picture. And there is my problem because it displays the next picture correctly but it doesn't change the id in the rating system so i am rating the same picture again and again
Source code:
$place="upload/";
$first = mysql_query("SELECT * FROM images ORDER BY RAND()");
while($wor = mysql_fetch_array($first))
{
$id=$wor['id'];
$name = $wor['name'];
$image = $place . $wor['name'];
}
$number="1";
$wrongnumber="2";
$random = mysql_query("SELECT * FROM images ORDER BY RAND()");
$place="upload/";
echo '<script> ';
while($wor = mysql_fetch_array($random))
{
$ids=$wor['id'];
$name = $wor['name'];
$images = $place . $wor['name'];
$number=$number + 1;
$wrongnumber=$wrongnumber + 1;
echo 'function ' . 'changeSrc' . $number . '() '; ?>
{
document.getElementById("rand").src="<? echo $images;?>";
document.getElementById("button").onclick=changeSrc<? echo $wrongnumber;?>;
document.getElementById("102").id=<? echo $ids;?>;
}
<?
}
?>
</script>
<img id="rand" src="<? echo $image;?>"><br>
<div id="button" onclick="changeSrc2()">
<div class="rate_widget" id="102">
<div class="star_1 ratings_stars"></div>
<div class="star_2 ratings_stars"></div>
<div class="star_3 ratings_stars"></div>
<div class="star_4 ratings_stars"></div>
<div class="star_5 ratings_stars"></div>
<div class="total_votes">vote data</div>
</div>
</div>
The output code:
// This is the first thing we add ------------------------------------------
$(document).ready(function() {
$('.rate_widget').each(function(i) {
var widget = this;
var out_data = {
widget_id : $(widget).attr('id'),
fetch: 1
};
$.post(
'ratings.php',
out_data,
function(INFO) {
$(widget).data( 'fsr', INFO );
set_votes(widget);
},
'json'
);
});
$('.ratings_stars').hover(
// Handles the mouseover
function() {
$(this).prevAll().andSelf().addClass('ratings_over');
$(this).nextAll().removeClass('ratings_vote');
},
// Handles the mouseout
function() {
$(this).prevAll().andSelf().removeClass('ratings_over');
// can't use 'this' because it wont contain the updated data
set_votes($(this).parent());
}
);
// This actually records the vote
$('.ratings_stars').bind('click', function() {
var star = this;
var widget = $(this).parent();
var clicked_data = {
clicked_on : $(star).attr('class'),
widget_id : $(star).parent().attr('id')
};
$.post(
'ratings.php',
clicked_data,
function(INFO) {
widget.data( 'fsr', INFO );
set_votes(widget);
},
'json'
);
$.post(
'setcookie.php',
clicked_data,
function(INFO) {
widget.data( 'fsr', INFO );
set_votes(widget);
},
'json'
);
});
});
function set_votes(widget) {
var avg = $(widget).data('fsr').whole_avg;
var votes = $(widget).data('fsr').number_votes;
var exact = $(widget).data('fsr').dec_avg;
window.console && console.log('and now in set_votes, it thinks the fsr is ' + $(widget).data('fsr').number_votes);
$(widget).find('.star_' + avg).prevAll().andSelf().addClass('ratings_vote');
$(widget).find('.star_' + avg).nextAll().removeClass('ratings_vote');
$(widget).find('.total_votes').text( votes + ' votes recorded (' + exact + ' rating)' );
}
// END FIRST THING
</script><script> function changeSrc2() {
document.getElementById("rand").src="upload/1329614519daily_erotic_picdump_48-2-500x334.jpg";
document.getElementById("button").onclick=changeSrc3;
document.getElementsByClassName('rate_widget').id="125";
}
function changeSrc3() {
document.getElementById("rand").src="upload/1329614453tumblr_leb4pwc0Xc1qzy9ouo1_1280-1024x640.jpg";
document.getElementById("button").onclick=changeSrc4;
document.getElementsByClassName('rate_widget').id="65";
}
function changeSrc4() {
document.getElementById("rand").src="upload/1329614295daily_erotic_picdump_20-copy-500x333.jpg";
document.getElementById("button").onclick=changeSrc5;
document.getElementsByClassName('rate_widget').id="44";
}
function changeSrc5() {
document.getElementById("rand").src="upload/1329614301daily_erotic_picdump_80-2-500x375.jpg";
document.getElementById("button").onclick=changeSrc6;
document.getElementsByClassName('rate_widget').id="51";
}
function changeSrc6() {
document.getElementById("rand").src="upload/13296142941-3-450x600.jpg";
document.getElementById("button").onclick=changeSrc7;
document.getElementsByClassName('rate_widget').id="225";
}
function changeSrc7() {
document.getElementById("rand").src="upload/1329614284tumblr_l53l0qM6HB1qc4zlyo1_500-450x568.jpg";
document.getElementById("button").onclick=changeSrc8;
document.getElementsByClassName('rate_widget').id="19";
}
function changeSrc8() {
document.getElementById("rand").src="upload/1329614454tumblr_lro15r2fkh1qzlro6o1_500-450x301.jpg";
document.getElementById("button").onclick=changeSrc9;
document.getElementsByClassName('rate_widget').id="73";
}
function changeSrc9() {
document.getElementById("rand").src="upload/tumblr_mccaolmQPE1regfy1o1_500.jpg";
document.getElementById("button").onclick=changeSrc10;
document.getElementsByClassName('rate_widget').id="272";
}
function changeSrc10() {
document.getElementById("rand").src="upload/1329614297Pix-Mix-304-img012-500x312.jpg";
document.getElementById("button").onclick=changeSrc11;
document.getElementsByClassName('rate_widget').id="47";
}
</script>
<img id="rand" src="upload/1329614465tumblr_lscy8aqOFE1qg7sdjo1_500-450x322.jpg"><br>
<div id="button" onclick="changeSrc2()">
<div class="rate_widget" id="99">
<div class="star_1 ratings_stars"></div>
<div class="star_2 ratings_stars"></div>
<div class="star_3 ratings_stars"></div>
<div class="star_4 ratings_stars"></div>
<div class="star_5 ratings_stars"></div>
<div class="total_votes">vote data</div>
</div>
</div>
document.getElementById("button").onclick=changeSrc<? echo $wrongnumber;?>;
Aren't you missing brackets?
document.getElementById("button").onclick=changeSrc<? echo $wrongnumber;?>();
By the way, to reduce data laod add LIMIT 1 to your SQL query when retrieving only one row.