Trying to display data shown depending on what users click - javascript

Have a look here:
http://test.neworgan.org/100/
Scroll down to the community section.
What I'm trying to achieve is to get the data for new organizers, (e.g.: number of friends / amount donated) to show once users click on their thumbnails. right now each user has his or her own unique data stored externally.
Once the users click the thumbnail, 'inline1' appears with the content.
As of now, I'm only able to get the data from the last user to show regardless of whichever user's thumbnails I'm clicking on. I just need a bit of help as to how to change the content depending on which thumbnail users click. So I was wondering if I could have some help here?
Here's that part of the code that matters:
<div class="top-fundraisers-wrapper">
<div class="subsection top-fundraisers">
<?php if ($top_fundraisers && is_array($top_fundraisers)): ?>
<?php foreach ($top_fundraisers as $index => $fundraiser): ?>
<a title="" class="fancybox" href="#inline1">
<div class="top-fundraiser">
<div id="newo<?php print htmlentities($index + 1); ?>" class="top-fundraiser-image">
<img src="<?php
if($fundraiser['member_pic_medium']) {
print htmlentities($fundraiser['member_pic_medium']);
} else {
print $template_dir . '/images/portrait_placeholder.png';
}
?>"/>
</div>
</div>
</a>
<?php endforeach;?>
<?php endif; ?>
</div>
</div>
</div>
<div id="inline1">
<div class="top-fundraiser-image2">
<img src="<?php
if($fundraiser['member_pic_large']) { print htmlentities($fundraiser['member_pic_large']);
} else {
print $template_dir . '/images/portrait_placeholder.png';
}
?>"/>
</div>
<span class="member-name"><?php print htmlentities($fundraiser['member_name']); ?></span>
<span class="friend-count"><?php print number_format($fundraiser['num_donors']) . (($fundraiser['num_donors'] == 1) ? ' Friend' : ' Friends'); ?></span>
<span class="fundraisers-text"> Donated: </span><span class="fundraisers-gold"> $<?php print number_format($fundraiser['total_raised']); ?></span>
</div>

Best way is to use Ajax. Something like this
$("#button").click( function() {
$.ajax({
url: 'file.php',
method: 'post',
data: { id: $(this).val() },
error: function() {
alert('error while requesting...');
}, success: function(data) {
alert( data ); /** received data - best to use son **/
}
});
});
Next parse json var json = $.parseJSON(data);
or ... use dataJson option.
Next Your data should be inserted using class or id to specific location.

Create another loop for content
<?php if ($top_fundraisers && is_array($top_fundraisers)):
$i = 1;
foreach ($top_fundraisers as $index => $fundraiser): ?>
<a title="" class="fancybox" href="#inline<?php echo $i; ?>">
// ... content
<?php $i++;
endforeach;
endif; ?>
And another loop
<?php if ($top_fundraisers && is_array($top_fundraisers)):
$i = 1;
foreach ($top_fundraisers as $index => $fundraiser): ?>
<div id="inline<?php echo $i; ?>">
// inline content here
</div>
<?php $i++;
endforeach;
endif; ?>

Hope your JavaScript function to open fancybox works fine via calling class. So by following code you do not need to play with Javascript code.
Building anchors tags:
<?php
if (!empty($top_fundraisers) && is_array($top_fundraisers)) {
foreach ($top_fundraisers as $index => $fundraiser) {
<a title="" class="fancybox" href="#inline<?php echo $fundraiser['id']; ?>">HTML Content Goes Here</a>
<?php
} //end of foreach
} // end of if condition
?>
Building Popup HTML DOMs:
<?php
if (!empty($top_fundraisers) && is_array($top_fundraisers)) {
foreach ($top_fundraisers as $index => $fundraiser) {
<div id="inline<?php echo $fundraiser['id']; ?>">HTML Content Goes Here</div>
<?php
} //end of foreach
} // end of if condition
?>

You cannot perform this because PHP runs server-side and JavaScript runs in the browser.
To perform this you can use AJAX to get the div as required by user.
...or store the data client-side and change the content of #inline1 based on which item was clicked

Related

