Assign unique ID to div as created and then reference with jquery - php

I am brand new to php and a beginner with jQuery. I have a php page that is populated with data from a mySQL table. What I am trying to achieve is for the h3 that contains "View Job" to have a unique id assigned to it, as well as the div that prints out the job description. Then, I would like to reference these with jQuery so that if someone clicks View Job, only the description for that job will show. I hope this makes sense.
I tried this with classes and of course all the job descriptions revealed themselves when any View Job was clicked.
I tried the solution here, but this ended up with 36 "View Job" links on my page, and I need to assign the unique ID to the h3 and div as they are created.
I am open to suggestions for another way to achieve what I'm looking for - basically to hide/collapse each description as the user clicks on View Job for each job.
here is my code:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<style type="text/css">
.job-post{border-bottom: 1px solid red; padding: 0; margin: 10px 0;}
h3, p{padding: 0; margin:0;}
.view-job{cursor: pointer;}
</style>
<script type="text/javascript">
$(document).ready(function() {
$("div#job-details").css("display" , "none");
$("h3#view-job").click(function() {
$("div#job-details").css("display" , "block");
});
});
</script>
<?php
// Connects to your Database
mysql_connect("xx", "xx", "xx") or die(mysql_error());
mysql_select_db("lcwebsignups") or die(mysql_error());
$data = mysql_query("SELECT * FROM openjobs")
or die(mysql_error());
?>
<div id="job-container">
<?php
Print "";
while($info = mysql_fetch_array( $data ))
{
Print "<div class='job-post'>";
Print "<h3>Position / Location:</h3> <p>".$info['jobtitle'] . ", ".$info['joblocation'] . "</p>";
Print "<h3 id='view-job'>View Job:</h3> <div id='job-details'>".$info['jobdesc'] . " </div>";
Print "</div>";
}
?>
</div><!--//END job-container-->

Assign the classNames instead of id's
Then use the this context to select your div which will only search for the one in the context and not all the divs
$("h3.view-job").on('click',function() {
$(this).next("div.job-details").css("display" , "block");
});

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<style type="text/css">
.job-details{display:none;}
.job-post{border-bottom: 1px solid red; padding: 0; margin: 10px 0;}
h3, p{padding: 0; margin:0;}
.view-job{cursor: pointer;}
</style>
<script type="text/javascript">
$(document).ready(function() {
// Please hide this class on CSS
// $("div.job-details").css("display" , "none");
$("h3.view-job").click(function() {
// you ned to use this keyword
// it is very important when you use javascript or jquery
// this keyword only pick element on which you click
$(this).parent().find(".job-details").show();
});
});
</script>
<?php
// Connects to your Database
mysql_connect("xx", "xx", "xx") or die(mysql_error());
mysql_select_db("lcwebsignups") or die(mysql_error());
$data = mysql_query("SELECT * FROM openjobs")
or die(mysql_error());
?>
<div id="job-container">
<?php
// First of all Please use echo instead of Print
echo "";
while($info = mysql_fetch_array( $data ))
{
echo "<div class='job-post'>";
echo "<h3>Position / Location:</h3> <p>".$info['jobtitle'] . ", ".$info['joblocation'] . "</p>";
// you can't use id multiple time in a same page so instead of id use Class
// if you want to use id then you have to generate uniq id
// check below I generate id --> I don't know your database field that's why I used jobId
echo "<h3 class='view-job' id='job".$info['jobId']."'>View Job:</h3> <div class='job-details'>".$info['jobdesc'] . " </div>";
echo "</div>";
}
?>
</div><!--//END job-container-->

