Hiding a button when maximum is reached: Jquery - php

I have the following button that is used to View More Friends in increments of 16:
<button class="cancel auto-btn hide-btn" id="viewAllFriends" style="display: visible;">View All Friends</button>
It's initial display is given with this:
var username = '<?php echo $username; ?>';
var num_friends = '<?php echo $num_friends; ?>';
var counter = 8;
$(document).ready(function(){
<?php if ($num_friends > 8): ?>
$("viewAllFriends").attr('style', 'display: visible;');
$("#viewAllFriends").click(function(){
counter = counter+16;
$.ajax({
url:'includes/handlers/ajax_load_profile_friends.php',
type:'POST',
data:{'username':username, 'num_friends':num_friends, 'counter':counter},
success: function(data) {
$('#data_friends').html(data);
}
});
});
<?php else: ?>
$("#viewAllFriends").attr('style', 'display: none;');
<?php endif; ?>
});
The button displays if a user has more than 8 friends or does not if there is less than 8. When ajax_load_profile_friends.php gets to the end, I have a hidden tag that echos on the page.
$max = "<p id='max' hidden>$num_rows</p>";
echo "$max";
The html output looks like this: <p id="max" hidden="">43</p>
This hidden tag doesn't appear on the page until the last query. What I'm trying to do, is when 43 appears (which in this example indicates that there are no more friends to load) is remove the View More friends button from view.
This is what I've tried:
var friend_count = '<?php echo $num_friends; ?>';
var max = ("max").text();
if (max = friend_count) {
$("#viewAllFriends").remove();
}
Sadly this isn't working - the button remains. Everything else works fine, but this final detail. I'm not so great at jQuery, so I'm wondering if the ajax is overriding this script, or if I'm possibly not getting the data in var max? Any help, links, examples would be appreciated.

I can try
$('#viewAllFriends').hide();
http://api.jquery.com/hide/
instead
$("#viewAllFriends").remove();

The solution could be like this.
First update ajax_load_profile_friends.php
$max = "<input id='max' type='hidden' value='".$num_rows."'>";
echo "$max";
Then in your script
var friend_count = '<?php echo $num_friends; ?>';
var max = $("#max").val();
if (max >= friend_count) {
$("#viewAllFriends").hide();
}

Related

In PHP, session variable is not storing the value. What is wrong?

The following is a sample PHP code. I am expecting the session variable 't' to increment its value when update function is called. However, when I run the code I keep getting the output as Value: 1. What should I do so that the value is stored into the session variable?
<?php
session_start();
if(!isset($_SESSION['t'])) {
$_SESSION['t'] = 0;
}
?>
<div id="test" class="test"></div>
<script src="http://code.jquery.com/jquery.js"></script>
<script>
function update() {
var ct = "<?php echo $_SESSION['t'] += 1 ?>";
<?php echo "Value: " . $_SESSION['t']; ?>;
$("#test").html(ct);
}
$(document).ready(function() {
setInterval('update()', 1000);
});
</script>
Put session_start() at the very top of your script, before any output
<?php
session_start();
// if you automatically set SESSION['t'] to 0 when the page loads, it will never increment
// check if the SESSION exists, and if it doesn't, then we create it
if(!isset($_SESSION['t'])) {
$_SESSION['t'] = 0;
}
?>
<div id="test" class="test"></div>
<!-- it's recommended to load scripts at the end of the page -->
<script src="http://code.jquery.com/jquery.js"></script>
<script>
function update() {
// you had some formatting issues in here...
// shortcut: using +=1 will take the current value of $_SESSION['t'] and add 1
var ct = "<?php echo $_SESSION['t'] += 1 ?>";
<?php echo "Value: " . $_SESSION['t']; ?>;
$("#test").html(ct);
}
$(document).ready(function() {
setInterval('update()', 1000);
});
</script>
UPDATE:
This is an example that will do what I think you're looking for. It will display the value of $_SESSION['t'] when the page is loaded, and then increment the value of $_SESSION['t'] every time the update button is clicked. There is no error checking, this is just a very simple example to show you how this works.
<?php
session_start();
if(!isset($_SESSION['t'])) {
$_SESSION['t'] = 0;
}
?>
<div id="test" class="test"></div>
<button type="button" id="update">Update</button>
<script src="http://code.jquery.com/jquery.js"></script>
<script>
$(document).ready(function() {
// create the ct varaible
var ct = <?php echo $_SESSION['t']; ?>;
// display the value in the #test div
$("#test").text(ct);
// when the update button is clicked, we call ajax.php
$("#update").click(function(){
$.post("ajax.php", function(response){
// display the returned value from ajax.php
$("#test").text(response);
});
});
});
</script>
ajax.php
<?php
session_start();
// increment the session by 1
$_SESSION['t'] += 1;
// return the result
echo $_SESSION['t'];

