I have a PHP page that lists a bunch of words that it grabs from a MySQL database table. It displays the words in different sizes based on a count in the table:
<?php
$selectStr = "select * from test";
if ($results = MySQL($dbName, $selectStr))
{
$rowCount = MySQL_NUMROWS($results);
}
$i = 0;
while ($i < $rowCount)
{
echo '<div style="float: left; font-size:' . (MySQL_RESULT($results,$i,'count') * 5) . 'px;">' . MySQL_RESULT($results,$i,'word') . '</div>';
$i++;
}
?>
The trick is that I want the content to display dynamically. So if a user is sitting on the page, and one of the word counts goes up, I want the word to change size without the user refreshing the page.
I am a novice with jQuery. I have used it a bit before, but only using examples. Can someone steer me in a good direction to have my page dynamically change the content without refreshing?
You can auto refresh your page body like this ... give body id='body'
<html>
<head>
<script type="text/javascript">
var auto_refresh = setInterval(
function ()
{
$('#body').load('wordscount.php').fadeIn("slow");
}, 10000); // refresh every 10000 milliseconds
</script>
</head>
<body>
<div id='content'></div>
</body>
Dont forget to include jquery inside your head tag
It calls the file rowfunctie.php every 30000ms and fills the topbar diff with with the result of the getRows function.
<div id="center-rows">
<div id="links">Nu </div>
<div id="rows">
<div id="topbar"></div>
</div>
<div id="rechts"> aantal rijen</div>
</div>
<script type="text/javascript">
function doRequest() {
jQuery("#topbar").fadeOut('slow', function() {
jQuery.ajax({
type: "GET",
url: "rowfunctie.php",
cache: false,
success: function(html){
jQuery("#topbar").html(html);
jQuery("#topbar").fadeIn('slow',function() {
setTimeout('doRequest()',30000);
});
}
});
});
}
doRequest();
</script>
rowfunctie.php should look like this beneath:
<?php
$selectStr = "select * from test";
if ($results = MySQL($dbName, $selectStr))
{
$rowCount = MySQL_NUMROWS($results);
}
$i = 0;
while ($i < $rowCount)
{
echo '<div style="float: left; font-size:' . (MySQL_RESULT($results,$i,'count') * 5) . 'px;">' . MySQL_RESULT($results,$i,'word') . '</div>';
$i++;
}
?>
Related
I have this php file which is fetch data from my database and place it into divs. this div created by while loop I want tow div only to be select then send the content to php file using Ajax.
The code execute with no problem but there is no result!!
Any help advance and I completely lost of mind !!!
while($row=mysqli_fetch_array($result)){
$so=$row[0];
$s=$row[1];
$m=$row[2];
$a=$row[3];
$b=$row[5];
$c=$row[8];
?>
<body>
<div id="all"> //start all
<div class="r"> //start r
<div id="e"><?php echo"{$s}"; ?></div>
<div id="b"><?php echo"{$m}"; ?></div>
<div id="a"><?php echo"{$a}"; ?></div>
<div id="b"><?php echo"{$b}"; ?></div>
</div> //end r
</div> //end all
<?php
} //end while
?>
<div id="show"></div>
script code
$(document).ready(function(){
$(".r").click(function(){
$data = $(this).text();
alert($data); //it work well
$.ajax({
url: "view.php",
type: "post",
data: {
you: $data
},
success:function(response){
$('#show').html(response);
}
});
});
});
view.php
<?php
if(isset($_post['you'])){
printf("ok"); //just to check
}
?>
First of all
IDs on a page should be unique
Now coming to your code, maintain a global variable to have select count and call the below function to allow selection of maximum 2 divs
var selectCount = 0;
$('.r div').click(function() {
if(!$(this).hasClass('active') && selectCount < 2) {
$(this).addClass('active');
selectCount++;
}
else if($(this).hasClass('active')) {
$(this).removeClass('active');
selectCount--;
}
else {
alert("ony 2 allowed");
}
});
To send the data to your call you can
$('button').click(function() {
var result = [];
$('.active').each(function(val){
result.push(val);
});
});
You may change the data format accordingly.
I have a system in php, ajax and jquery. This system will search the database queries per page 5 and divide the results into several pages. The problem is that the more the results are more pages are displayed. In the current code, paging is like this: first 1 2 3 4 5 6 last. I would like to remain so: first 1 2 ... 5 6 last. Ie I want to limit the pagination. If I do not limit the pagination when they have more results would look like this: 1234567891011 ...
The code:
<script type="text/javascript">
$(document).ready(function(){
function showLoader(){
$('.search-background').fadeIn(200);
}
function hideLoader(){
$('.search-background').fadeOut(200);
};
$(".pagcon li").click(function(){
showLoader();
$(".pagcon li").removeClass('current');
$(this).addClass("current");
$("#resultado").load("data.php?page=" + this.id, hideLoader)
return false;
});
$("#1").addClass("current");
showLoader();
$("#resultado").load("data.php?page=1", hideLoader);
});
</script>
<style type="text/css">
#consultas {
width:780px;
min-height:245px;
overflow:hidden;
}
.search-background {
background:#FFF;
display:none;
height:154px;
position:absolute;
padding-top:84px;
text-align:center;
opacity:0.5;
filter:alpha(opacity=50);
width:780px;
z-index:999;
}
</style>
<div id="consultas">
<?php
$per_page = 5;
$sql = "select * from consultas ";
$rsd = mysql_query($sql);
$count = mysql_num_rows($rsd);
$pages = ceil($count/$per_page);
?>
<div class="search-background">
<label><img title="Carregando..." src="loader.gif" alt="" /></label>
</div>
<div id="resultado">
</div>
</div>
<ul class="pagination clearfix pagcon">
<?php
//Show page links
echo '<li id="1"><a title="Página 1" href="#">Primeiro</a></li>';
for($i=1; $i<=$pages; $i++)
{
echo '<li id="'.$i.'">'.$i.'</li>';
}
echo '<li id="'.$pages.'"><a title="Página '.$pages.'" href="#">Último</a></li>';
?>
</ul>
data.php:
<?php
include_once("config.php"); //MYSQL CONFIG
$per_page = 5;
$sqlc = "show columns from consultas";
$rsdc = mysql_query($sqlc);
$cols = mysql_num_rows($rsdc);
$page = $_REQUEST['page'];
$start = ($page-1)*5;
$sql = "select * from consultas ORDER BY data DESC LIMIT $start,5";
$rsd = mysql_query($sql);
?>
<?php
while ($rows = mysql_fetch_assoc($rsd))
{?>
<div class="message status success">
<span><b><?php echo $rows['consulta']; ?> (<font color="#8D4B19"><?php echo $rows['codigo']; ?></font>)</b></span>
<span><?php if(strlen($rows['user']) >= 30){ echo substr($rows['user'], 0, 30)."..."; } else { echo $rows['user']; } ?></span>
<span><b><?php echo $rows['operacao']; ?></b></span>
<span><?php echo date("d/m/Y", strtotime($rows['data'])); ?></span>
<span>R$ <?php echo $rows['valor']; ?></span>
</div>
<?php
}?>
<script type="text/javascript">
$(document).ready(function(){
var Timer = '';
var selecter = 0;
var Main =0;
bring(selecter);
});
function bring ( selecter )
{
$('div.status:eq(' + selecter + ')').stop().animate({ opacity: '1.0', height: '34px' },300,function(){
if(selecter < 6)
{
$('div.status').stop().animate({ opacity: '1.0', height: '17px' },300);
clearTimeout(Timer);
}
});
selecter++;
var Func = function(){ bring(selecter); };
Timer = setTimeout(Func, 20);
}
</script>
Try
$threshold=1;
for($i=1; $i<=$threshold+1; $i++)
{
echo '<li id="'.$i.'">'.$i.'</li>';
}
echo " ... ";
for($i=$pages-$threshold; $i<=$pages; $i++)
{
echo '<li id="'.$i.'">'.$i.'</li>';
}
By varying $threshold you can vary the number of page links available.
However, it would be better to present the results as first ... 3 4 5 ... last instead if the user is on the fourth page. This way they can easily move between adjacent pages. Also you can run through the loop fewer times. $current_page is the current page you are on. This needs to be made available to the pagination code somehow.
$threshold=1;
$lower_limit=(($current_page-$threshold)>1)?$current_page-$threshold:1;
$upper_limit=(($current_page+$threshold)<$pages)?$current_page-$threshold:$pages;
for($i=$lower_limit; $i<=$upper_limit; $i++)
{
echo '<li id="'.$i.'">'.$i.'</li>';
}
Edit for the sake of this specific question
Your pagination is once and not reloaded in the ajax. In order to achieve this reduced pagination, you either need to
load only a few link elements as in either of the choices above and add new link elements or
load all the link elements but hide unnecessary links until they are required.
For the latter:
php
$threshold=1;
for($i=1; $i<=$threshold+1; $i++)
{
echo '<li id="'.$i.'">'.$i.'</li>';
}
echo " ... ";
for($i; $i<=$pages; $i++)
{
echo '<li id="'.$i.'"'.($i<($pages-$threshold)?'style="display:none"':'')'>'.$i.'</li>';
}
javascript
$(".pagcon li").click(function(){
showLoader();
$(".pagcon li").hide();//hide all links
$(".pagcon li").removeClass('current');
$(this).addClass("current").show();
var id=parse_int($(this).attr(id));
$(".pagcon li:first, .pagcon li:first, .pagcon li#"+(id-1)+" .pagcon li#"+(id+1)).show();//show adjacent links and 'First' and 'Last'
$("#resultado").load("data.php?page=" + this.id, hideLoader)
return false;
});
sorry if the title is a little.. vague i couldnt pin it down.
So i am developing a friend request system which works i guess similar in concept to facebook. So you get a request and it lists them without a page reload.
However i get the div 'refreshing' or so i think i cant test the php which is where i have a problem, i will post the relevent code and files below.
It may look a little long winded but it shouldnt be too bad in reality. My php code should keep executing the query which is looking at the database in the updateFriendBox.php however it doesnt seem to be doing this. My code may be messy as well so I apologise.
myaccount.php
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script language="javascript" type="text/javascript">
function refreshDiv()
{
$.get('updateFriendBox.php', function(data){$('#refresh').html(data);});
}
$(function()
{
refreshDiv();
setInterval(refreshDiv, 5000);
});
function box(x){
if($('#'+x).is(":hidden")){
$('#'+x).slideDown(200);
} else {
$('#'+x).hide();
}
}
</script>
<?php
$addBox = '<div style="display:inline; padding:5px;">
Show/Hide Friend Requests
</div>';
// a bit further down in the code where its all called:
<? echo $addBox; ?></span>
<div class="friendSlide" id="fRequ" style="height:240px; overflow:auto;">Your friend requests: <br />
<div id="refresh"> <?php // this is where the refresh call is ?>
</div>
</center>
</div>
</div>
</div>
updateFriendBox.php:
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script language="javascript" type="text/javascript">
function acceptFriendRequest(x) {
var url = "friendParse.php";
$.post(url,{ request: "acceptFriend", reqID: x}, function(data){
$("#req"+x).html(data).show().fadeOut(5000);
});
}
function denyFriendRequest(x) {
var url = "friendParse.php";
$.post(url,{ request: "denyFriend", reqID: x}, function(data){
$("#req"+x).html(data).show().fadeOut(5000);
});
}
</script>
</head>
<body>
<?php
include 'dbc.php';
$sql = "SELECT * FROM friendRecu WHERE mem2='" . $_SESSION['user_id'] . "' ORDER BY id ASC LIMIT 10";
$query = mysql_query($sql)or die(mysql_error());
$num_rows = mysql_num_rows($query);
if($num_rows < 1) {
echo "No friend requests";
} else {
while($row = mysql_fetch_array($query)){
$requestID = $row['id'];
$req = $row['mem1'];
$sqlName = mysql_query("SELECT full_name FROM users WHERE id='$req'");
while($row = mysql_fetch_array($sqlName)){
$requesterName = $row['full_name'];
}
echo '<hr /><table width="100%", cellpadding="5"><tr><td width="17%" align="left"><div style="overflow:hidden; height:50px; color:white;"></div></td> <td width="83%">' . $requesterName . ' added you as a friend
<span id="req' . $requestID . '">
Accept
||
Deny
</span></td></tr>
</table>';
}
}
?>
I think you are having a problem because your updateFriendBox.php is returning too much. Remove all that inline JS code, place it in an include file, and include it from myaccount.php. You also shouldn't have <head> and <body> sections in your updateFriendBox.php file.
The ajax call here doesn't create a whole new page, you're getting additional HTML to add to the original page.
So the only thing you should have there is your SQL query, the loop, and your HTML output for each data row.
I just asked another question here: global variable and reduce database accesses in PHP+MySQL
I am using PHP+MySQL. The page accesses to the database and retrieve all the item data, and list them. I was planning to open a new page, but now I want to show a pop div using javascript instead. But I have no idea how to utilize the variables of PHP in the new div. Here is the code:
<html>
</head>
<script type="text/javascript">
function showDiv() {
document.getElementById('infoDiv').style.visibility='visible';
}
function closeDiv() {
document.getElementById('infoDiv').style.visibility='hidden';
}
</script>
</head>
<body>
<ul>
<?php foreach ($iteminfos as $iteminfo): ?>
<li><?php echo($iteminfo['c1']); ?></li>
<?php endforeach;?>
</ul>
<div id="infoDiv" style="visibility: hidden;">
<h1><?php echo($c1) ?></h1>
<p><?php echo($c2) ?></p>
<p>Return</p>
</div>
</body>
</html>
"iteminfos" is the results from database, each $iteminfo has two value $c1 and $c2. In "infoDiv", I want to show the details of the selected item. How to do that?
Thanks for the help!
A further question: if I want to use, for example, $c1 as text, $c2 as img scr, $c1 also as img alt; or $c2 as a href scr, how to do that?
Try this:
<?php foreach ($iteminfos as $iteminfo): ?>
<li>
<a href="javascript:showDiv(<?php echo(json_encode($iteminfo)) ?>)">
<?php echo($iteminfo['c1']); ?>
</a>
</li>
<?php endforeach;?>
Also, modify showDiv to take your row data:
function showDiv(row) {
document.getElementById('infoDiv').style.visibility='visible';
document.getElementById('infoDiv').innerHTML = row['c1'];
}
Basically, you have to consider that the javascript runs in the browser long after the PHP scripts execution ended. Therefore, you have to embed all the data your javascript might need into the website or fetch it at runtime (which would make things slower and more complicated in this case).
Do you want a single info area with multiple items listed on the page and when you click an item the info area is replaced with the new content??? or you want a new info area for each item??
I see something along the lines of the first approach, so I will tackle the latter.
<?php
//do some php magic and get your results
$sql = 'SELECT title, c1, c2 FROM items';
$res = mysql_query($sql);
$html = '';
while($row = mysql_fetch_assoc($res)) {
$html .= '<li><a class="toggleMe" href="#">' . $row['title'] . '</a><ul>';
$html .= '<li>' . $row['c1'] . '</li><li>' . $row['c2'] . '</li></ul>';
$html .= '</li>'; //i like it when line lengths match up with eachother
}
?>
<html>
</head>
<script type="text/javascript">
window.onload = function(){
var els = document.getElementsByClassName("toggleMe");
for(var i = 0, l = els.length; i < l; i++) {
els[i].onclick = function() {
if(this.style.display != 'none') {
this.style.display = 'block';
} else {
this.style.display = 'none';
}
}
}
}
</script>
</head>
<body>
<ul>
<?php
echo $html;
?>
</ul>
</body>
</html>
i am new to ajax . i want to submit a data with the help of ajax and then get the new data replacing the old one in the same div as of which the old data was .
here is the jquery for sliding tab
$(document).ready(function() {
// Vertical Sliding Tabs
$('div#st_vertical').slideTabs({
// Options
contentAnim: 'slideH',
contentAnimTime: 600,
contentEasing: 'easeInOutExpo',
orientation: 'vertical',
tabsAnimTime: 300
});
});
ajax
function addhubs()
{
var group =$('#customhubs').val();
var user=$('#loginuser').val();
$.ajax({
type:"GET",
url: 'mfrnds.php?val='+group+'&& loguser='+user,
success: function(html){
}
});
}
the div i want to replace data
<div id="st_vertical" class="st_vertical">
<div class="st_tabs_container">
<div class="st_slide_container">
<ul class="st_tabs">
<?php $sql=mysql_query("select * from groups");
while($ab=mysql_fetch_array($sql))
{
$gpID[]=$ab['group_id'];
$gp=$ab['group_id'];
$gpName=$ab['group_name'];
?>
<li><?php echo $gpName;?></li>
<?php
}
?> </ul>
</div> <!-- /.st_slide_container -->
</div> <!-- /.st_tabs_container -->
and the mfrnds.php of the ajax call file contains query to update the new data.
$user=$_GET['loguser'];
$group=$_GET['val'];
$sql=mysql_query("insert into groups (group_name) values ('$group')");
how can i update the div in the above . plz help me .m stuck badly luking for solution from 4 days. thanks
Note that in your addhubs function you should only add one & in your url and concatenate everything without spaces in between such as below.
When the ajax call has finished it returns the contents of the page you requested (mfrnds.php) in the html variable. So you can simply select the div you want and enter the html as you can see below. So here we go...:
Your Page
<html>
<body>
<script>
$(document).ready(function() {
setupTabs();
});
function setupTabs() {
// Vertical Sliding Tabs
$('div#st_vertical').slideTabs({
// Options
contentAnim: 'slideH',
contentAnimTime: 600,
contentEasing: 'easeInOutExpo',
orientation: 'vertical',
tabsAnimTime: 300
});
}
function addhubs() {
var group = $('#customhubs').val();
var user = $('#loginuser').val();
$.ajax({
type:"GET",
url: 'mfrnds.php?val=' + group + '&loguser=' + user,
success: function(html) {
//Get div and display the data in there
$('div.st_slide_container).html(html);
//As your slide effect is gone after you updated this HTML, redo your slide effect:
setupTabs();
}
});
}
</script>
<!-- Vertical div -->
<div id="st_vertical" class="st_vertical">
<div class="st_tabs_container">
<div class="st_slide_container">
<ul class="st_tabs">
<?php
$sql = mysql_query("select * from groups");
while($ab = mysql_fetch_assoc($sql)) {
$gp = $ab['group_id'];
$gpName = $ab['group_name']; ?>
<li>
<a href="#stv_content_<?=$gp?>" rel="v_tab_<?=$gp?>" class="st_tab ">
<?php echo $gpName;?>
</a>
</li>
<?php
}
?>
</ul>
</div> <!-- /st_slide_container -->
</div> <!-- /st_tabs_container -->
</div> <!-- /st_vertical -->
</body>
</html>
So in your mfrnds.php you should have a PHP script that uses the val and loguser GET variables and updates the database. After the database has been updated you should return the updated HTML like the following:
*mfrnds.php
<?php
$user = $_GET['loguser'];
$group = $_GET['val'];
$sql = mysql_query("insert into groups (group_name) values ('$group')"); ?>
<ul class="st_tabs">
<?php
$sql = mysql_query("select * from groups");
while($ab = mysql_fetch_assoc($sql)) {
$gp = $ab['group_id'];
$gpName = $ab['group_name']; ?>
<li>
<a href="#stv_content_<?=$gp?>" rel="v_tab_<?=$gp?>" class="st_tab ">
<?php echo $gpName;?>
</a>
</li>
<?php
}
?>
</ul>
Note though that this code is basically meant as an example, I don't know what you want to do exactly in mfrnds.php etc, but I hope this gives you a good idea!
It looks like you are almost there.
In your mfrnds.php file add a line to grab the updated rows
use:
PSEUDOCODE
"SELECT * FROM groups"
for each row in groups
echo "<div> groups.name groups.category </div"
and then in your callback function
success: function(html){
$('.st_tabs').html(html); //replace the html of the sttabs div with the html echoed out from mfrnds.php
}