This should do what you want (tested okay). Just replace your mysql login info and the example should work.
I completed your job-details div (it was missing the data from php), but what you were really looking for is the jQuery code.
When an <h3> tag whose id begins with the characters view-job is clicked, the jQuery click event handler will:
re-hide all divs whose id starts with the chars job-details
display the next div in the DOM tree
CODE:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<style type="text/css">
.job-post{border-bottom: 1px solid red; padding: 0; margin: 10px 0;}
h3, p{padding: 0; margin:0;}
.view-job{cursor: pointer;}
</style>
<script type="text/javascript">
$(document).ready(function() {
$("div[id^='job-details']").css("display" , "none");
$('h3[id^="view-job"]').click(function() {
$("div[id^='job-details']").hide(500);
$(this).next('div').show(500);
});
});
</script>
<?php
// Connects to your Database
mysql_connect("xx", "xx", "xx") or die(mysql_error());
mysql_select_db("lcwebsignups") or die(mysql_error());
$data = mysql_query("SELECT * FROM openjobs") or die(mysql_error());
$data = mysql_query("SELECT * FROM openjobs") or die(mysql_error());
?>
<div id="job-container">
<?php
echo "<br>";
while($info = mysql_fetch_assoc( $data )) {
echo "<div class='job-post'>";
echo "<h3>Position / Location:</h3> <p>".$info['jobtitle'] . ", ".$info['joblocation'] . "</p>";
echo "<h3>View Job:</h3> <div id='job-details'>".$info['jobdetails']."</div>";
echo "</div>";
}
?>
</div><!--//END job-container-->

Related

Make elements in a list clickable (PHP)

I'm currently developing a simple web page that enables the user to: upload an image and a corresponding caption to a DB, let the user view the images and delete them.
I have already accomplished the first two with the following code:
<?php
#include_once("connection.php");
$db = new mysqli("192.168.2.2", "root", "", "proyectoti");
if ($db->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
echo "Información de servidor: ";
echo $db->host_info . "\n";
// Initialize message variable
$msg = "";
// If upload button is clicked ...
if (isset($_POST['upload'])) {
// Get image name
$image = addslashes(file_get_contents($_FILES['image']['tmp_name'])); #$_FILES['image']['name'];
// Get text
$image_text = mysqli_real_escape_string($db, $_POST['image_text']);
$sql = "INSERT INTO images (image, image_text) VALUES ('{$image}', '{$image_text}')";
// execute query
mysqli_query($db, $sql);
}
$result = mysqli_query($db, "SELECT * FROM images");
?>
<!DOCTYPE html>
<html>
<head>
<title>Proyecto TI | Sube imágenes</title>
<style type="text/css">
#content{
width: 50%;
margin: 20px auto;
border: 1px solid #cbcbcb;
}
form{
width: 50%;
margin: 20px auto;
}
form div{
margin-top: 5px;
}
#img_div{
width: 80%;
padding: 5px;
margin: 15px auto;
border: 1px solid #cbcbcb;
}
#img_div:after{
content: "";
display: block;
clear: both;
}
img{
float: left;
margin: 5px;
width: 300px;
height: 140px;
}
</style>
</head>
<body>
<h1>Proyecto TI | <a> Interfaz </a></h1>
<div id="content">
<?php
while ($row = mysqli_fetch_array($result)) {
echo "<div id='img_div'>";
#echo "<img src='images/".$row['image']."' >";
echo '<img src="data:image/jpeg;base64,'.base64_encode( $row['image'] ).'"/>';
echo "<p>".$row['image_text']."</p>";
echo "</div>";
}
?>
<form method="POST" action="index.php" enctype="multipart/form-data">
<input type="hidden" name="size" value="1000000">
<div>
<input type="file" name="image">
</div>
<div>
<textarea
id="text"
cols="40"
rows="4"
name="image_text"
placeholder="Di algo de esta imagen ^^"></textarea>
</div>
<div>
<button type="submit" name="upload">Publicar</button>
</div>
</form>
</div>
</body>
</html>
It looks like this:
Now, the only part I'm missing is being able to delete an image (basically I only echo each image), how would you suggest for me to accomplish this, to make each item clickable and let's say, pop up a dialog or button to perform an action (delete from DB).
I really don't know much about PHP or CSS/HTML, any help would be much appreciated, Thank you!
Within this loop:
<?php
while ($row = mysqli_fetch_array($result)) {
echo "<div id='img_div'>";
#echo "<img src='images/".$row['image']."' >";
echo '<img src="data:image/jpeg;base64,'.base64_encode( $row['image'] ).'"/>';
echo "<p>".$row['image_text']."</p>";
echo "</div>";
}
?>
Personally I would add an element to click on - like an 'x' or whatever - with a unique data attribute:
https://www.abeautifulsite.net/working-with-html5-data-attributes
You have to add the unique id of the image obviously, so you can let SQL know which row to delete... Like this:
echo "<div class='delete-image' data-id='" . $row['id'] . "'>x</div>';
Then I would link this class to an AJAX call to make an asynchronous request to the server and delete the image without reloading the page. It's not very hard.
An easier solution would be to create a new form in the loop, so you create multiple forms per image, add a hidden field with the image id in the form and make a submit button with the valeu 'delete' or simply 'x'.
The same way you created the check:
if (isset($_POST['upload'])) { ... }
You can create something like this:
if (isset($_POST['delete-image'])) { ... }
You will be carrying the image id value like a normal form input. And you can do whatever you want with it.
I would HIGHLY suggest you to look into how to work with jquery and ajax calls though.
Opening a dialogue and ask the user before he deletes an item will require that you either go another page for deletion or use javascript for this.
In both cases, you should somehow set an identifier for your image in your html-code.
I would suggest you give every image an id
'<img ... id="'.$yourImageId.'">'
or a data-attribute
'<img ... data-identifier="'.$yourImageId.'" >'
with that identifier.
First variant:
...
echo '<a href="/path/to/delete/view/page.php?image=yourImageId">'
echo '<img ... id="'.$yourImageId.'"/>'
echo '</a>'
...
and on this delete-view-page, you just have a form that triggers your delete-code
<form action="/path/to/delete/view/page.php" method="POST">
<input type="hidden" name="id" value="<?php echo $yourImageId ?>">
</form>
<!-- after this, react with $_POST['id'] --> to the id sent to the server side and delete the image in your database -->
The other way is not server side rendered.
You should give your Elements some class like "my-clickable-image".After that, you have a script on your page, that looks something like the following
<script>
/* get your images with querySelectorAll, the . stands for class and after that your name */
var clickables = document.querySelectorAll(".my-clickable-image");
clickables.foreach(function(image){
// say that for each image, when clicked the generated function is called image.addEventListener('click',generateShowDialogueFunc(image.getAttr("id")));
});
// generate a function(!) that reacts to an image being clicked
function generateShowDialogueFunc(imageIdentifier){
// return a function that adds a Pop Up to the page
// the Pop Up has approximately the code of the first options second page
// except that now, it must create and remove elements in javascript
return function createPopUp(){
removePopUp();
var popup = document.createElement("div");
popup.setAttribute("id","deletePopUp");
var deleteForm = document.createElement("form");
deleteForm.setAttr("action","/path/to/file/that/deletes/given/query.php?id="+imageIdentifier);
var deleteContents = '<p> Do you want to delete this image? </p>'
+ '<button type="submit"> yes </button>'
+ '<button onclick="removePopUp()"> no </button>'
deleteForm.innerHTML = deleteContents;
document.body.appendChild()
}
}
// remove the Pop Up that can be used to delete an image from the page
function removePopUp(){
var existingPopUp = document.getElementById("deletePopUp");
if(existingPopUp) document.body.removeChild(existingPopUp);
}
</script>
<!-- just add some styling to make the popup show on top of the page -->
<style>
#deletePopUp{
width: 50vw;
height: 50vh;
position: absolute;
z-index: 1;
padding: 1em;
}
</style>
In this case, you just call the server to delete the image, not to show the delete form.
I would suggest the second one but stack overflow is not made for opinion based answers.
Regarding simple security:
It looks like your users could give titles or texts to images.
try what happens if a user gives a title like <bold>some title</title>
and guess what would happen if the title is <script>window.location.href="google.com"</script>
(XSS * hint hint *)
Regarding code structure:
If you want to do something like web development more often, think about separating your database accessing code, and your logic code from your php page template code, this is called 3 tier architecture and standard for bigger projects but i guess this is really just a first, short prototype or test.

