I'm trying to create a collapsible div for each order in a customers account. The code works fine without the jquery.
But when I use jquery, and try to expand the div, there's nothing in there, it's just blank.
Here's the the PHP:
<div class="container">
<h1> My Orders </h1>
<?php
$user_id = $_SESSION['user_session'];
$stmtGetOrderNumber = $DB_con->prepare("SELECT DISTINCT order_id FROM orders WHERE user_id = :user_id");
$stmtGetOrderNumber->bindparam(":user_id",$user_id);
$stmtGetOrderNumber->execute();
$orderids=$stmtGetOrderNumber->fetchAll(PDO::FETCH_ASSOC);
$stmtGetOrderItems = $DB_con->prepare("SELECT * FROM orders as o
INNER JOIN products as p ON p.product_id=o.product_id
INNER JOIN users as u ON u.user_id=o.user_id
WHERE order_id = :this_order_id
ORDER BY order_date_added DESC");
$stmtGetOrderItems->bindparam(":this_order_id", $id['order_id']);
$stmtGetOrderItems->execute();
$orders=$stmtGetOrderItems->fetchAll(PDO::FETCH_ASSOC);
foreach($orderids as $id)
{
$nameshown = false;
$emailshown = false;
$dateshown = false;
echo '<div class="list-group" style="padding-bottom:1%;">';
echo '<h1 class="list-group-item active">Order ID: ',$id['order_id'],'</h1>';
echo '<div class="header"> <span>Expand</span> </div>';
echo '<div class="content">';
foreach($orders as $order)
{
echo'<p>',$order['product_name'],'</p>';
echo'<p>£',$order['product_price'],'</p>';
echo'<img id="img" class="img-fluid" src="images/',$order['product_image'],'" style="height:100px;width:100px;">';
echo'<hr>';
}
echo'</div></div>';
}
?>
</div>
And the jQuery:
$(".header").click(function () {
$header = $(this);
//getting the next element
$content = $header.next();
//open up the content needed - toggle the slide- if visible, slide up, if not slidedown.
$content.slideToggle(500, function () {
//execute this after slideToggle is done
//change text of header based on visibility of content div
$header.text(function () {
//change text based on condition
return $content.is(":visible") ? "Collapse" : "Expand";
});
});
});
And the styles for the div's (Not sure if this is necessary):
.container {width:100%;}
.container div {width:100%;}
.container .header {background-color:#d3d3d3;padding: 2px;cursor: pointer;font-weight: bold;}
.container .content{display: none;padding : 5px;}
Related
I have 2 lists, one for companies and one for sites. Each company has different sites around the country. I am am displaying 2 lists side by side on a modal popup. I have the companies list displaying dynamically from a query all ok, I want the second list to populate with the sites, depending on the company selection from the first list.
image of both lists side by side as I have it
The html element is as follows:
<div class="row">
<div class="col-md-6">
<div class="container-fluid">
<div style="height: 400px; overflow-y: scroll">
<div class="list-group" name="companies" id="company">
<!--Call the Showcompany() method from the select.class.php-->
<?php echo $opt->ShowCompany(); ?>
</div>
</div><!--End of first input group-->
</div><!--End of container-->
</div><!--End of column-->
<div class="col-md-6">
<div class="container-fluid">
<div style="height: 400px; overflow-y: scroll">
<div class="list-group" multiple onchange="changeSelection(this.value)" name="sites" id="sites">
<?php echo $opt->ShowSite(); ?>
</div>
</div><!--End of first input group-->
</div><!--End of container-->
</div><!--End of column-->
</div>
This is being populated from a separate included php file as follows:
//function to handle db connectivity
protected function DbConnect()
{
include "db_config.php";
$this->conn = mysql_connect($host,$user,$password) OR die("Unable to connect to the database");
mysql_select_db($db,$this->conn) OR die("can not select the database $db");
return TRUE;
}
//function to query the companies and return list for companies list
public function ShowCompany()
{
$sql = "SELECT company.company_name, company.id FROM company ORDER BY company.company_name ASC";
$res = mysql_query($sql,$this->conn);
$company = '<a class="list-group-item active" value="0">choose...</a>';
while($row = mysql_fetch_array($res))
{
$company .= '<a class="list-group-item" value="' . $row['id'] . '">' . $row['company_name'] . '</a>';
}
return $company;
}
//function to query the sites and return list for sites list
public function ShowSite()
{
$sql = "SELECT * FROM sites WHERE company_id=$_POST[id]";
$res = mysql_query($sql,$this->conn);
$site = '<a class="list-group-item" value="0">Select All</a>';
while($row = mysql_fetch_array($res))
{
$site .= '<a class="list-group-item" value="' . $row['id'] . '">' . $row['site_name'] . '</a>';
}
return $site;
}
The jquery I am using to try and populate the second list is as follows this is in my document.ready function.
$("#company").change(function(){
var id = $("#company a:selected").attr('value');
$.post("select_site.php", {id:id}, function(data){
$("#sites").html(data);
});
});
I have had this working when I used select dropdowns and instead of anchor tags I had option tags and it all worked, but it never looked right for what I needed so I decided to make the 2 list views.
The jQuery I had when it worked for my select and option tags was as follows:
$("select#company").change(function(){
var id = $("select#company option:selected").attr('value');
$.post("select_site.php", {id:id}, function(data){
$("select#sites").html(data);
});
});
I won't lie, jQuery is not my biggest strength and I can't for the life of me work out why it won't populate the second list. absolutely any help would be really really appreciated as I have spent the last 3 days trying to figure this out. Thank you.
I'm trying to learn php, mysql and javascript/jquery by building a live bidding system. I want to refresh the value of a bid button and dropdown automatically, but only if the value has changed. I've made a bidbuttons.php that outputs the buttons after querying the db for the current values, and I load and reload the page with this jquery I found elsewhere. I have tried several different methods of refreshing the div, and the best I came up with unfortunately closed the dropdown on the timer. This current version was described as exactly what I need but doesn't seem to work, in fact it logs me out. would prefer the div to refresh and the dropdown to close ONLY if the bidbuttons.php is updated. This is my first post, I hope I did this right.
<div id="bidbuttons"></div>
<script type="text/javascript">
var loadUrl = "includes/bidbuttons.php?id='.$item->id.'";
$("#bidbuttons").load(loadUrl).fadeIn("slow");
var auto_refresh = setInterval(function () {
$.get(loadUrl, function(data) {
if (data.changed) {
$("#bidbuttons").load(loadUrl).fadeIn("slow");
}
});
}, 10000);
</script>
and my bidbuttons.php
<?php
include_once 'db_connect.php';
include_once 'functions.php';
sec_session_start();
if (login_check($mysqli) == true) {
$getid = (int)$_GET['id'];
// get current price
$result = $mysqli->query("SELECT ammount, bidder_id FROM bids WHERE ammount=(SELECT MAX(ammount)) && item_id like $getid order by ammount desc");
while($row = $result->fetch_assoc()) {
$bidder_id = $row["bidder_id"];
$current = $row['ammount'];
echo ($mysqli->error);
$result->free();
}
//get item info
$results = $mysqli->query("SELECT * FROM items WHERE id like $getid ");
while($row = $results->fetch_assoc()) {
if (empty ($current)) { $current = $row["start"];}
$title = $row["title"];
$item->thenext = ($current + $row["raise"]);
$buyout = $row["buyout"];
$raise = $row["raise"];
$sold = $row["sold"];
}
$results->free();
echo ('<div id="buttons">
<a class="btn btn-primary btn-lg" style="margin-bottom: 10px; margin-top: 10px; width: 80%;" href="includes\placebid.php?itemid=' . $getid . '&ammount=' . $item->thenext .'">Bid $' . $item->thenext . '</a>
');
if ($buyout){echo ('
<a class="btn btn-success btn-lg" style="margin-bottom: 10px; width: 80%;" href="includes\placebid.php?itemid='.$getid.'&ammount='.$buyout.'">Buyout $'.$buyout.'</a>
');}
echo '</div><!-- buttons -->';
echo ('
<div class="dropdown">
<button style="margin-bottom: 10px; width: 80%;" type="button" class="btn btn-info btn-lg dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Custom Bid<span class="caret"></span></button>
<ul class="dropdown-menu">
');
// build the custom bid dropdown
if (!$buyout) { $maxcust = $item->thenext*25;
for ($cust = $item->thenext; $cust <= $maxcust; $cust = $cust + $raise) {
echo ('<li>' .$cust. '</li>');
}
}
if ($buyout) {
for ($cust = $item->thenext; $cust <= $buyout; $cust = $cust + $raise) {
echo ('<li>' .$cust. '</li>');
}
}
echo ('
</ul>
</div><!-- dropdown -->
');
}
mysqli_close($mysqli);
?>
I think the problem may be in that your PHP file is generating HTML which is continually replacing elements on your page due to them being loaded via AJAX.
Just an idea but you could make your PHP output a JSON instead that contains the database results, then have jQuery read the output. Your code would then process that JSON file and create or update the HTML elements accordingly (rather than replace them).
This way you have more fine grained control in the JavaScript for when your dropdown should close.
See this answer if you'd like to output from MySQLi to JSON.
Hi guys i need some help i have these code i need to show content by id
after clik to show content i need to show content by the same id
<script type="text/javascript">
function toggleAndChangeText() {
$('#divToToggle').toggle();
if ($('#divToToggle').css('display') == 'none') {
$('#aTag').html('Collapsed text mode ►');
}
else {
$('#aTag').html('Expanded text mode ▼');
}
}
</script>
<style>
#divToToggle{display:none;}
</style>
and this code php/html
<?php
$stmt = $DB_con->prepare("SELECT * FROM `topic` ORDER BY id");
$stmt->execute();
foreach ($stmt->fetchAll() as $row) {
echo"
<div class='Post'>
<div class='rgt Pimg'><a href='post.php?id=".$row['id']."'><img src='".$row['e_title']."' class='Pimg'/></a></div>
<div>
<a id='aTag' href='javascript:toggleAndChangeText()'>
Show Content
</a>
<div id='divToToggle'>".$row['e_content']."</div>
</div>
";
}
?>
You cannot use same ID's for multiple elements. Use class instead:
Change your script to :
$(document).ready(function(){
$("a.aTag").on("click", function(){
var toggleElement = $(this).closest("div").find(".divToToggle");
toggleElement.toggle();
if (toggleElement.css('display') == 'none') {
$(this).html('Collapsed text mode ►');
}
else {
$(this).html('Expanded text mode ▼');
}
});
});
And your PHP code to this:
<?php
$stmt = $DB_con->prepare("SELECT * FROM `topic` ORDER BY id");
$stmt->execute();
foreach ($stmt->fetchAll() as $row) {
echo"
<div class='Post'>
<div class='rgt Pimg'><a href='post.php?id=".$row['id']."'><img src='".$row['e_title']."' class='Pimg'/></a></div>
<div>
<a class='aTag' href='javascript:toggleAndChangeText()'>
Show Content
</a>
<div class='divToToggle'>".$row['e_content']."</div>
</div>
";
}
?>
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++;
}
?>
I have a PHP script to selected records for comments from a database, and then print them onto the page. What I'd like to happen is that if a user is on a page, and another user comments on an item on said page, it automatically appends the new comment to the bottom. The problem I'm having is that I don't know how to differentiate between all of the statuses.
My code for generating the comments on a status is:
<?php
$rt = ("SELECT * FROM (SELECT comment as comment, byuid as byuid, comuid as comuid, likes as likes, dislikes as dislikes, UNIX_TIMESTAMP(timestamp) as timestamp FROM mingle_comments WHERE onuid = '$sid' AND type = 'status' ORDER BY timestamp DESC LIMIT 2) mingle_comments ORDER BY timestamp ASC"); //query
$result = mysql_query($rt) or die (mysql_error());
if(mysql_num_rows($result) >= 2) {
?>
<div id="sa" style="background:#E0E0E0; padding:5px 5px 5px 5px;">
View all comments...
</div>
<?php
}
while($st = mysql_fetch_assoc($result)) {
$comment = nl2br($st['comment']);
$by = $st['byuid'];
$comuid = $st['comuid'];
$time = $st['timestamp'];
$l = $st['likes'];
$d = $st['dislikes'];
$bq = "SELECT * FROM users WHERE uid = '$by' LIMIT 1";
$bqq = mysql_query($bq) or die (mysql_error());
while($bqr = mysql_fetch_assoc($bqq)) {
$dp = $bqr['dp'];
$fbq = $bqr['fname'];
$sbq = $bqr['sname'];
}
?>
<div id="commentbox" class="<?php echo $comuid; ?>" style="padding:5px 5px 5px 5px;">
<div id="cbi" style=" display:inline; position:relative; ">
<img src="<?php if ($dp == null) { echo 'img/unknown_user.jpg'; } else { echo "pf/" . $by . "/" . $dp; } ?>" width="36px" style=" display:inline; position:relative;"/>
</div>
<div id="cbt" style="position:relative; margin-left:32px; margin-top:-35px;">
<?php echo $fbq . " " . $sbq; ?>
<p class="<?php echo $comuid; ?>" style="position:relative; margin-left:5px;"><?php echo $comment; ?></p>
</div>
<div id="clb" style="background:#E0E0E0; padding-left:5px;">
Like<?php echo time_since($time); ?>
</div>
</div>
<?php
}
?>
TL:DR; How can I automatically fetch new comments and append them to the comments generated in the above script without page refresh.
JQUERY
$(document).ready(function(){
var lastcheck='';
setInterval(function() {
$.ajax({
url: 'URL_TO_PHP_SCRIPT',
type: 'POST',
data: {'lastcheck':lastcheck},
success: function(result){
if (result!='nothing_new'){
lastcheck=result.lastcheck /*Update lastcheck*/
var data=result.data;
$.each(data, function(i,val){
//Foreach comment you do what you need, like append, prepend, etc. data[i]."key" to get the value.
});
}
}
});
}, 15000 /* This will check each 15 seconds, you can change it */);
});
PHP SIDE
$lastcheck=$_POST['lastcheck'];
/*
You should add a date field to each new created comment,then filter by "orderby date > $lastcheck" so you get comments since your last check
You get the new comments here
...
...
..
*/
if (!empty($arrayofnewcomments)){
/*The output*/
echo json_encode(array('lastcheck'=>date('Y-m-d H:i:s'),'data'=>$arrayofnewcomments));
}else{/*No new comments*/
echo 'nothing_new';
}
This is some code I came up with, it's a general Idea but it works. It will check each 15 seconds for new comments.