Pass single PHP value from ACF Repeater Field

I have a page for team members of a company. The team members are rendered with an ACF repeater that has fields for Name, Job Title, and Biography. On the page I would like to render just their Name, and Job Title. If you were to click on a team member, that would open a modal that would render that team members biography.
I have this working, but my approach adds the Biography field to the DOM for each team member, hides it, and passes it into the modal on click. I am wondering if it is possible to pass the Biography field into the modal without having to render the text in the DOM initially and hiding it?
Below is my current code:
<!-- acf repeater -->
<?php if( have_rows('team_member') ): ?>
<?php while( have_rows('team_member') ): the_row();
$name = get_sub_field('name');
$job_title = get_sub_field('job_title');
$biography = get_sub_field('biography');
?>
<div class="team-member">
<div>
<?php echo $name ?>
</div>
<div>
<?php echo $job_title ?>
</div>
<div class="biography" style="display: none;">
<?php echo $biography ?>
</div>
</div>
<?php endwhile; ?>
<!-- modal -->
<div class="modal">
modal
<div class="modal-biography">
</div>
</div>
<?php endif; ?>
<!-- javascript -->
jQuery(function($) {
$('.team-member').on('click', function() {
var modalBiography = $(this).find('.biography').text();
$('.modal-biography').text(modalBiography);
})
});
If you don't need to display the bio div, I'd suggest just putting it into a data-bio attribute:
<div class="team-member" data-bio="<?php echo $biography; ?>">
<div><?php echo $name; ?></div>
<div><?php echo $job_title; ?></div>
</div>
then tweak js a bit to pull this data-bio instead:
jQuery(function($) {
$('.team-member').on('click', function() {
var modalBiography = $(this).data('bio');
$('.modal-biography').text(modalBiography);
})
});

Wordpress - Show random post with JS, not PHP

I have this page containing recent posts at the bottom. I have set it to randomly show me three posts from the same category as the current post. Heres the loop:
<!-- Related Posts =========================================== -->
<div class="relared-posts-heading">
<h2>SIMILAR INSIGHTS</h2>
</div>
<div class="container blog-card-container">
<div class="card-columns">
<?php
// the query
$the_query = new WP_Query( array(
'orderby' => 'rand',
'cat' => '-14',
'posts_per_page' => 3,
));
?>
<?php if ( $the_query->have_posts() ) : ?>
<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<!-- Conditional a Link =========================================== -->
<?php
if(get_field('quote') == ''){
$yourTag = "<a href='".get_the_permalink()."'>" ;
} else {
$yourTag = "";
}
?>
<div> <?php echo $yourTag; ?> </div>
<div class="card">
<a href="<?php the_permalink(); ?>">
<div class="blog-thumb-container-2">
<?php if ( has_post_thumbnail() ) { the_post_thumbnail(); } ?>
</div>
</a>
<div class="blog-meta-container-2">
<p class="blog-cat-label"><?php the_category(', '); ?></p>
<h2 class="blog-card-title"><?php the_title(); ?></h2>
<p class="card-text"><?php the_excerpt(__('(moreā€¦)')); ?></p>
<p><strong><?php the_author(); ?></strong> | <?php echo get_the_date(); ?> </p>
</div>
</div>
</a>
<?php endwhile; ?>
<?php wp_reset_postdata(); ?>
<?php else : ?>
<p><?php __('No News'); ?></p>
<?php endif; ?>
</div>
</div>
This works fine currently.
The trouble is, when finished, the site will be behind a clients custom cache and he tells me that PHP randomisers wont work as it will just show the cached version. He suggested I do any randomising using Javascript!
So firstly - is this possible? Secondly, How would I go about targeting this is javascript!? Thanks for looking!!
Unfortunately you won't be able to randomize a post in this way for the caching reason.
What you can do instead is use an Ajax call to dynamically fetch and insert a random post...
$.get('/wp-content/themes/SomeTheme/random.php?v=' + Math.floor(Date.now() / 1000))
.done(function(resp) {
$('.random-post').html(resp);
})
.fail(function(xhr) {
// handle error (xhr object contains the response)
});
And then create a separate random.php file in your theme and put the code to randomly return a single post in there. Note, that you don't need to put the whole layout around the post (don't include header.php etc). That's because this exact HTML fragment will be sent to the frontend and inserted dynamically.
The ?v= parameter is required for cache busting so that it fetches a new post each time.
Try wrapping the entire funtionality as a shortcode.