php pick data from web and show it in div

i have a div and also on same page i have some data which is show on web page i just want data show on div how can i do this? i am very very new in php .thanks here is the php file.
<?php
define('HOST','xxxxxxxxxxx');
define('USER','xxxxxxxxxxxxx');
define('PASS','xxxxxxxx');
define('DB','androidapi2');
$con = mysqli_connect(HOST,USER,PASS,DB);
$sql = "select * from users WHERE status = 1";
$res = mysqli_query($con,$sql);
$result = array();
while($row = mysqli_fetch_array($res)){
array_push($result,
array(
// 'id'=>$row[0],
'email'=>$row[3],
));
}
echo json_encode(array("result"=>$result));
mysqli_close($con);
?>
<html>
<head>
<title>DIC ChatBox Beta 1</title>
<style>
#usersOnLine {
font-family:tahoma;
font-size:12px;
color:black;
border: 3px teal solid;
height: 525px;
width: 250px;
float: right;
overflow-y:scroll;
}
.container{
width:970px;
height:auto;
margin:0 auto;
}
</style>
</head>
<body>
<div class="container">
</div>
<h2> all contacts</h2>
<div id="usersOnLine">
</div>
</div>
</body>
</html>
here is the div id usersonline where i want all data show . how to made it.
There is no need to use json_encode(array("result"=>$result));, directly use $result
<div id="usersOnLine">
<?php
foreach($result as $key => $val)
{
echo $val['email'];
echo "<br>";
}
?>
</div>
If you want to use it on another page
Creating New Session In php file
<?php
session_start(); ///at the top of this file
///after your query and creating array
$_SESSION["result"]= $result;////set $result in session
?>
Getting Session on another page
<?php
session_start();
if(isset($_SESSION["result"]))
{
$result = $_SESSION["result"];
///your foreach loop to print data
}
?>
READ SESSION DOCUMENTAION

