utilize PHP variable in javascript - php

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>

Related

Jquery load() get a variable from another page

On my main page I have a content box where I load the content using Jquery's load() from another page. All is working fine and it's quick and nice.
Next thing I want to do is to add a small filtering feature to it. The variable is sent to the main page (snappage.php) as a GET variable. However the php for the sql query is in another page (i.e all-snaps.php). Let me show you my code:
snappage.php
<?php
require "database/database.php";
session_start();
if($_GET['country']) {
$country = $_GET['country'];
}
?>
<section class="main-snap-page-wrapper">
<nav class="all-snaps-countries">
<h4>Filter by country</h4>
<ul>
<?php
//GET COUNTRY FLAGS
$flagsql = mysql_query("SELECT * FROM countries");
while($getflag = mysql_fetch_array($flagsql)) {
$countryname = $getflag['countryname'];
$flag = $getflag['countryflag']; ?>
<li>
<a href="snappage.php?country=<?php echo $countryname?>">
<img src="<?php echo $flag?>" alt="">
<h5><?php echo $countryname?></h5>
</a>
</li>
<?php } ?>
</ul>
</nav>
<div class="all-snaps-page">
<nav class="main-page-tabs-wrapper">
<ul class="main-page-tabs" id="<?php echo $country?>">
<li class="active-tab">All</li>
<li>Female</li>
<li>Male</li>
</ul>
<div class="main-snaps-content"></div>
</nav>
</div>
</section>
<script type="text/javascript">
$('.main-snaps-content').load('all-snaps.php');
$('.main-page-tabs li').on('click', function () {
$('.main-page-tabs li').removeClass('active-tab');
$(this).addClass('active-tab');
var page = $(this).find('a').attr('href');
$('.main-snaps-content').load(page + '.php');
return false;
});
</script>
Next is the page which I load into .main-snaps-content from i.e all-snaps.php:
all-snaps.php
<?php
require "database/database.php";
session_start();
if($_GET['country']) {
$country = $_GET['country'];
$newsql = mysql_query("SELECT * FROM users JOIN fashionsnaps ON users.id = fashionsnaps.userid WHERE country = '$country' ORDER BY snapid ASC");
}
else {
$newsql = mysql_query("SELECT * FROM fashionsnaps ORDER BY snapid ASC");
}
?>
<ul class="snaps-display">
<?php
//GET SNAPS BY ID
while ($getnew = mysql_fetch_array($newsql)) {
$newsnappics = $getnew['snappic'];
$newsnapid = $getnew['snapid'];
?>
<li>
<a href="snap.php?id=<?php echo $newsnapid?>">
<img src="<?php echo $newsnappics?>" alt="">
</a>
</li>
<?php } ?>
</ul>
So what I want to achieve here is to load the filtered content from all-snaps.php into the .main-snaps-content which is on snappage.php.
Where should I send this $country variable? On which page should I retrieve it?
You can do this pretty easily with jQuery load.
In snappage.php:
$(".main-snaps-content").load("all-snaps.php?" + $.param({country: "<?php echo htmlentities($country); ?>"}));
Update:
You'll need better handling of the PHP GET/$country var. You can initialize it at the top of snappage.php like this:
$country = (isset($_GET['country'])) ? $_GET['country'] : '';
Then, your JS will need a conditional:
var country = "<?php echo htmlentities($country); ?>";
if (country) {
$(".main-snaps-content").load("all-snaps.php?" + $.param({country: country}));
} else {
$(".main-snaps-content").load("all-snaps.php");
}

set background color for body depending on if/else statement

