I am loading the latest news article to my home page, I would like to load the next one on click of a button. However I get this error on click: home.php:353 Uncaught ReferenceError: nextNews is not defined. The code I have written will load another article but will not hide the previous one. Any suggestions for this are also welcome.
<script>
$( document ).ready(function() {
var newsCount = 1;
function nextNews(item){
newsCount = newsCount + 1;
$("#newsHome2").load("load-news.php", {
newsNewCount: newsCount
});
}
});
</script>
<?php
$query = $handler->query('SELECT * FROM articles LIMIT 1');
$results = $query->fetchAll(PDO::FETCH_ASSOC);
if ($_GET['sort'] == 'dateTime')
{
$sql = " ORDER BY dateTime";}
for ($i=0; $i < count($results); $i++) {
echo '<div class="col-lg-6 col-xs-12 col-sm-12 height-news82" id="newsHome2">';
echo '<h2 class="ashu">Lastest News</h2><br>';
echo '<p class="news-title78">'.$results[$i]['headline'].' <br>'.'</p>';
echo '<img class="news-img33" src="data:image/png;base64,' .base64_encode( $results[$i]['logo'] ).'"/>';
echo '<p class="news-time">'.$results[$i]['dateTime'].'< br>'.'</p>';
echo '<p class="news-body56">'.$results[$i]['text'].'</p>' ;
echo '</p><br><button id="solo-buttons67">Read More</button>';
echo '<i id="arrow20" class="fa fa-chevron-left fa-1x"></ i><i id="arrow21" onclick="nextNews(this)" class="fa fa-chevron-right fa-1x"></i></div>';
}
?>
Your function 'nextNews' is defined in the anonymous function passed to .ready(). So it can't be called in your html.
Alternative:
Use jquery click event
Define the function outside of the anonymous function
Try this workout Its working fine :)
view file view.php
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"></script>
<div id="newsHome2"></div>
<script type="text/javascript">
var newsCount = 1;
$( document ).ready(function() {
nextNews(newsCount)
});
function nextNews(newsCount){
newsCount = newsCount + 1;
$.post("load-news.php", { newsNewCount: newsCount }, function(data, status){
$("#newsHome2").html(data);
});
}
</script>
php file load-news.php
<?php
if(isset($_POST['newsNewCount'])) { $newsCount=$_POST['newsNewCount']; } else { $newsCount=1; }
echo '<div class="col-lg-6 col-xs-12 col-sm-12 height-news82" id="newsHome2">';
echo '<h2 class="ashu">Lastest News</h2><br>';
echo '<p class="news-title78">headline '.$newsCount.' <br>'.'</p>';
echo '<img class="news-img33" src="data:image/png;base64,"/>';
echo '<p class="news-time">dateTime '.$newsCount.'< br>'.'</p>';
echo '<p class="news-body56">text '.$newsCount.'</p>' ;
echo '</p><br><button id="solo-buttons67">Read More '.$newsCount.'</button>';
echo '<i id="arrow20" class="fa fa-chevron-left fa-1x"></ i><i id="arrow21" onclick="nextNews('.$newsCount.')" class="fa fa-chevron-right fa-1x"> click here for next </i></div>';
?>
Related
I have a problem my delete function does not work he does not delete the organisation. When I press the button it show the text if I want to delete it I say yes but it only refreshes the site. I am not an advanced programmer and some of the code I did not write myself someone else worked on the project before me so idk why he some codes are written this way and he did not use any framework.
My code
<?php
if ($_SERVER['REQUEST_METHOD'] == "POST") {
if (isset($_FILES['croppedImage'])) logoChange();
// change organisation information is not made yet
if (isset($_POST['update'])) echo "This function is not made yet!";
if (isset($_POST['deleteOrganisation'])) DeleteOrganisations();
}
//this is the logoChange function
function logoChange() {
include '../../../include/db_conn.php';
//get organisation_id
$organisation_id = $_POST['organisation_id'];
//blob file info
$fileName = $_FILES['croppedImage']['name'];
$fileTmpName = $_FILES['croppedImage']['tmp_name'];
$fileSize = $_FILES['croppedImage']['size'];
$fileError = $_FILES['croppedImage']['error'];
//change blob to png
$fileType = 'png';
//check if image is able to upload
if ($fileError === 0) {
//check if file is not too big change number to needs!
if ($fileSize < 1000000) {
//make new random filename
$fileNameNew = uniqid('', true).".".$fileType;
$fileDesination = '../../../img/uploads/'.$fileNameNew;
move_uploaded_file($fileTmpName, $fileDesination);
//check if organisation already has a logo
$get_organisation_stmt = $conn->prepare('SELECT `organisation_logo` FROM `organisations` WHERE `organisation_id` = ?');
$get_organisation_stmt->bind_param('s', $organisation_id);
$get_organisation_stmt->execute();
$result_organisation = $get_organisation_stmt->get_result();
$row = mysqli_fetch_assoc($result_organisation);
if (is_null($row['organisation_logo'])) {
//if not inserted it
$sqlUpdateLogo = 'UPDATE `organisations` SET `organisation_logo`="'.$fileNameNew.'" WHERE `organisation_id` ="'.$organisation_id.'"';
mysqli_query($conn, $sqlUpdateLogo);
echo 'image inserted';
} else {
//else replace it
unlink('../../../img/uploads/'.$row['organisation_logo']);
$sqlUpdateLogo = 'UPDATE `organisations` SET `organisation_logo`="'.$fileNameNew.'" WHERE `organisation_id` ="'.$organisation_id.'"';
mysqli_query($conn, $sqlUpdateLogo);
echo 'image replaced';
}
}
else {
echo "File to big";
}
} else {
echo "Error in file";
}
}
// here i made the delete function
function DeleteOrganisations() {
include '../../../include/db_conn.php';
//delete the organisation
$getDeleteOrganisation = $_POST['deleteOrganisation'];
$delete_organisation_stmt = $conn->prepare('DELETE FROM `organisations` WHERE `organisation_id`= ?');
$delete_organisation_stmt->bind_param('i', $getDeleteOrganisation);
$delete_organisation_stmt->execute();
$delete_organisation_stmt->close();
}
here are the functions and here is JavaScript
//link for datatable functions
$(document).ready(function(){
$('#organisations').DataTable({
"columnDefs": [
{ "orderable": false, "targets": [0, 5] }
],
"order": [[ 1, "asc" ]]
});
});
//open edit modal for logo
$(document).on("click", ".btnopenEditLogo", function(e) {
event.preventDefault();
var organisationId = $(this).val();
var url = "functions/getOrganisationActions.php";
$.ajax({
type: 'POST',
url : url,
data: {'HiddenLogoid': organisationId},
success: function (data) {
$('#myLogoEditModal').modal('show');
$("#myLogoEditModal .modal-body").html(data);
}
});
});
//open modal with info of user for editing
$(document).on("click", ".btnopenEditOrganisation", function(e) {
event.preventDefault();
var organisationId = $(this).val();
var url = "functions/getOrganisationActions.php";
$.ajax({
type: 'POST',
url : url,
data: {'HiddenOrganisationid': organisationId},
success: function (data) {
$('#myOrganisationEditModal').modal('show');
$("#myOrganisationEditModal .modal-body").html(data);
}
});
});
//delete organisation
$(document).on("click", ".btnRemoveOrganisation", function(e) {
event.preventDefault();
var remove = $(this).val();
var url = "../cms/organisations/functions/postOrganisationActions.php";
Swal.fire({
title: 'Delete this test?',
text: "If you delete the test the questions and all statistics will be lost!",
type: 'warning',
showCancelButton: true,
confirmButtonText: 'Yes, delete it!',
cancelButtonText: 'No, cancel!',
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33'
}).then((result) => {
if (result.value) {
$.ajax({
type: 'POST',
url : url,
data: {'deleteOrganisation': remove},
success: function (data) {
Swal.fire({
title: 'Deleted!',
text: "You deleted the survey!",
type: 'success',
confirmButtonColor: '#3085d6',
confirmButtonText: 'OK'
}).then((result) => {
if (result.value) {
window.location.reload();
}
});
}
});
} else if (result.dismiss === Swal.DismissReason.cancel) {
Swal.fire (
'Cancelled',
'Your test is safe :)',
'error'
)
}
});
});
this is the index
<?php
session_start();
if (!isset($_SESSION["userId"])) {
header('Location: ../../auth/login');
die();
}
$activePage = "cms";
$activeCMSTab = "organisations";
?>
<!doctype html>
<html lang="en">
<head>
<title>Admin CMS | Organisations</title>
<!-- include header -->
<?php require '../../include/header.php'; ?>
</head>
<body class="d-flex flex-column">
<!-- include navbar -->
<?php require '../../include/navbar.php'; ?>
<!-- include organisation functions -->
<?php require 'functions/getOrganisationsActions.php'; ?>
<div id="main">
<div class="container">
<div class="row">
<div id="sidenav-border" class="col-lg-3 d-none d-md-none d-lg-block">
<?php require '../../include/cms_sidenav.php'; ?>
</div>
<div class="col-lg-9">
<div class="card-theme mt-3">
<div class="clearfix">
<h5 class="card-title-theme float-left"><i class="fas fa-building"></i> Organisation list:</h5>
<i class="fas fa-info-circle fa-fw mt-2 mr-2"></i>
</div>
<hr class="hr-theme" />
<div class="card-body">
<?php getOrganisations(); ?>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- footer -->
<?php require '../../include/footer.php'; ?>
<!-- logo modal -->
<?php require 'logo-edit-modal.php'; ?>
<!-- organisation modal -->
<?php require 'organisation-edit-modal.php'; ?>
<!-- logout modal -->
<?php require '../../auth/logout-modal.php'; ?>
<!-- include js scripts -->
<script src="js/organisationFunctions.js"></script>
</body>
</html>
you need get organisation where the button is made the button is at
<?php
function getOrganisations() {
//include DataBase connection
include '../../include/db_conn.php';
//show every organisation that is approved
$sqlCollectAllOrganisations = "SELECT * FROM `organisations` WHERE `approval_admin`='1'";
$resultAllOrganisations = mysqli_query($conn, $sqlCollectAllOrganisations);
echo '<div class="table-responsive">';
echo '<table id="organisations" class="table table-striped table-bordered table-hover">';
echo '<thead>';
echo '<tr>';
echo '<th>Logo</th>';
echo '<th>Organisation</th>';
echo '<th>Parent</th>';
echo '<th>type</th>';
echo '<th>Users</th>';
echo '<th>Tools</th>';
echo '</tr>';
echo '</thead>';
echo '<tbody>';
//Show organisations
if ($resultAllOrganisations->num_rows > 0) {
while ($row = $resultAllOrganisations-> fetch_assoc()) {
echo '<tr>';
//organisation logo
if ($row['organisation_logo'] == '')
echo '<td class="align-middle" align="center"><img src="../../img/stock/no-image-icon.png" class="rounded d-inline mr-1" width="30px"></img><button class="btn btn-link d-inline p-0 btnopenEditLogo" value="'. $row['organisation_id'] .'">edit</button></td>';
else
echo '<td class="align-middle" align="center"><img src="../../img/uploads/'. $row['organisation_logo'] .'" class="rounded border d-inline mr-1" width="30px"><button class="btn btn-link d-inline p-0 btnopenEditLogo" value="'. $row['organisation_id'] .'">edit</button></td>';
//organisation name
echo '<td class="align-middle">' .$row['organisation_name']. '</td>';
//organisation parent
if ($row['organisation_parent'] != null) {
$sqlCollectparent = "SELECT * FROM `organisations` WHERE `organisation_id`='".$row['organisation_parent']."'";
$resultparent = mysqli_query($conn, $sqlCollectparent);
if ($parent = $resultparent-> fetch_assoc()) echo '<td class="align-middle">'.$parent['organisation_name'].'</td>';
} else {
echo '<td class="align-middle"><i class="fas fa-times" style="font-size: 16px;"></i></td>';
}
//organisation type
echo '<td class="align-middle">' . $row['organisation_type'] . '</td>';
//count users
$sqlCountUsers = "SELECT COUNT(organisation_id) AS `count` FROM `users` WHERE `organisation_id`='".$row['organisation_id']."'";
$resultcount = mysqli_query($conn, $sqlCountUsers);
if ($count = $resultcount-> fetch_assoc()) echo '<td class="align-middle">'.$count['count'].'</td>';
//buttons
echo '<td class="align-middle text-center">';
echo '<div class="btn-group">';
echo '<button class="btn-theme btn-theme-success btn-theme-sm mr-1">Add user</button>';
echo '<button class="btn-theme btn-theme-primary btn-theme-sm mr-1 btnopenEditOrganisation" value="'. $row['organisation_id'] .'"><i class="fas fa-edit fa-fw"></i></button>';
if ($_SESSION['organisation_id'] != $row['organisation_id']) echo '<button type="button" class="btn-theme btn-theme-danger btn-theme-sm btnRemoveOrganisation" value=""><i class="fas fa-trash-alt fa-fw"></i></button>';
echo '</div>';
echo '</td>';
echo '</tr>';
}
} else {
//do nothing
}
echo '</tbody>';
echo '</table>';
echo '</div>';
}
?>
This question already has answers here:
php include prints 1
(11 answers)
Closed 2 years ago.
I am using PHP and Ajax to get Data. Data get successfully, but after loaded data at the bottom of loaded data showing "1111111". Why?
I try to find solution on different websites, but i can't. please help me. Advanced Thanks.
please see the attached image
Here is my PHP code (load_more.php) :
<?php
include '../../includes/session.php';
$conn = $pdo->open();
$id= $_POST['last_product_id'];
$output = '';
$stmt = $conn->prepare("SELECT *, COUNT(*) AS numrows FROM products WHERE id < :id ORDER BY id DESC");
$stmt->execute(['id'=>$id]);
$row = $stmt->fetch();
$totalRowCount = $row['numrows'];
$showLimit = 6;
try {
$stmt = $conn->prepare("SELECT * FROM products WHERE id < :id ORDER BY id DESC LIMIT $showLimit");
$stmt->execute(['id'=>$id]);
foreach($stmt as $row){
$product_id = $row['id'];
if (!empty($row['old_price'])){
$cart_wish_btn = '
<small> <del class="taka_sign_sm text-secondary">'.number_format($row['old_price'], 0).'
</del> <span class="ml-2 badge border border-success rounded text-success badge-sm">'.number_format($current_price,0).'% OFF</span></small>';
}
$current_price = 100 -(($row['price'] / $row['old_price']) * 100) ;
$image = (!empty($row['photo'])) ? '../../images/products/'.$row['photo'] : '../../images/noimage.jpg';
$output .= ''.include ('../product/item_view_5.php').'';
}
if($totalRowCount > $showLimit){
$output .= '
<div class="show_more_main" id="show_more_main'.$product_id.'">
<div id="'.$product_id.'" class="show_more"></div>
<div class="loding" style="display: none;"><div class="spinner-border spinner-border-sm text-primary"></div></div>
</div>
';
}
}
catch(PDOException $e){
$output .= $e->getMessage();
}
$pdo->close();
echo $output;
?>
Here is my AJax:
$(document).ready(function() {
//$(document).on('click', '.show_more', function() {
$(window).scroll(function(){
var ID = $('.show_more').attr('id');
if(($(window).scrollTop() == $(document).height() - $(window).height()) && (ID != 0)){
$('.show_more').hide();
$('.loding').show();
$.ajax({
type: 'POST',
url: "../product/load_more.php",
data: 'last_product_id=' + ID,
success: function(html) {
$('#show_more_main' + ID).remove();
$('.load_data_table').append(html);
}
})
}
})
});
Here is my HTML:
<div class="row row-cols-2 row-cols-sm-4 row-cols-md-6 px-2 load_data_table"></div>
<div class="show_more_main" id="show_more_main<?php echo $product_id; ?>">
<div id="<?php echo $product_id; ?>" class="show_more"></div>
<div class="loding" style="display: none;"><div class="spinner-border spinner-border-sm text-primary">
</div>
</div>
</div>
include returns 1 which you assign to $output. You probably want to buffer and get the output of the included file:
ob_start();
include('../product/item_view_5.php');
$output .= ob_get_clean();
If you are doing this frequently then build a function with the above code:
function get_template($file) {
ob_start();
include($file);
return ob_get_clean();
}
And use it thusly:
$output .= get_template('../product/item_view_5.php');
In my page there is a div element containing a MetroUI listview :
...
<div id="listSalles" class="listview">
<?php
$ret = ReservationSalle::lireParCritere([]); // database SELECT query
if ($ret->count() > 0) {
$html = '';
foreach ( $ret as $key => $val ) {
$html .= '<div class="list" id="salle_'.$ret[$key]->salle_code.'_'.$ret[$key]->flag_reserver.'">
<span class="mif-bookmarks list-icon"></span>
<span class="list-title">'.$ret[$key]->salle_lib.'</span>
<span class="place-right"><button id="reservS_'.$ret[$key]->salle_code.'" class="button default">Réserver</button></span>
<br/>
<span class="sub-title">'.$ret[$key]->reserver.'</span>
</div>';
}
echo $html;
}
else {
echo '<br/><div class="sub-header">Aucun enregistrement</div>';
}
?>
</div>
...
As you can see there is a database SELECT query which populates the listview. I want to "reload" this listview's content when a button , outside of the listview , is pressed. How to do that ?
Use javascript to do so.
In your PHP script put your current code:
$ret = ReservationSalle::lireParCritere([]); // database SELECT query
if ($ret->count() > 0) {
$html = '';
foreach ($ret as $key => $val) {
$html .= '<div class="list" id="salle_' . $ret[$key]->salle_code . '_' . $ret[$key]->flag_reserver . '">
<span class="mif-bookmarks list-icon"></span>
<span class="list-title">' . $ret[$key]->salle_lib . '</span>
<span class="place-right"><button id="reservS_' . $ret[$key]->salle_code . '" class="button default">Réserver</button></span>
<br/>
<span class="sub-title">' . $ret[$key]->reserver . '</span>
</div>';
}
return $html;
} else {
return '<br/><div class="sub-header">Aucun enregistrement</div>';
}
Lets call it data.php.
Then in your page load jQuery (if you havent yet, because it's easier) and add the following JS:
$.ajax({
type: 'GET',
url: 'data.php'
}).done(function (result) {
$("#listSalles").html(data); //Here you replace the current content with the update
}, "html");
And then wrap this JS in $(document).ready(function() {}) and inside a click listener $(btn).click(function(){ });
I suggest using AJAX.
Make a view with the relevant php code for the task, like this:
<?php
$ret = ReservationSalle::lireParCritere([]); // database SELECT query
if ($ret->count() > 0) {
$html = '';
foreach ( $ret as $key => $val ) {
$html .= '<div class="list" id="salle_'.$ret[$key]->salle_code.'_'.$ret[$key]->flag_reserver.'">
<span class="mif-bookmarks list-icon"></span>
<span class="list-title">'.$ret[$key]->salle_lib.'</span>
<span class="place-right"><button id="reservS_'.$ret[$key]->salle_code.'" class="button default">Réserver</button></span>
<br/>
<span class="sub-title">'.$ret[$key]->reserver.'</span>
</div>';
}
echo $html;
}
else {
echo '<br/><div class="sub-header">Aucun enregistrement</div>';
}
?>
Let's call it list-view.php.
Then in your page, add the following jquery:
$("#listSalles").load("list-view.php");
That would load the view inside that div.
If you want to reload that content when you press a button you could add a click handler for that button:
$("#id_of_button").click(function(){ $("#listSalles").load("list-view.php"); });
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.