How can I auto increment mysql LIMIT number?

So I load 3 records with this msql query:
$query = "SELECT * FROM adatok ORDER BY `id` DESC LIMIT 3 "
And I created a load more button for user can be load the other 3 records with this query:
$query = "SELECT * FROM adatok ORDER BY `id` DESC LIMIT 4,3
And then come the problem.
Becouse when the user click for the load more button again, this get the same record as which had been received.
So how can I autoincrement limit number?
demo page:
http://neocsatblog.mblx.hu/addvideos/type.html
Press crtl+i for open box.
Update:
The id is auto incremented.
Thanks for the improvements for #spencer7593.
My table strukture looks like this.
Full php code, for what happening if you click the more button:
<?php
$connection = mysql_connect('localhost', 'neocsat_videos', 'password'); //The Blank string is the password
mysql_select_db('neocsat_videos');
mysql_query("SET CHARACTER SET utf8 ");
$page = 1
$query = "SELECT * FROM adatok ORDER BY `data_reg` DESC LIMIT 3,4 ";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)){ //Creates a loop to loop through results
echo '<div class="video-header">';
if (!function_exists('echoOnce')) {
$runOnce = false;
function echoOnce()
{
global $runOnce;
if(!$runOnce)
{
$runOnce = true;
return "<img class='close2' src='/kep/icon_24x24_close_highlight.png'>";
}
}
}
$datatime=$row['date_reg'];
$img = '<img title="' . $datatime . '" src="time.png" class="time_icon" >';
echo echoOnce();
echo '<p>';
echo $row['name'];
echo '</p>';
echo $img;
echo '</div>';
echo '<div class="result">';
echo ' <iframe class="video" allowfullscreen style="overflow-x: hidden; overflow-y: hidden;" width="658px" height="569" frameborder="0" src="'.$row['url'].'"></iframe>' ;
echo '</div>';
echo '<div class="leiras">';
echo '<p>';
echo $row['leiras'] ; //$row['index'] the index here is a field name
echo '</p>';
echo '</div>';
echo '<div class="clear">';
echo '</div>';
?>
<a class='load'><div class='more'>További videók betöltése</div></a>
<?php
$connection = mysql_connect('localhost', 'neocsat_videos', 'zP77XRavaXMA'); //The Blank string is the password
mysql_select_db('neocsat_videos');
mysql_query("SET CHARACTER SET utf8 ");
$page = 1
$query = "SELECT * FROM adatok ORDER BY `data_reg` DESC LIMIT 3,4 ";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)){ //Creates a loop to loop through results
echo '<div class="video-header">';
if (!function_exists('echoOnce')) {
$runOnce = false;
function echoOnce()
{
global $runOnce;
if(!$runOnce)
{
$runOnce = true;
return "<img class='close2' src='/kep/icon_24x24_close_highlight.png'>";
}
}
}
$datatime=$row['date_reg'];
$img = '<img title="' . $datatime . '" src="time.png" class="time_icon" >';
echo echoOnce();
echo '<p>';
echo $row['name'];
echo '</p>';
echo $img;
echo '</div>';
echo '<div class="result">';
echo ' <iframe class="video" allowfullscreen style="overflow-x: hidden; overflow-y: hidden;" width="658px" height="569" frameborder="0" src="'.$row['url'].'"></iframe>' ;
echo '</div>';
echo '<div class="leiras">';
echo '<p>';
echo $row['leiras'] ; //$row['index'] the index here is a field name
echo '</p>';
echo '</div>';
echo '<div class="clear">';
echo '</div>';
?>
<a class='load'><div class='more'>További videók betöltése</div></a>
<?php
}
mysql_close(); //Make sure to close out the database connection
?>
<meta charset="utf-8">
<link href='http://fonts.googleapis.com/css?family=Nunito:700' rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=Lobster' rel='stylesheet' type='text/css'>
<link rel="stylesheet" type="text/css" href="style2.css">
<style>
#video-body,.video-body{
background-color:white;
width:780px;
position: fixed !important;
top: 100px;
right: -799px;
border-radius: 5px;
padding-left: 13px;
padding-bottom: 30px;
max-height: 453px;
overflow-x: hidden;
}
#video-header,.video-header{
border-bottom: 6px solid gray;
margin-left: 73px;
width: 628px;
}
#result,.result{
margin-left: 62px;
}
#video-header p,.video-header p{
margin-left: 158px;
font-family: 'Nunito', sans-serif;
font-size: 22px;
font-weight: bold;
padding-top: 12px;
margin-bottom: 11px;
}
#clear,.clear{
border-bottom: 6px solid gray;
width: 625px;
margin: 50px 82px;
}
#leiras, .leiras{
margin: -274px 139px 28px;
font-family: 'Nunito', sans-serif;
font-size: 13px;
font-weight: bold;
word-wrap: break-word;
background-color: rgba(0, 0, 0, 0.8);
border-radius: 5px;
min-height: 29px;
text-align: center;
padding: 3px;
}
.leiras p{
color:white;
}
</style>
<script>
$(".close2").click(function(){
$(".video-body").fadeOut();
$( "iframe" ).remove();
$( "div" ).remove();
$( "p" ).remove();
});
$(".video-body").on('click', '.load', function() {
jQuery.ajaxSetup({ async: false }); //if order matters
$.get("next.php", '', function (data) { $("#video-body").append(data); });
});
$( ".time_icon" ).tooltip({
show: null,
position: {
my: "left top",
at: "left bottom"
},
open: function( event, ui ) {
ui.tooltip.animate({ top: ui.tooltip.position().top + 10 }, "fast" );
}
});
</script>
<script>
// The plugin code
(function($){
$.fn.urlToLink = function(options) {
var options = $.extend({}, $.fn.urlToLink.defaults, options);
return this.each(function(){
var element = $(this),
expression = /(\b(https?|ftp|file|https|http):\/\/[-A-Z0-9+&##\/%?=~_|!:,.;]*[-A-Z0-9+&##\/%=~_|])/ig;
// The magic
return element.html( element.text().replace(expression, "<a class=lightview href='$1' target='"+options.target+"'>$1</a>") );
});
}
/**
* Default configuration
*/
$.fn.urlToLink.defaults = {
target : '_self' // Link target
}
})(jQuery)
// The call
$('p').urlToLink();
</script>
Javascript:
$(".video-body").on('click', '.load', function() {
jQuery.ajaxSetup({ async: false }); //if order matters
$( "#video-body" ).load( "next.php" );
});
$limit = 2; //how many items to show per page
$page = $_GET['page'];
if($page)
$start = ($page - 1) * $limit; //first item to display on this page
else
$start = 0; //if no page var is given, set start to 0
$sql = "SELECT column_name FROM tbl_name LIMIT $start, $limit";
$query = "SELECT * FROM adatok ORDER BYidDESC LIMIT ".($page*3 ).",3"; where $page is number of times that More button pressed.
on first click $page = 1, on second $page = 2 and so on
Assuming that id is unique, the normal pattern is to save the last id value retrieved by the previous query:
Then your "next" query would be of the form:
SELECT ... FROM adatok WHERE id < :last_id ORDER BY id DESC LIMIT 3
supplying the last retrieved id value for the :last_id placeholder.
For example, the previous query returns id values of 214, 212, 211. We "save" the value of 211 on the page. When the user clicks the "more data", then we take that value of 211, and supply it in the "next rows" query.
SELECT ... FROM adatok WHERE id < 211 ORDER BY id DESC LIMIT 3
^^^
This query is guaranteed to not return id values that were retrieved by the previous query. If the execution of this query returns id values of 210, 209, 208... we save that last retrieved id value, 208. A subsequent "next" query would use that saved value...
SELECT ... FROM adatok WHERE id < 208 ORDER BY id DESC LIMIT 3
^^^
And so on.
The OP "next" query is going to skip the fourth row; the first argument to LIMIT should be the number of rows retrieved previously... LIMIT 3,3. (Using LIMIT 4,3 as in the OP query is actually going to "skip" the fourth row.
For the next sets:
... LIMIT 6,3
... LIMIT 9,3
One of the issues with this approach is that if there are any insertions to the table with a larger id value, since the query is ordering by descending id value, a subsequent "next" query has the potential to return a row(s) that were retrieved previously. If rows with higher id values are deleted, this form has the potential to "skip" some id values.
Using a queries of the first form, at the top of my answer, results are unaffected by insertions/deletions of rows with higher id values.

How to load values to page while scrolling the page

I have a table named "User" with more than 3k rows in MySql database.I want to fetch the database while scrolling the page(As like Facebook news feeds). I surfed for a long time but I can't get it. hoping positive response as soon as possible.
thank you!
If I understood what did you mean:
Database Table
CREATE TABLE messages(
mes_id INT PRIMARY KEY AUTO_INCREMENT,
msg TEXT);
load_data.php
When we are scrolling down a webpage, the script($(window).scroll) finds that you are at the bottom and calls the last_msg_funtion(). Take a look at $.post("") eg: $.post("load_data.php?action=get&last_msg_id=35")
<?php
include('config.php');
$last_msg_id=$_GET['last_msg_id'];
$action=$_GET['action'];
if($action <> "get")
{
?>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
function last_msg_funtion()
{
var ID=$(".message_box:last").attr("id");
$('div#last_msg_loader').html('<img src="bigLoader.gif">');
$.post("load_data.php?action=get&last_msg_id="+ID,
function(data){
if (data != "") {
$(".message_box:last").after(data);
}
$('div#last_msg_loader').empty();
});
};
$(window).scroll(function(){
if ($(window).scrollTop() == $(document).height() - $(window).height()){
last_msg_funtion();
}
});
});
</script>
</head>
<body>
<?php
include('load_first.php'); //Include load_first.php
?>
<div id="last_msg_loader"></div>
</body>
</html>
<?php
}
else
{
include('load_second.php'); //include load_second.php
}
?>
load_first.php
Contains PHP code to load 20 rows form the message table.
<?php
$sql=mysql_query("SELECT * FROM messages ORDER BY mes_id DESC LIMIT 20");
while($row=mysql_fetch_array($sql))
{
$msgID= $row['mes_id'];
$msg= $row['msg'];
?>
<div id="<?php echo $msgID; ?>" class="message_box" >
<?php echo $msg; ?>
</div>
<?php
}
?>
load_second.php
Contains PHP code to load 5 rows less than last_msg_id form the message table.
<?php
$last_msg_id=$_GET['last_msg_id'];
$sql=mysql_query("SELECT * FROM messages WHERE mes_id < '$last_msg_id' ORDER BY mes_id DESC LIMIT 5");
$last_msg_id="";
while($row=mysql_fetch_array($sql))
{
$msgID= $row['mes_id'];
$msg= $row['msg'];
?>
<div id="<?php echo $msgID; ?>" class="message_box" >
<?php echo $msg;
?>
</div>
<?php
}
?>
CSS
body
{
font-family:'Georgia',Times New Roman, Times, serif;
font-size:18px;
}
.message_box
{
height:60px;
width:600px;
border:dashed 1px #48B1D9;
padding:5px ;
}
#last_msg_loader
{
text-align: right;
width: 920px;
margin: -125px auto 0 auto;
}
.number
{
float:right;
background-color:#48B1D9;
color:#000;
font-weight:bold;
}
Take a look at live demo and scroll down.
Regards,
Ivan
Check out http://jscroll.com/ or just google for "jQuery load content while scrolling" or "jQuery infinite scroll" for other alternatives.

Creating 5 Star Rating System With PHP , MySQL ,Jquery And Ajax

I've downloaded this tutorial http://megarush.net/5-star-rating-system-with-php-mysql-jquery-and-ajax/ but I'm getting these errors:
Notice: Undefined variable: rat in C:\xampp\htdocs\rating\rating.php on line 37
Notice: Undefined variable: v in C:\xampp\htdocs\rating\rating.php on line 41
<?php
include("settings.php");
connect();
$ids=array(1,2,3);
?>
<html>
<head>
<script src="jquery.js" type="text/javascript"></script>
<link rel="stylesheet" href="rating.css" />
<script type="text/javascript" src="rating.js"></script>
</head>
<body>
<?php
for($i=0;$i<count($ids);$i++)
{
$rating_tableName = 'ratings';
$id=$ids[$i];
$q="SELECT total_votes, total_value FROM $rating_tableName WHERE id=$id";
$r=mysql_query($q);
if(!$r) echo mysql_error();
while($row=mysql_fetch_array($r))
{
$v=$row['total_votes'];
$tv=$row['total_value'];
$rat=$tv/$v;
}
$j=$i+1;
$id=$ids[$i];
echo'<div class="product">
Rate Item '.$j.'
<div id="rating_'.$id.'" class="ratings">';
for($k=1;$k<6;$k++){
if($rat+0.5>$k)$class="star_".$k." ratings_stars ratings_vote";
else $class="star_".$k." ratings_stars ratings_blank";
echo '<div class="'.$class.'"></div>';
}
echo' <div class="total_votes"><p class="voted"> Rating: <strong>'.#number_format($rat).'</strong>/5 ('.$v. ' vote(s) cast)
</div>
</div></div>';}
?>
</body></html>
$rat and $v are being defined within the scope of your while loop.
If you declare them globally (outside the loop), the rest of your code will recognize them.
$rat = 0;
$v = 1;
while($row=mysql_fetch_array($r))
{
$v=$row['total_votes'];
$tv=$row['total_value'];
$rat=$tv/$v;
}
See here:
http://bgallz.org/988/javascript-php-star-rating-script/
This combines a Javascript code that generated the URL for the different ratings given as well as the change in display for the stars before and after a rating is given.
An overlay DIV is displayed after the rating is given so that no immediate ratings can be given by the same. It also stores the user's IP address with the rating submission to prevent multiple ratings from one user.
This is a simple and easy to use script with just Javascript and PHP for star rating.
The problem is because of scoping of those variables. When you are trying to echo those variables outside the while loop; PHP can not find the varables as they were created (and assigned) inside the loop. To solve this, just assign a blank value to both variables outside too:
if(!$r) echo mysql_error();
$rat = 0;
$v = 1; // In case there are no records.
while($row=mysql_fetch_array($r))
{
$v = $row['total_votes'];
$tv = $row['total_value'];
$rat = $tv/$v;
}
Add this at line at beginning to nide notice error in your code .
error_reporting(E_ALL ^ E_NOTICE);
Most of time notice error do not affect the program.
In case if your votes are not recording then delete your cookies and try to vote from different IP address .This script has a feature to not accept votes from same ip or vistitor to avoid multiple votes by same users on same product.
var cname=document.getElementById(id).className;
var ab=document.getElementById(id+"_hidden").value;
document.getElementById(cname+"rating").innerHTML=ab;
for(var i=ab;i>=1;i--)
{
document.getElementById(cname+i).src="star2.png";
}
var id=parseInt(ab)+1;
for(var j=id;j<=5;j++)
{
document.getElementById(cname+j).src="star1.png";
}
Code from http://talkerscode.com/webtricks/star-rating-system-using-php-and-javascript.php
<style>
.star {
font-size: x-large;
width: 50px;
display: inline-block;
color: gray;
}
.star:last-child {
margin-right: 0;
}
.star:before {
content:'\2605';
}
.star.on {
color: red;
}
.star.half:after {
content:'\2605';
color: red;
position: absolute;
margin-left: -20px;
width: 10px;
overflow: hidden;
}
</style>
<div class="stars">
<?php
$enable = 5.5; //enter how many stars to enable
$max_stars = 6; //enter maximum no.of stars
$star_rate = is_int($enable) ? 1 : 0;
for ($i = 1; $i <= $max_stars; $i++){ ?>
<?php if(round($enable) == $i && !$star_rate) { ?>
<span class="<?php echo 'star half'; ?>"></span>
<?php } elseif(round($enable) >= $i) { ?>
<span class="<?php echo 'star on'; ?>"></span>
<?php } else { ?>
<span class="<?php echo 'star'; ?>"></span>
<?php }
}?>
</div>

Categories