Dynamically loading in order images from the server (for html gallery)

So I made a wowslider gallery dynamic so it loads all the images from a specific folder. The problem though is that they all get loaded simultaneously and take too long to load. I want them to load in order, one by one using js or jquery. My code;
<div class="ws_images" >
<ul>
<?php // start looping the pics
$inc = 0;
foreach (new DirectoryIterator('gallery/data1/images/') as $file) {
if($file->isDot()) continue;
$withoutExt = preg_replace('/\\.[^.\\s]{3,4}$/', '', $file->getFilename()); //removing the extension
?>
<li>
<img class='imgs' src="gallery/data1/images/<?php echo $file->getFilename(); ?>" alt="<?php echo $withoutExt ?>" title="<?php echo $withoutExt; ?>" id="wows1_<?php echo $inc; $inc++; ?>"/>
</li>
<?php } // ending the loop ?>
</ul>
</div>
I've found this thread Controlling image load order in HTML which solves the problem i guess but I can't implement it to my dynamic code... I tried many approaches but none of them worked, please help !
Here you have something implementin the code from that answer you posted here
<div class="ws_images" >
<ul>
<?php // start looping the pics
$inc = 0;
foreach (new DirectoryIterator('gallery/data1/images/') as $file) {
if($file->isDot()) continue;
$withoutExt = preg_replace('/\\.[^.\\s]{3,4}$/', '', $file->getFilename()); //removing the extension
?>
<li>
<img class='imgs' img-name="<?php echo $file->getFilename(); ?>" src="" alt="<?php echo $withoutExt ?>" title="<?php echo $withoutExt; ?>" id="wows1_<?php echo $inc; $inc++; ?>"/>
</li>
<?php } // ending the loop ?>
</ul>
</div>
<script>
var imgAddresses = [];
$('.ws_images ul li').each(function(){
imgAddresses.push($(this).find('img').attr('img-name'));
});
function loadImage(counter) {
//Break out if no more images
if(counter==imgAddresses.length) { return; }
//Grab an image obj
var I = document.getElementById("wows1_"+counter);
//Monitor load or error events, moving on to next image in either case
I.onload = I.onerror = function() { loadImage(counter+1); }
//Change source (then wait for event)
I.src = 'gallery/data1/images/'+imgAddresses[counter];
}
loadImage(0);
</script>
You need to test this code because i didn't test it but i wrote it just to give you an idea how to do that

PDO fetch then targeted object?

