I'm using a star ratings system to display rating data from SQL. Each item that can be rated has unique identifyer variable $id and each rating in ratings tabl has unique identifyer $storyidr. I would like this script to display:
the average rating
the number of times the item has been rated.
The values are retirevable but they display on the page together and I can't see how to seperate them. FOr example, for an item that has an average rating of 4 and has been rated 200 times. when user clicks the data returns via AJAX looking like:
For 'response1' 4"200"
For 'response2' 4"200"
I would like to be able to seperate them to look like:
For 'response1' 4
For 'response2' 200
html page
<div id="products" style="">
<div class="rateit" data-storyidr="<?php echo $id; ?>">
</div>
<div class="averagevote">
<div style="display:block;" id="response<?php echo $id; ?>"><?php echo $avgratep; ?></div><br>
<div style="display:block;" id="response2<?php echo $id; ?>">RaTeD <?php echo $rankcount; ?> TiMeS</div>
</div>
</div>
<?php endwhile; mysqli_close($connection); ?>
<script type ="text/javascript">
$('#currentslide .rateit').bind('rated reset', function (e) {
var ri = $(this);
var value = ri.rateit('value');
var storyidr = ri.data('storyidr');
ri.rateit('readonly', true);
$.ajax({
dataType : 'json',
url: 'rate.php',
data: {storyidr: storyidr, value: value},
type: 'POST',
success: function (data) {
$('#response'+storyidr).replaceWith('Avg rating ' + data.avg + '/5');
$('#response2'+storyidr).replaceWith('Rated ' + data.cnt + ' times');
},
error: function (jxhr, msg, err) {
$('#response').append('<li style="color:red">' + msg + '</li>');
}
});
});
</script>
PHP
<?PHP
$storyidr=$_POST['storyidr'];
$mysqli = mysqli_connect($dbhost,$dbusername,$dbpasswd,$database_name) or die ("Couldn't connect to server.");
if (mysqli_connect_errno($mysqli))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "INSERT INTO ratings (storyidr, rank, entry_date) VALUES ('$_POST[storyidr]','$_POST[value]',now());";
$sql .= "SELECT AVG(rank) AS avrank, COUNT(rank) AS countrank FROM ratings WHERE storyidr = $storyidr";
if($mysqli->multi_query($sql))
{ $mysqli->next_result();
if ($result = $mysqli->store_result())
{
$data = mysqli_fetch_assoc($result);
$avrank = $data['avrank'];
$countrank = $data['countrank'];
$avrankr = round($avrank,2);
if(is_null($avrank)){$avrank ="null";}
echo json_encode(array('avg' => $avrankr, 'cnt' => $countrank));
}
}
?>
You should only use json_encode() once and only echo the result of that function. Doing it more than once invalidates your json:
else
{
$results = array();
$results['av'] = $avrankr;
$results['cnt'] = $countrank;
echo json_encode($results);
}
Then, in your javascript, you can access data.av and data.cnt directly:
$('#response'+storyidr).replaceWith('Avg rating ' + data.av +'/5');
$('#response2'+storyidr).replaceWith(data.cnt);
You could also set the dataType parameter in your ajax call as mentioned by #barell, but normally jQuery will figure that out correctly already.
Edit: To avoid the undefined errors you are getting you should do something like:
$results = array('status' => 'fail');
...
if () {
...
if ($result)
{
$results['status'] = 'success';
$results['av'] = $avrankr;
$results['cnt'] = $countrank;
}
}
echo json_encode($results);
Now you can check for data.status first in the success callback of your ajax call and take the appropriate action:
success: function (data) {
if (data.status === 'fail') {
// show a warning message somewhere, this is just an example
alert('No results found!');
} else {
$('#response'+storyidr).replaceWith('Avg rating ' + data.av + '/5');
$('#response2'+storyidr).replaceWith('RaTeD ' + data.cnt + ' TiMeS');
}
},
I think the problem is you don't set the correct header. In the php file, before any output, put this:
header('Content-type: text/json');
And also, instead of write two objects, write it as an array:
echo json_encode(array('avg' => $avrankr, 'cnt' => $countrank));
Now it should work
Then, in your Javascript you will access this data like this:
$('#response'+storyidr).replaceWith('Avg rating ' + data.avg +'/5');
$('#response'+storyidr).replaceWith(data.cnt); // Suppose you want the count here
Related
I have see the example about search box using JQuery and mysql, But the view more function no work. how to improve the program. When i click the view more i can see the next 10 record. Thanks
<script type="text/javascript">
$(document).ready(function()
{
$("#keywords").keyup(function()
{
var kw = $("#keywords").val();
if(kw != '')
{
$.ajax
({
type: "POST",
url: "search.php",
data: "kw="+ kw,
success: function(option)
{
$("#results").html(option);
}
});
}
else
{
$("#results").html("");
}
return false;
});
$(".overlay").click(function()
{
$(".overlay").css('display','none');
$("#results").css('display','none');
});
$("#keywords").focus(function()
{
$(".overlay").css('display','block');
$("#results").css('display','block');
});
});
</script>
<div id="inputbox">
<input type="text" id="keywords" name="keywords" value="" placeholder="Type Your Query..."/>
</div>
</div>
<div id="results"></div>
<div class="overlay"></div>
we extract the value of that key and send it to the search.php
<?php
include('db.php');
//file which contains the database details.
?>
<?php
if(isset($_POST['kw']) && $_POST['kw'] != '')
{
$kws = $_POST['kw'];
$kws = mysql_real_escape_string($kws);
$query = "select * from wp_posts where post_name like '%".$kws."%' and (post_type='post' and post_status='publish') limit 10" ;
$res = mysql_query($query);
$count = mysql_num_rows($res);
$i = 0;
if($count > 0)
{
echo "<ul>";
while($row = mysql_fetch_array($res))
{
echo "<a href='$row[guid]'><li>";
echo "<div id='rest'>";
echo $row['post_name'];
echo "<br />";
echo "<div id='auth_dat'>".$row['post_date']."</div>";
echo "</div>";
echo "<div style='clear:both;'></div></li></a>";
$i++;
if($i == 5) break;
}
echo "</ul>";
if($count > 5)
{
echo "<div id='view_more'><a href='#'>View more results</a></div>";
}
}
else
{
echo "<div id='no_result'>No result found !</div>";
}
}
?>
press the view more result will not show more result.
If I'm not mistaken, you want to bring next 10 with ajax ?
This situation behaves as a pagination,
You have to store the current click count in javascript . Wİthout clicking more button, the variable of clickCount is 0, when you click more ,then your variable clickCount=1 ,
while sending ajax , send clickCount to the php.
$.ajax
({
type: "POST",
url: "search.php",
data: "kw="+ kw+"&clickCount="+clickCount,
success: function(option)
{
$("#results").html(option);
}
});
You can query with limit&offset (clickCount )*10, itemCountForEachMoreClick = limit 0,10
when click more
limit 10,10
when click one more
limit 20,10. Do not forget to reset clickCount on keyPress !
php Side
$count = isset($_REQUEST["clickCount"])? $_REQUEST["clickCount"]:0;
$limitAndOffset = $count*10.",10";
$query = "select * from wp_posts where post_name like '%".$kws."%'
and (post_type='post' and post_status='publish') limit ".$limitAndOffset ;
I am trying this code, but it isn't working.
The main problem is in these variables or in the script given at the bottom.
<?PHP
$upVote1 = "UPDATE facerate SET votes = votes + 1 WHERE Picture = '".$idOptain1."'";
$upVote2 = "UPDATE facerate SET votes = votes + 1 WHERE Picture = '".$idOptain2."'";
$upIgnore1 = "UPDATE facerate SET ignores = ignores + 1 WHERE Picture = '".$idOptain2."'";
$upIgnore2 = "UPDATE facerate SET ignores = ignores + 1 WHERE Picture = '".$idOptain1."'";
?>
<img onClick='renderData1()' src="<?php echo $img1['Picture'] ?>" />
<img onClick='renderData2()' src="<?php echo $img2['Picture'] ?>" />
<!-- £££££££££££££££ SCRIPT HERE ££££££££££££££ -->
<script>
function renderData1()
{
document.write(<?php mysql_query("$update1, $upIgnore1") or die(mysql_error()); ?>);
};
function renderData2()
{
document.write(<?php mysql_query("$update2, $upIgnore2") or die(mysql_error()); ?>);
};
</script>
mysql_query does not support multiple queries. You will need to break it up into a single query per call.
You should set up some Ajax request to register user votes: This might give you some idea how to do it (using jQuery here):
Javascript function to execute on vote click event :
function upvote_picture(id){
$.ajax({
type: 'POST',
url: 'vote.php',
dataType: 'json',
data: {
picture_id: id
},
success: function (data) {
alert(data);
}
});
}
vote.php file:
<?php
// Any error or warning in this script will break JSON response !
function send_json($array)
{
header('Content-Type: application/json; charset=utf-8');
echo json_encode($array);
exit();
}
// Add query execution status variables and messages here
$response = array();
$id = !empty($_POST['picture_id']) ? $_POST['pciture_id'] : FALSE;
if($id){
// Do you query here
if ( mysql_query(....)) {
$response['success'] = TRUE;
} else {
$response['success'] = FALSE;
}
} else {
$response['success'] = FALSE;
}
send_json($response);
?>
I'm using jquery ,ajax and php to implementing infinite scrolling
the image from database
and the code just works one time when i reach the end of a page and show me the message "No More Content" when there is actually content in the database
here is my cod
index.php
<html >
<?php include($_SERVER["DOCUMENT_ROOT"].'/db.php');
$query = "SELECT * FROM photo ORDER by PhotoNo DESC limit 12";
$result = mysql_query($query) or die('Query failed: ' . mysql_error());
$actual_row_count =mysql_num_rows($result);
?>
<head>
<title>Infinite Scroll</title>
<script src="jquery-1.7.2.js" type="text/javascript"></script>
<script type="text/javascript">
var page = 1;
$(window).scroll(function () {
$('#more').hide();
$('#no-more').hide();
if($(window).scrollTop() + $(window).height() > $(document).height() - 200) {
$('#more').css("top","400");
$('#more').show();
}
if($(window).scrollTop() + $(window).height() == $(document).height()) {
$('#more').hide();
$('#no-more').hide();
page++;
var data = {
page_num: page
};
var actual_count = "<?php echo $actual_row_count; ?>";
if((page-1)* 12 > actual_count){
$('#no-more').css("top","400");
$('#no-more').show();
}else{
$.ajax({
type: "POST",
url: "data.php",
data:data,
success: function(res) {
$("#result").append(res);
console.log(res);
}
});
}
}
});
</script>
</head>
<body>
<div id='more' >Loading More Content</div>
<div id='no-more' >No More Content</div>
<div id='result'>
<?php
while ($row = mysql_fetch_array($result)) {
$rest_logo=$row['PhotoName'];
$image="../images/rest/".$rest_logo;
echo '<div><img src='.$image.' /></div>';
}
?>
</div>
</body>
</html>
data.php
<?php
$requested_page = $_POST['page_num'];
$set_limit = (($requested_page - 1) * 12) . ",12";
include($_SERVER["DOCUMENT_ROOT"].'/db.php');
$result = mysql_query("SELECT * FROM photo ORDER by PhotoNo DESC limit $set_limit");
$html = '';
while ($row = mysql_fetch_array($result)) {
$rest_logo=$row['PhotoName'];
$image="../images/rest/".$rest_logo;
$html .= '<div><img src='.$image.' /></div>';
}
echo $html;
exit;
?>
I really nead a help
You see to be setting the variables wrong from a quick look:
var actual_count = "<?php echo $actual_row_count; ?>";
You're using mysql_num_rows() to count the return on your first set of results. But that is limited to 12.
You need to do a second mysql query to get all the images without limi, then count them to get the total number of images in the database.
In index.php your query is only returning 12 rows meaning that $actual_row_count is only ever going to be 12. Instead I would set $actual_row_count to the result of the query "SELECT count
(*) FROM photo".
My personal preference for these sort of things is to return a JSON response which only contains the n responses that are loading and have a template html stored in javascript. The way you've written it will return all the photo's on the last query instead of the last 12 that you want.
A PHP script obtains data from a MySQL database and returns an array to javascript using JSON. I can get the results but I cannot get them to print them out individually.
The PHP code -
header('Content-type:application/json');
$link = #new mysqli(_HOST, _USER, _PASS, _DB); //constants
if(mysqli_connect_errno())
{
//failure
}
else
{
//success
$sqlQuery = "SELECT COL1, COL2 FROM TABLE"; //the query should return two
//columns from every selected row
$mix = array(); //array to return using JSON
$result = $link->query($sqlQuery);
if ($result->num_rows <= 0)
{
//no data
}
else
{
while ($row = $result->fetch_assoc()) //fetch loop
{
$mix["C1"][] = $row['COL1'];
$mix["C2"][] = $row['COL2'];
}
}
$result->free();
// Close connection
$link->close();
}
print json_encode($mix); //this line wont show up in previous code formatting block for some reason.
The Javascript / jQuery code -
$.ajax({ // ajax call
url: 'serv.php', // server page
data: 'fetch=1', //ignore any data
dataType: 'json', // server return type
success: function(data) // on success
{
for (var i in data) {
$('#someDiv').append( i + " = " + data[i] + '<br>');
}
}
});
The output, as expected is like this -
C1 = 1,2
C2 = A,B
What I want to accomplish is to put these data (1,2,A,B) inside a form table element. And to do that I need to pick the every element of C1 or C2 individually.
How can I accomplish this?
I've found the solution myself.
The following ajax call works-
$.ajax({ // ajax call
url: 'serv.php', // server page
data: 'fetch=1', //ignore any data
dataType: 'json', // server return type
success: function(data) // on success
{
for (var i in data["C1"]) {
$('#someDiv').append( i + " = " + data["C1"][i] + '<br>');
}
for (var i in data["C2"]) {
$('#someDiv').append( i + " = " + data["C2"][i] + '<br>');
}
}
});
Instead of accessing the data, I've tried to access the indices inside data. It was so simple.
I'm making a simple voter that takes either a "like" vote or "dislike" vote. Then, I count the total number of likes and dislikes and output the total numbers. I figured out how to put in the votes using Jquery Ajax, but the number of votes do not update after I put in a vote. I would like to update the $numlike and $numdislike variables using Jquery Ajax.
Here is the PHP script pertaining to the output:
$like = mysql_query("SELECT * FROM voter WHERE likes = 1 ");
$numlike = 0;
while($row = mysql_fetch_assoc($like)){
$numlike++;
}
$dislike = mysql_query("SELECT * FROM voter WHERE likes = 0 ");
$numdislike = 0;
while($row = mysql_fetch_assoc($dislike)){
$numdislike++;
}
echo "$numlike like";
echo "<br>";
echo "$numdislike dislike";
UPDATE:
Jquery Ajax for uploading vote
<script>
$(document).ready(function(){
$("#voter").submit(function() {
var like = $('#like').attr('value');
var dislike = $('#dislike').attr('value');
$.ajax({
type: "POST",
url: "vote.php",
data: "like=" + like +"& dislike="+ dislike,
success: submitFinished
});
function submitFinished( response ) {
response = $.trim( response );
if ( response == "success" ) {
jAlert("Thanks for voting!", "Thank you!");
}
return false;
});
});
</script>
<form id="voter" method="post">
<input type='image' name='like' id='like' value='like' src='like.png'/>
<input type='image' name='dislike' id='dislike' value='dislike' src='dislike.png'/>
</form>
vote.php:
if ($_POST['like'])
{
$likeqry = "INSERT INTO test VALUES('','1')";
mysql_query($likeqry) or die(mysql_error());
echo "success";
}
if ($_POST['dislike'])
{
$dislikeqry = "INSERT INTO test VALUES('','0')";
mysql_query($dislikeqry) or die(mysql_error());
echo "success";
}
If you want to change current like or dislike number after clicking it you must return result instead of printing it ! return json result and echo this and change div innerHTML to see new result !
............
............
............
$dislike = mysql_query("SELECT * FROM voter WHERE likes = 0 ");
$numdislike = 0;
while($row = mysql_fetch_assoc($dislike)){
$numdislike++;
}
echo json_encode( array( $numlike, $numdislike ) ) ;
exit();
Now in your html code :
$.ajax({
type: "POST",
url: "vote.php",
context:$(this)
data: "like=" + like +"& dislike="+ dislike,
success: submitFinished(data)
});
function submitFinished( response ) {
response = $.parseJSON( response );
//Now change number of like and dilike but i don't know where are shown in your html
$('#like').attr('value',response[0]);
$('#dislike').attr('value',response[1]);
return false;
});
You can send a $_GET or $_POST variable to the file that you are calling with AJAX.
.load("google.com", "foo=bar", function(){
});