create divs dynamically while php loop creating divs - php

im new in jquery and get stacked in a issue and need help.
i have a sql query that retrieve ids and put them in array . i have a loop that create a div for each id in that array all in php. works fine.
on the other hand i have a javascript function doing the same with the same array and creating divs inside the div created with the above function all in jquery.
the first one show the picture of a users with the id.
the javascript one shows the name of users with the id.
the problem is jquery function only createme the div with all names within the first div created in the php loop.
i want both being created at the same time. i tried all i know and couldnt getit.
please help.
here is the code :
$receivers is the array containing the ids.
$totalreceivers is the count of the ids.
function showfbnames() {
var receivers = <? echo $receivers; ?>;
var count = <? echo $totalreceivers; ?>;
for (var i = 0; i < count; i++) {
var temparray = ["<?php echo join("\", \"", $receivers); ?>"];
FB.api(
{
method: 'fql.query',
query: 'SELECT name FROM user WHERE uid='+temparray[i]
},
function(resp) {
$.each(resp, function(k,v) {
$("#divfather").append("<div class='tit' id ='fbname'>"+(v.name)+"</div>");
//$("#fbname").html(v.name);
})
}
);
}
}
the php loop creating divs :
<?for ($i = 0; $i < $totalreceivers; $i++) {?>
<script>showfbnames()</script>
<tr><td>
<div style="width:100%; height:150px;overflow:auto;border-top:1px solid #c89cc1;border-bottom:1px solid #c89cc1;" id="divfather">
<? echo "<img src='https://graph.facebook.com/$receivers[$i]/picture' width='40' style='float:left'/>";?>
</div>
</td>
</tr>
<? } ?>