when i add new comment the delete button doesn't work till i reload the page?

first page
ajax and jquery code
<script>
$(document).ready(function(){
$(".delete_buttom").click(function(){
var x = $(this).attr('id');
click_delete(x);
});
function click_delete(commentId){
$.post("ajax_comments3.php",
{
task : "this is the task",
commentId : commentId
}).success(
function(data){
$('#comment_' + commentId).remove();
}).error(function(){
alert("404 not found");
});
}
</script>
======================================================================
second page code
<?php
if(isset($_POST['task']) && $_POST['task'] == "this is the task"){
$server_id = $_POST['ajax_id'];
$server_comment = $_POST['ajax_text'];
$user_name = $_POST['ajax_uname'];
$connection = mysqli_connect("localhost","root","","comments")
$insert_query = "insert into comment (commet_text,user_id)
values ('$server_comment','$server_id')";
$excute_insert = mysqli_query($connection,$insert_query) or die("insert query error");
?>
this the the li tage which will insert into ul tage (i have a ul tage in html code)
<li class="li_style" id="comment_<?php echo mysqli_insert_id($connection) ?>">
<img src="profile.jpg" class="user_img_src" />
<h5 class="username"><?php echo $user_name ; ?></h5>
<div class="delete_buttom" id="comment_<?php echo mysqli_insert_id($connection) ?>">X</div>
<div class="user_comment"><?php echo $server_comment ; ?> </div>
</li>
<?php
}
?>
when i type a new comment it inserted into database and appear in the web browser as well but the problem is that i have a delete button when i clicked on it right after typing comment it doesn't work i have to reload the page the the delete button works fine any solutions.
Correct. That is because theres no event on that new button.
Maybe like this:
var deleteButton = function() {
$(".delete_buttom").off('click');
$(".delete_buttom").on('click', function() {
var x = $(this).attr('id');
click_delete(x);
});
}
Now, in your success (after you added the new entry):
success(function(data) {
// add your entry...
deleteButton();
});

Turn Regular Javascript Into jQuery

I have some code that involves clicking on a button and either you are logged in and you go to the next page or you are logged out and you get an alert. I have never liked onClick inside HTML and so I would like to turn this around into clicking on the id and having the jQuery do its magic.
I understand the click function of jQuery, but I don't know how to put do_bid(".$val["id"]."); down with the rest of the Javascript. If I haven't given enough information or if there is an official resource for this then let me know.
<li class='btn bid' onclick='do_bid(".$val["id"].");'> Bid </li>
<script>
//Some other Javascript above this
function do_bid(aid)
{
var loged_in = "<?= $_SESSION["BPLowbidAuction_LOGGED_IN"] ?>";
if(loged_in=="")
{
alert('You must log in to bid!');
}
else
{
document.location.href="item.php?id="+aid;
}
}
</script>
UPDATE: This is the entirety of the Javascript code. I think none of the answers have worked so far because the answers don't fit the rest of my Javascript. I hope this helps
<script language="JavaScript">
$(document).ready(function(){
function calcage(secs, num1, num2) {
s = ((Math.floor(secs/num1))%num2).toString();
if (LeadingZero && s.length < 2)
s = "0" + s;
return "" + s + "";
}
function CountBack() {
<?
for($i=0; $i<$total_elements; $i++){
echo "myTimeArray[".$i."] = myTimeArray[".$i."] + CountStepper;";
}
for($i=0; $i<$total_elements; $i++){
echo "secs = myTimeArray[".$i."];";
echo "DisplayStr = DisplayFormat.replace(/%%D%%/g, calcage(secs,86400,1000000));";
echo "DisplayStr = DisplayStr.replace(/%%H%%/g, calcage(secs,3600,24));";
echo "DisplayStr = DisplayStr.replace(/%%M%%/g, calcage(secs,60,60));";
echo "DisplayStr = DisplayStr.replace(/%%S%%/g, calcage(secs,1,60));";
echo "if(secs < 0){
if(document.getElementById('el_type_".$i."').value == '1'){
document.getElementById('el_".$i."').innerHTML = FinishMessage1;
}else{
document.getElementById('el_".$i."').innerHTML = FinishMessage2;";
echo " }";
echo "}else{";
echo " document.getElementById('el_".$i."').innerHTML = DisplayStr;";
echo "}";
}
?>
if (CountActive) setTimeout("CountBack()", SetTimeOutPeriod);
}
function putspan(backcolor, forecolor, id) {
document.write("<span id='"+ id +"' style='background-color:" + backcolor + "; color:" + forecolor + "'></span>");
}
if (typeof(BackColor)=="undefined") BackColor = "white";
if (typeof(ForeColor)=="undefined") ForeColor= "black";
if (typeof(TargetDate)=="undefined") TargetDate = "12/31/2020 5:00 AM";
if (typeof(DisplayFormat)=="undefined") DisplayFormat = "%%D%%d, %%H%%h, %%M%%m, %%S%%s.";
if (typeof(CountActive)=="undefined") CountActive = true;
if (typeof(FinishMessage)=="undefined") FinishMessage = "";
if (typeof(CountStepper)!="number") CountStepper = -1;
if (typeof(LeadingZero)=="undefined") LeadingZero = true;
CountStepper = Math.ceil(CountStepper);
if (CountStepper == 0) CountActive = false;
var SetTimeOutPeriod = (Math.abs(CountStepper)-1)*1000 + 990;
var myTimeArray = new Array();
<? for($i=0; $i<$total_elements; $i++){?>
ddiff=document.getElementById('el_sec_'+<?=$i;?>).value;
myTimeArray[<?=$i;?>]=Number(ddiff);
<? } ?>
CountBack();
function do_bid(aid)
{
var loged_in = "<?= $_SESSION["BPLowbidAuction_LOGGED_IN"] ?>";
if(loged_in=="")
{
alert('You must log in to bid!');
}
else
{
document.location.href="item.php?id="+aid;
}
}
}</script>
If you want to attach click event handler using jQuery. You need to first include jQuery library into your page and then try the below code.
You should not have 2 class attributes in an element. Move both btn and bid class into one class attribute.
Markup change. Here I am rendering the session variable into a data attribute to be used later inside the click event handler using jQuery data method.
PHP/HTML:
echo "<li class='btn bid' data-bid='".$val["id"]."'>Bid</li>";
JS:
$('.btn.bid').click(function(){
do_bid($(this).data('bid'));
});
If you don't want to use data attribute and render the id into a JS variable then you can use the below code.
var loged_in = "<?= $_SESSION["BPLowbidAuction_LOGGED_IN"] ?>";
$('.btn.bid').click(function(){
if(!loged_in){
alert('You must log in to bid!');
}
else{
do_bid(loged_in);
}
});
First, you need to make the <li> have the data you need to send, which I would recommend using the data attributes. For example:
echo "<li class=\"btn bid\" data-bid=\"{$val['id']}\">Bid</li>";
Next, you need to bind the click and have it call the javascript method do_bid which can be done using:
function do_bid(bid){
//bid code
}
$(function(){
// when you click on the LI
$('li.btn.bid').click(function(){
// grab the ID we're bidding on
var bid = $(this).data('bid');
// then call the function with the parameter
window.do_bid(bid);
});
});
Assuming that you have multiple of these buttons, you could use the data attribute to store the ID:
<li class='btn' class='bid' data-id='<?php echo $val["id"]; ?>'>
jQuery:
var clicked_id = $(this).data('id'); // assuming this is the element that is clicked on
I would add the id value your trying to append as a data attribute:
Something like:
<li class='btn' class='bid' data-id='.$val["id"].'>
Then bind the event like this:
$('.bid').click(function(){
var dataId = $(this).attr('data-id');
doBid(dataId);
});
You can store the Id in a data- attribute, then use jQuery's .click method.
<li class='btn' class='bid' data-id='".$val["id"]."'>
Bid
</li>
<script>
$(document).ready(function(){
$("li.bid").click(function(){
if ("" === "<?= $_SESSION["BPLowbidAuction_LOGGED_IN"] ?>") {
alert('You must log in to bid!');
}
else {
document.location.href="item.php?id=" + $(this).data("id");
}
});
});
</script>
If you are still searching for an answer to this, I put a workaround.
If data is not working for you, try the html id.
A working example is here: http://jsfiddle.net/aVLk9/

Tracking and Manipualting the contents via Jquery Ajax on database update

I am querying the database to retrieve contents via Jquery Ajax, and by using SetInterval function it queries the database for new contents every 1 min.
My question is How can i keep track of New contents ? For ex: If database has new contents, I want to Add highlight Class to it. How can that be done ?
the Jquery code for Retrieving contents
$(document).ready(hot_listings());
setInterval( "hot_listings();", 10000 );
var ajax_load = "<img class='loading' src='images/indicator.gif' alt='loading...' />";
function hot_listings() {
$.ajax({
url: "hot_listing.php",
cache: false,
success: function(msg) {
$("#hot_properties").html(msg);
}
});
}
Well, i am including the Php too ..
<?php
include("includes/initialize.php");
// hot properties, featured
$per_page = 3;
global $database;
$listings = Listings::hot_listings();
//while ($listing = $database->fetch_array($listings)) {
foreach ($listings as $listing ) {
$listing_id = $listing->listing_id; //initialize listing_id to fetch datas from other table
$photo = Photos::find_by_id($listing_id); //initialize table photo
$comment = Comments::find_by_id($listing_id);
$comment_count = Comments::count_by_id($listing_id);
$photo_count = Photos::count_by_id($listing_id);
//echo $listing['listing_id'];
?>
<li><span class="imageholder">
<img class="listingimageSmall" src="<?php if (!empty($photo->name)) { echo 'uploads/thumbs/'.$photo->name; } else { echo 'images/no-thumb-100.jpg'; } ?>" width="66" height="66" >
</span>
<h3><?php echo ucfirst($listing->title) . ' in ' . ucfirst($listing->city) ; ?></h3>
<p class="description">
<span class="price">Rs <?php echo $listing->price; ?></span>
<span class="media"> <img src="images/icon_img.jpg" alt="Images" width="13" height="12" /> <?php echo $photo_count;?> Images <img src="images/comments.png" alt="Images" width="13" height="12" /> <?php echo $comment_count; ?> comments </span>
</p>
<div class="clear"> </div>
</li>
<?php } // end of foreach
?>
Answer
I recommend that you change your PHP part to emit JSON data about listings.
This can be accomplished through the use of the PHP function json_encode(). You can read more about json_encode() at http://php.net/manual/en/function.json-encode.php.
Then on the client you'll be able to do this:
$.ajax({
url: "hot_listing.php",
cache: false,
success: function(data) {
last_received_listings = data;
build_html_in('#hot_properties', data);
}
});
In an ajax callback you memorize data that you just received and then build HTML markup out of it.
Since you know what listings you already saw, when you get new listings you'll be able to identify new ones.
var new_listings = detect_new_listings(data, last_received_listings);
last_received_listings = data;
build_html_in('#hot_properties');
highlight_listings(new_listings); // set a CSS class on a div or whatever
More details
Possible implementation of detect_new_listings
function detect_new_listings(original, new) {
var result = [];
for(var i = 0; i < original.length; i++) {
var found = false;
// find similar listing in new
for(var j = 0; j < new.length; j++) {
if(original[i].listing_id == new[j].listing_id) {
found = true;
break;
}
}
if(!found) {
result.push(original[i]);
}
}
return result;
}
You could put all listings inside an array in JS and then compare that with the newly fetched list from the PHP file or you could simply check on a date column containing the date for when the row was added and then through PHP; if row is earlier than 1 minute - go ahead and put a class on the HTML element.

jQuery/PHP Hide Div, Update Information from MySQL, Show Div New Information

jQuery:
$(document).ready(function(){
$(".reload").click(function() {
$("div#update").fadeOut("fast")
.load("home.php div#update").fadeIn("fast")
});
});
PHP:
function statusUpdate() {
$service_query = mysql_query("SELECT * FROM service ORDER BY status");
$service_num = mysql_num_rows($service_query);
for ($x=1;$x<=$service_num;$x++) {
$service_row = mysql_fetch_row($service_query);
$second_query = mysql_query("SELECT * FROM service WHERE sid='$service_row[0]'");
$row = mysql_fetch_row($second_query);
$socket = #fsockopen($row[3], $row[4], $errnum, $errstr, 0.01);
if ($errnum >= 1) { $status = 'offline'; } else { $status = 'online'; }
mysql_query("UPDATE service SET status='$status' WHERE sid='$row[0]'")
or die(mysql_error());
?>
<ul><li style="min-width:190px;"><?php echo $row[1]; ?></li>
<li style="min-width: 190px;" title="DNS: <?php echo $row[2]; ?>">
<?php echo $row[3] . ':' . $row[4]; ?></li>
<li class="<?php echo $status; ?>" style="min-width:80px;"><div id="update">
<?php echo $status; ?></div></li></ul>
<?php
}
}
?>
<?php statusUpdate(); ?>
I have a button which I press (refresh) and that will then refresh the #update id to hopefully fadeOut all the results, and then fade in the new results... issue is it fades them out okay, but when it brings them back, it's just div on div and div and looks really messy - does not do what it's meant to do (would have to upload a picture to give further information).
In the short, what I want to happen is when you hit the update, they will all fade and then fade in with updated values from the php... I made the php/mysql into a function so then I could call it when i hit that refresh button, thinking that would work, but I don't know how to do that...
Thank-you in advance,
Phillip.
Javascript
$(document).ready(function(){
$(".reload").click(function() {
$("div#update").fadeOut("fast");
$.ajax({
url:'home.php',
data:{type:'getStatus'},
type;'post',
success:function(data){
$('div#update').html(data).fadeIn('fast');
}
});
});
});
php page format
<?php
$type= $_POST['type'];
if($type=="getStatus")
{
//get statuses from data base and return only formatted statuses in html
}
else
{
//your page codes here
//like tags <html>,<body> etc, all regular tags
//<script> tags etc
}
?>
.load("home.php div#update").fadeIn("fast")
That's wrong. You need to use,
$('div#update').load('home.php', function(data) {
$('div#update').html(data).fadeIn("fast");
});
Make sure your PHP file works properly by calling it directly and confirming that it returns the results properly.
Reference : http://api.jquery.com/load
Try this
var $data = $('div#update');
$data.fadeOut('slow', function() {
$data.load('home.php div#update', function() {
$data.fadeIn('slow');
});
});
Just for the reference, it will be better to add an additional page in the same directory (eg: phpcode.php) and then put your php code also in there! then try this:
var $data = $('div#update');
$data.fadeOut('slow', function() {
$data.load('phpcode.php div#update', function() {
$data.fadeIn('slow');
});
});

Categories