I don't know if this is possible but I want to know if I can set the background color of a page depending on an if/else statement?
What I want is that if the if statement is met, then I want the background color of the body to be white, if the else statement is met where it contains a div, then I want the background color of the body to be grey.
Can this be done?
<?php
if (page()){
//all the code in the page
}else{
?>
<div class="boxed">
</div>
<?php
}
?>
UPDATE:
<?php
if (page()){
?>
<body class="bodypage <?php echo page()? "color1":"color2" ?>" >
</body>
<?php
}else{
<div class="boxed">
Continue with Current Assessment
</div>
}
?>
Yes it can be. How about you use a predefined class that have the background color you need:
.color1 {
background-color:red;
}
.color2 {
background-color:yellow;
}
<body class="boxed <?php echo page()? "color1":"color2" ?>" >
</body>
UPDATE:
<body class="bodypage <?php echo page()? "color1":"color2" ?>" >
<?php if (page()){?>
... all the page code
<?php else {?>
<div class="boxed">
Continue with Current Assessment
</div>
?>
A zillion ways to do this.
PHP:
$bodyClass = $condition ? 'foo' : 'bar';
...
echo <<< END_HTML
<body class="$bodyClass">
<!-- stuff here -->
</body>
END_HTML;
CSS:
body.foo { background-color:#fff; }
body.bar { background-color:#888; }
..is one way to do it.
Cheers
Try this
<body <?php if(true) {echo('style="background:red"'); } else { echo('style="background:white"'); } ?> >
</body>
You can do it this way using javascript & jQuery:
<script>
$(document).ready(function(condition){
if (cond) {
$(body).css("background-color","red");
} else {
$(body).css("background-color","blue");
}
});
</script>
Or in php you can just echo that code, with some changes.
Try to minimize the php influence on your design. (CSS for design, html for semantics, php for structure and javascript for interaction)
To accomplish this I recommend sending a hidden input to the browser containing a value:
if(statement) {
$color = '#ffffff';
} else {
$color = '#ff0000';
}
echo '<input id="pageColor" type="hidden" value="'.$color.'" />';
Now do the following with (for example) jquery:
$(document).ready(function() {
//change bg color based on input value
$('body').css('background-color', $('#pageColor').val());
});
Yep, you can do this.
One of the most elegant ways:
PHP part:
<?php
$style = 'background:'; # property
$given = page() ? 'red;' : 'black;'; # Ternary operator
$style .= $given; # Concatenate two strings
?>
HTML part:
<div class="boxed" style='<?php echo $style; ?>'></div>
Also you can create special CSS classes with predefined variety of CSS properties:
PHP part:
<?php
$class = page() ? 'first' : 'second'; # CSS classes defined in your stylesheet.
?>
HTML part:
<div class="boxed <?php echo $class;?>"></div>
And here you go. That's just a quick demonstration, you can replace this with you parameters.

How to dynamically display MySQL data using jQuery and PHP?

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++;
}
?>

PHP While Loop and jQuery

I have created a while loop that selects random images from from my server and posts it. Now I want to add some jquery code and allow me to click on one of the images and run the slideUp() function in jQuery. Here is my problem. I can click on the first image produced in the while loop but when I click on the second image nothing happens. The slideUp() function does not work. I don't know what to do. Here is the code below.
<script src="http://code.jquery.com/jquery-latest.js"></script>
<?php
$num_dresses = dress_count ();
$i=0;
while ($i < 2){
?>
<style>
div:hover { border:2px solid #021a40; cursor:pointer;}
</style>
<script>
$("div").click(function () {
$(this).slideUp();
});
</script>
<?php
$rand_id = rand(1, $num_dresses);
$dress_feed_data = clothing_data($rand_id, 'file_name', 'user_defined_name', 'user_defined_place' , 'user_who_uploaded', 'match_1');
$new_file_name = $dress_feed_data['file_name'];
if (file_exists('fashion_images/' . $new_file_name)){
echo str_replace("|", " ", $dress_feed_data['user_defined_name']);
?>
<br>
<div>
<img src=" fashion_images/<?php echo $new_file_name;?> " width="50" height="50" />
<div>
<br><br>
<?php
echo str_replace("|", " ", $dress_feed_data['user_defined_place']);
?>
<br><br>
<?php
}
$i++;
}
?>
You are binding the click handler to the elements before the elemnts are inserted into DOM,
Probably when the first call is made no elements called div are there so the binding goes to void, then the first element gets inserted.
Now the binding for second element is made, now it gets attached to first one as it matches $('div') . So you got only forst one working.
The clean way is to take the click binding out of while loop, so that it happens only once, and call it on DOM ready event
<script>
$(document).ready(function(){
$("div").click(function(){
$(this).slideUp();
});
});
</script>
And if you want to make a live binding, which applies to all dynamically added images as well use delegation:
<script>
$(document).ready(function(){
$('body').on('click',"div",function(){
$(this).slideUp();
});
});
</script>
If you are posting the above images with html to a host/parent page, just add the above delegation logic to parent page, and post only the images.
Try this :
<style>
div:hover { margin:10px 0; border:2px solid #021a40; cursor:pointer;}
</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(function(){
$("div.randomImage").click(function() {
$(this).slideUp();
});
});
</script>
<?php
$num_dresses = dress_count();
$i=0;
while ($i < 2) {
?>
<?php
$rand_id = rand(1, $num_dresses);
$dress_feed_data = clothing_data($rand_id, 'file_name', 'user_defined_name', 'user_defined_place' , 'user_who_uploaded', 'match_1');
$new_file_name = $dress_feed_data['file_name'];
if (file_exists('fashion_images/' . $new_file_name)) {
echo str_replace("|", " ", $dress_feed_data['user_defined_name']);
?>
<div class="randomImage">
<img src="fashion_images/<?php echo $new_file_name;?>" width="50" height="50" />
</div>
<?php
echo str_replace("|", " ", $dress_feed_data['user_defined_place']);
}
$i++;
}
?>
Notes:
Stylesheet and script moved outside the php while loop. Repetition is unnecessary and undesired.
jQuery statement now inside a $(function(){...}) structure to ensure it runs when the ducument is ready, ie. after the served HTML has been interpreted by the browser to create DOM elements.
class="randomImage" added to the <div>
Second <div> changed to </div>
For readability of source and served page, the PHP and HTML are indented independently.
I've not tried to verify the PHP.

change the content of div after submitting data to mysql

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
}

Categories