Your loop creates multiple divs with the id of "divfather".
That will not produce the results you desire. You need to have each div with a different id.
id="divfather<?echo $i;?>"
Also, pass the id to the "showfbnames" function:
<script>showfbnames(<?echo $i;?>)</script>
So that you can use it in your jquery code:
function showfbnames(passedi) {
and then $("#divfather"+passedi).append(
(Note: I recommend you move the <script> to appear AFTER the div, to be safe. You don't have to, but it's too risky.)

I retract my previous answer; please select this one as the Accepted solution.
I believe this is what you're trying to accomplish:
<? for ($i = 0; $i < $totalreceivers; $i++) { ?>
<tr><td>
<div style="width:100%; height:150px;overflow:auto;border-top:1px solid #c89cc1;border-bottom:1px solid #c89cc1;" id="divfather<? echo $i; ?>">
<? echo "<img src='https://graph.facebook.com/$receivers[$i]/picture' width='40' style='float:left'/>"; ?>
</div>
</td></tr>
<? } ?>
<script type="text/javascript">
var count = <? echo $totalreceivers; ?>;
var temparray = ["<?php echo join("\", \"", $receivers); ?>"];
for (var i = 0; i < count; i++) {
FB.api(
{
method: 'fql.query',
query: 'SELECT name FROM user WHERE uid='+temparray[i]
},
function(resp) {
$.each(resp, function(k,v) {
$("#divfather"+i).append("<div class='tit' id ='fbname"+i+"'>"+(v.name)+"</div>");
//$("#fbname").html(v.name);
})
}
);
}
</script>

Related

Hiding a button when maximum is reached: Jquery

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();
}

Auto creating div's with jQuery and inserting data from mysql

I want to make auto creating div's with jQuery. I have to fill them with data from MySql database. The problem is that when I use foreach loop it doesn't want to echo data.
Here is my code for mysql:
$sql = "SELECT * FROM `post` ORDER BY `id` DESC";
$result = mysqli_query($con, $sql);
$row = mysqli_num_rows($result);
And here is my jQuery code:
$(document).ready(function(){
var count = 1;
for(i = <?php echo $row; ?>; i > 0; i--){
$("#main").prepend('<div id="first'+count+'"></div>');
count++;
}
count = 1;
for(i = <?php echo $row; ?>; i > 0; i--){
<?php
while($col = mysqli_fetch_assoc($result))
{
$cols[] = $col;
}
foreach($cols as $col){
?>
$("#first"+count+"").text("<?php echo $col['post']; ?>");
count++;
<?php } ?>
}
});
I've also checked in inspect element and everything seems ok, but it doesnt want to create div's.
And if I change this echo $col['post']; to some other text, it works.
Here is what I get in inspect element:
$(document).ready(function(){
var count = 1;
for(i = 3; i > 0; i--){
$("#main").prepend('<div id="first'+count+'"></div>');
count++;
}
count = 1;
for(i = 3; i > 0; i--){
$("#first"+count+"").text("text1");
count++;
$("#first"+count+"").text("text2");
count++;
$("#first"+count+"").text("text3");
count++;
}
});
Thank you for ideas!
I run your code in my workstation it works fine.
I can suggest you check for duplicate id of your new created div you can alter them in class may be its not conflict then.
Is #main div binded before the page load.
check for database is data insertion OK.
Its just some suggestion. If you can say some specific details about the scene, then i can provide you some specific suggestion.
Thanks

PHP for loop not working with jQuery API (Uncaught TypeError)

So I have this array full of YouTube Video ID's that I'm trying to load with jQuery. But for some reason it's not fully working, It's giving me this error in the console:
CODE:
<script type='text/javascript'>
$(document).ready(function() {
<?php
$videos = array("VGh5DV0D3wk", "6y_NJg-xoeE", "9Q31J3mkCKY");
for ($i = 0; $i < count($videos); $i++) {
?>
// -----------
$.get(
"https://www.googleapis.com/youtube/v3/videos", {
part: 'snippet',
key: 'AIzaSyDYwPzLevXauI-kTSVXTLroLyHEONuF9Rw',
id: '<?php echo $videos[$i]; ?>',
},
function(data) {
$('#playlist-item-<?php echo $i; ?>').text(data.items[<?php echo $i; ?>].snippet.title);
});
<?php
}
?>
});
</script>
the response is having only one item. You don't have to increment the array index.
Use the below code.
$('#playlist-item-<?php echo $i; ?>').text(data.items[0].snippet.title);

Loading the Select Box again on clearing the text box field

I have a Select box and a text box to search through the list in the select box. The Select box is getting populated from a database with PHP. What I am trying to achieve here is as soon as clear the text field; the select box should refresh. I have to reload the whole page to do that. Here is the little script that I using to search through select box.
function filterSelectBox(filterButton) {
var searchValue = document.getElementById('selectFilter').value.toLowerCase();
var selectField = document.getElementById("domainID");
var optionsLength = selectField.options.length;
for(var i = 0; i < optionsLength; i++) {
if(selectField.options[i].innerHTML.toLowerCase().indexOf(searchValue) >= 0) {
selectField.options[i].style.display = 'block';
} else {
selectField.options[i].style.display = 'none';
}
}
}
Here is HTML Elements associated with the code.
<div class="search_domains" id="search_domains">
<input type="text" id="selectFilter" name="selectFilter" />
<input type="button" id="filterButton" value="Filter" onClick="filterSelectBox(this)"/>
</div>
and this is how I am populating the Select box,
<select name="domainID" id="domainID" size="15" style="width:175">
<option>Select a Domain</option>
<? foreach ($domains as $row) {
?>
<option value="<?=$row -> id ?>"><?=$row -> domain ?></option>
<? } ?>
</select>
Put this code:
document.getElementById('selectFilter').onkeyup = function() {
if(this.value.length == 0) {
var selectField = document.getElementById("domainID");
var optionsLength = selectField.options.length;
for(var i = 0; i < optionsLength; i++) {
selectField.options[i].style.display = 'block';
}
}
};
just before the </body> tag in your page, and it will show all of the options when you clear the textbox value.
What I'd do here is populate the list with AJAX from that same PHP file, but have it output JSON. On loading the page, the AJAX request would load the php file, get the JSON and add the items in the list.
For refreshing when the text field is blank, you could use an onChange or onKeyUp and check the length of the value.
I think all this would be much simpler in jQuery or any JS framework than pure JS :)
These will help:
http://css-tricks.com/dynamic-dropdowns/
Using jQuery, JSON and AJAX to populate a drop down
Populate dropdown using json
Populate Dropdown Menu in PHP from JSON
You could definitely use AJAX, but for this example, it may not be necessary. It might be more efficient to just store the original contents in a Javascript array and reset it when you need to. I would actually remove the options instead of hiding them:
<script type="text/Javascript">
var originalOptions = {<?php $echo = array(); foreach ($domains as $row) $echo[] = "\"{$row->id}\":\"{$row->domain}\""; echo implode(", ", $echo); ?>};
function filterSelectBox(text)
{
var selectField = document.getElementById('domainID');
selectField.options.length = 0;
for (var key in originalOptions)
{
if (originalOptions[key].substr(0, text.length) == text)
{
var option = document.createElement("option");
option.value = key;
option.text = originalOptions[key];
selectField.add(option, null);
}
}
}
</script>
<select name="domainID" id="domainID" size="15" style="width:175">
<?php foreach ($domains as $row) {
echo "\t<option value=\"{$row->id}\">{$row->domain}</option>\n";
} ?>
</select>
<input type="text" onkeyup="filterSelectBox(this.value)" />

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.

Categories