I currently have a page where I'm connecting to db via PDO, db, prepare.
Selecting SQL_CALC_FOUND_ROWS in order to have pagination with the results.
All of that is good. However, each return is to have a text popup when clicked. Thats where I want to target a particular field of defined row.
Code I have is as follows :
$db = new PDO('mysql:dbname=###;host=###','###','###');
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$perPage = isset($_GET['per-page']) && $_GET['per-page'] <= 50 ?(int)$_GET['per-page'] : 8;
//Positioning
$start = ($page > 1) ? ($page * $perPage) - $perPage : 0;
//Query
$articles = $db->prepare("
SELECT SQL_CALC_FOUND_ROWS id, comment_caption, comment_sub_caption,comment_title, comment_main, comment_name,
comment_date, comment_url
FROM TABLE_NAME
LIMIT {$start}, {$perPage}
");
$articles->execute();
$articles = $articles->fetchAll(PDO::FETCH_ASSOC);
// Pages
$total = $db->query("SELECT FOUND_ROWS() as total")->fetch()['total'];
$pages = ceil($total / $perPage);
//Pagination div
<div class="pagination">
<?php for($x = 1; $x <= $pages; $x++): ?>
<a href="?page=<?php echo $x; ?>&per-page=<?php echo $perPage; ?> "<?php if($page === $x){ echo 'class="selected"'; }?>><?php echo $x ?></a>
<?php endfor; ?>
</div>
// Here is the container for the foreach
<div id="container">
<?php
foreach($articles as $article): ?>
<div class="item small">
<div class="module">
<div class="article">
<div class="item-inner">
<a href="<?php echo $article['comment_url']; ?>">
<div class="project-title">
<div class="mid">
<h2><?php echo $article['comment_caption']; ?></h2>
</div>
</div>
</a>
</div>
</div>
</div>
</div>
<?php endforeach; ?>
// This is the popup that I want to associate with each return
<div id="test-popup" class="white-popup mfp-hide">
<blockquote><?php echo $article['comment_main'];
?></blockquote>
<p><i><?php echo $article['comment_name']; ?> - <?php echo $article['comment_date']; ?></i></p>
</div>
In the popup, I want to echo the 'comments_main, comments_name & comments_date' field of the particular instance that is clicked. Here currently, it just echos the first row.
I'm not sure what the best way to go about it is... ?
Any help would be greatly appreciated.
This is not really a php-mysql related question, but rather a javascript-html-css related one.
You have 2 options:
You output the comments_main, comments_name & comments_date fields to all listed items in a way they are not visible to the users first in the browser. Typically, you could use the anchor element's title property, or html5's data- properties, or even a list of invisible divs. Whenever the user clicks a link, you use javascript to fetch these data for the given comment from your list on the client side (if they are not stored in a list of divs already) and make it appear.
You do not output these data to the client, but upon clicking you use an ajax call to retrieve these data from the server via another php page.
For both approach there are lots of tutorials out there with designed boxes (tooltips) and copy-paste javascript, html, and css code.

jQuery addClass within a foreach loop

I have a few foreach loops with a trigger and a content div. The intent is for the trigger to be clicked, then addClass to content div, making it visible on screen.
foreach markup
<?php foreach( $posts as $post ) : ?>
<a class="slide-trigger" href="#loc<?php echo $post->ID;?>"><?php the_title(); ?></a>
<span>
<?php
$speakers = get_field('speakers');
?>
<?php if( $speakers ): ?>
<ul class="flat">
<?php foreach( $speakers as $speaker ): ?>
<li>
<a href="<?php echo get_permalink( $speaker->ID ); ?>">
<?php echo get_the_title( $speaker->ID ); ?>
</a>
</li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
</span>
<div class="slide" id="loc<?php echo $post->ID;?>">
<div class="close"></div>
<?php echo $post->post_title;?>
<?php echo $post->post_content;?>
</div>
<?php endforeach; ?>
jQuery
$(".slide-toggle[href^='#loc']").click(function(e){
e.preventDefault();
$(".slide[id^='loc']").addClass("open");
})
$(".close").click(function(){
$(".slide").removeClass("open");
});
What I'm looking for is each slide-toggle to trigger it's slide.
Any thoughts?
The ID is in the href, so just grab it and remove the #loc prefix, then you can select the corresponding slide to open. Also this way, the startsWith selector is no longer required.
$(".slide-toggle[href^='#loc']").click(function(e){
e.preventDefault();
$(".slide[id='loc" + this.href.replace('#loc', '') + "']").addClass("open");
})
Having to parse out the ID, then concatenate like this seems a bit hacky. It would be nicer to use data-* attributes.
Link:
<a class="slide-trigger" data-id="<?php echo $post->ID;?>" href="#loc<?php echo $post->ID;?>"><?php the_title(); ?></a>
Slide:
<div class="slide" data-id="<?php echo $post->ID;?>" id="loc<?php echo $post->ID;?>">
jQuery:
$(".slide-toggle[data-id]").click(function(e){
e.preventDefault();
$(".slide[data-id=" + $(this).data('id') + "]").addClass("open");
})
#MrCode had two great solutions to this. The data-id method is a bit more elegant and what I went with.
Note, the $post->ID is a number which just won't work as an id= - https://css-tricks.com/ids-cannot-start-with-a-number/ - and was causing the issue where things just wouldn't work.
The answer; follow #MrCode's method of using a data attribute. It's elegant and works great w/ the loop.

Categories