invoking jquery in php loop - php

I am new to php,jquery and json.
I am using all of it in my new website.
My problem is i need to divide my html page into 4 parts as divs(north,south,east,west) and display a pie chart in each div, drawn from a jquery/javascript.
I have added a foreach loop for each zone like north,south,east,west.
and i have set the data needed by jquery/php script in session.
But i see that script executes only at the end of for loop and draws the pie chart only in the fourth div.
I want to know the syntax of how i can invoke the script for every iteration of the php loop.
Request your help.
<?php
$customerSelected = "IBL";//change this to actual selected customer
$zoneArray = array(1,2,3,4);
$_SESSION['customerSelected']=$customerSelected;
foreach($zoneArray as $zone){
$_SESSION['zone']=$zone;
$quadrantName = '';
if($zone == 1){
$quadrantName = 'firstQuadrantNorth';
}else if($zone == 2){
$quadrantName = 'secondQuadrantSouth';
}else if($zone == 3){
$quadrantName = 'thirdQuadrantEast';
}else if($zone == 4){
$quadrantName = 'fouthQuadrantWest';
}
$_SESSION['quadrant']=$quadrantName;
?>
<div id="<?=$zone?>" style="height:250px;width:49.7%;float:left; border:1px solid #CCC;">
<div id="<?=$quadrantName?>" style="min-width:50%; height:100px;text-align:left"></div>
<script src="scripts/piechartsims.js?v=<?=$cachebuster; ?>"></script>
<div style="min-width:50%;height:140px;text-align:center;align:center;overflow:auto;">
<?php
include('LastCommunicatedInc.php');
?>
</div>
</div>
<?php
}
?>
`

Related

Load More with PHP prevent calling of en event handler twice on fast clicks?

I have this code, which allows me to make a "show more" button on Advanced Fields Pro repeater Elements in WordPress.
The problem is when I click fast twice(or more) on the buttons it shows me the fields, which are hidden also twice the (or more) time.
Does anyone have an idea on how to solve it?
Code on WordPress Front end:
<div id="photo-gallery">
<div class="row mt-5 mb-3">
<?php
if( have_rows('logos_der_externen_plattformen') ):
$total = count(get_field('logos_der_externen_plattformen'));
$count = 0;
$number = 5;
while ( have_rows('logos_der_externen_plattformen') ) : the_row(); ?>
<div class="col-6 col-md-4 col-lg-2 p-md-5 pr-2 pl-2 pb-5 pt-2 text-center" data-aos="fade-up">
<img data-src="<?php the_sub_field('logo'); ?>" alt="<?php the_sub_field('alternative_beschreibung_des_logos'); ?>" class="lazy img-fluid">
</div>
<?php
if ($count == $number) {
// we've shown the number, break out of loop
break;
} ?>
<?php $count++; endwhile;
else : endif;
?>
</div>
<div align="center" class="text-decoration-none">
<a id="gallery-load-more" style="text-decoration:none;" href="javascript: my_repeater_show_more();" <?php if ($total < $count) { ?> class="d-none" <?php } ?>><h7 id="title-bg"><span>und viele mehr...</span></h7></a></div>
</div>
var my_repeater_field_post_id = <?php echo $post->ID; ?>;
var my_repeater_field_offset = <?php echo $number + 1; ?>;
var my_repeater_field_nonce = '<?php echo wp_create_nonce('my_repeater_field_nonce'); ?>';
var my_repeater_ajax_url = '<?php echo admin_url('admin-ajax.php'); ?>';
var my_repeater_more = true;
function my_repeater_show_more() {
// make ajax request
jQuery.post(
my_repeater_ajax_url, {
// this is the AJAX action we set up in PHP
'action': 'my_repeater_show_more',
'post_id': my_repeater_field_post_id,
'offset': my_repeater_field_offset,
'nonce': my_repeater_field_nonce
},
function (json) {
// add content to container
// this ID must match the containter
// you want to append content to
jQuery('#photo-gallery .row').append(json['content']);
// update offset
my_repeater_field_offset = json['offset'];
// see if there is more, if not then hide the more link
if (!json['more']) {
// this ID must match the id of the show more link
jQuery('#gallery-load-more').css('display', 'none');
}
},
'json'
);
}
Backend:
/**
* ACF Load More Repeater
*/
// add action for logged in users
add_action('wp_ajax_my_repeater_show_more', 'my_repeater_show_more');
// add action for non logged in users
add_action('wp_ajax_nopriv_my_repeater_show_more', 'my_repeater_show_more');
function my_repeater_show_more() {
// validate the nonce
if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'my_repeater_field_nonce')) {
exit;
}
// make sure we have the other values
if (!isset($_POST['post_id']) || !isset($_POST['offset'])) {
return;
}
$show = 10; // how many more to show
$start = $_POST['offset'];
$end = $start+$show;
$post_id = $_POST['post_id'];
// use an object buffer to capture the html output
// alternately you could create a varaible like $html
// and add the content to this string, but I find
// object buffers make the code easier to work with
ob_start();
if (have_rows('logos_der_externen_plattformen', $post_id)) {
$total = count(get_field('logos_der_externen_plattformen', $post_id));
$count = 0;
while (have_rows('logos_der_externen_plattformen', $post_id)) {
the_row();
if ($count < $start) {
// we have not gotten to where
// we need to start showing
// increment count and continue
$count++;
continue;
}
?>
<div class="col-6 col-md-4 col-lg-2 p-md-5 pr-2 pl-2 pb-5 pt-2 text-center" data-aos="fade-up">
<img src="<?php the_sub_field('logo'); ?>" alt="<?php the_sub_field('alternative_beschreibung_des_logos'); ?>" class="img-fluid">
</div>
<?php
$count++;
if ($count == $end) {
// we have shown the number, break out of loop
break;
}
} // end while have rows
} // end if have rows
$content = ob_get_clean();
// check to see if we have shown the last item
$more = false;
if ($total > $count) {
$more = true;
}
// output our 3 values as a json encoded array
echo json_encode(array('content' => $content, 'more' => $more, 'offset' => $end));
exit;
} // end function my_repeater_show_more
This solution fork just fine for me:
document.getElementById("title-bg").onclick = function() {
document.getElementById("title-bg").style.display = "none";
}
There are 2 ways you could solve this:
Create a wrapper function around your JAVASCRIPT implementation of my_repeater_show_more. When this function starts, set a variable that the request is in progress. Unset the variable when the request has completed and the fields have been loaded. Disable the button when the field is set. This way, while the fields are loading, the button cannot be clicked.
Wrap your JAVASCRIPT call to my_repeater_show_more in a debounce. This will prevent the function from firing until some minimum amount of time has passed between clicks. Doing so will prevent the function from firing twice if you double click quickly.
More information about writing a debounce in vanilla JS can be found on this excellent blog post.

How do I adjust margin-top attribute depending on length of php title?

I'm building a custom template in Wordpress.
I need the title of the page to auto adjust itself if it is larger than 45 characters.
The title is being pulled from the Wordpress database via PHP.
I am trying to build javascript to do this:
If the length of the title (via php) is < 45 characters: change the css attribute "margin-top" to 111px.
Else change the css attribute "margin-top" to 150px.
Here is what I have so far:
My HTML:
<div class="title-of-page" id="title" style="margin-top:53px">
<?php echo get_the_title($post->post_parent); ?>
</div>
My Javascript:
<script>
if ( <? php strlen(get_the_title($post - > post_parent)) ?> < 45) {
document.getElementById("title").style.marginTop = "111px";
} else {
document.getElementById("title").style.marginTop = "150px";
}
</script>
Ask questions if I'm not being clear enough.
Why javascript?
<?php
$title = get_the_title($post->post_parent);
if (strlen($title)<45) { $mtop ='111px'; } else { $mtop='150px'; }
echo '<div class="title-of-page" id="title" style="margin-top:'.$mtop.';">'.$title.'</div>';
?>
You can do it in PHP only as #Thomas Martin suggested.
However if you are too keen to do it at the Javascript Side.You can do it by .
<script>
var title = document.getElementById('title').textContent;
if(title.length < 45){
document.getElementById("title").style.marginTop = "111px";
}else{
document.getElementById("title").style.marginTop = "150px";
}
</script>

PHP .rand function,

My php knowledge is limited so sorry if answer is obvious.
I'm using the .rand function to display random images from one of 3 pages when a link is clicked. The pages are all named the same and are in different folders (pages,media,text). The problem I'm having is that I want a combination of 3 different pages/images every time but instead it comes out as the same 3 page/image combination each time.
I want this
e.g.
Page1, Media2, Text1. next...
Page3, Media2, Text3. next...
Page1, Media3, Text2.
Instead it comes out
e.g.
Page1, Media1, Text1. next...
Page3, Media3, Text3. next...
Page2, Media2, Text2.
The solution is probably simple but I can't seem to figure it out.
here is my code :
<body>
<div id="wrapper">
<div id="click">CLICK HERE></div>
<div id="content">
<?php
if (!empty($_GET['p'])) {
$pages_dir = 'pages';
$pages = scandir($pages_dir, 0);
unset($pages[0], $pages[1]);
$p = $_GET['p'];
if (in_array($p.'.inc.php',$pages)) {
include($pages_dir.'/'.$p.'.inc.php');
} else {
echo 'Sorry, page not found.';
}
}
?>
</div>
<div id="content2">
<?php
if (!empty($_GET['p'])) {
$media_dir = 'media';
$media = scandir($media_dir, 0);
unset($media[0], $media[1]);
$p = $_GET['p'];
if (in_array($p.'.inc.php',$media)) {
include($media_dir.'/'.$p.'.inc.php');
} else {
echo 'Sorry, page not found.';
}
}
?>
</div>
<div id="content3">
<?php
if (!empty($_GET['p'])) {
$text_dir = 'text';
$text = scandir($text_dir, 0);
unset($text[0], $text[1]);
$p = $_GET['p'];
if (in_array($p.'.inc.php',$text)) {
include($text_dir.'/'.$p.'.inc.php');
} else {
echo 'Sorry, page not found.';
}
}
?>
</div>
</div>
</body>
you have used the function "rand()" just once , so you will have just one random number. If you want more numbers , use the function multiple times. for example :
$rnd_1 = rand(0,3);
$rnd_2 = rand(0,3);
$rnd_3 = rand(0,3);
Each of them may produce a unique number ;)
You use rand only once here:
<a href="index.php?p=<?php echo 'include-'.rand(1,3); ?>">
There are two solutions:
Don't use rand as GET parameter, just generate random numbers when $_GET['p'] is set.
Create another two GET parameters, ex. $_GET['m'] for media, $_GET['c'] for content and replace $_GET['p'] with them.
Try using shuffle(glob('*.png'));, or just shuffle(); an array of your pictures.
See:
http://php.net/manual/en/function.glob.php
and
http://php.net/manual/en/function.shuffle.php
The string inside glob can be replaced with any file extension.
Your code might look like this:
$allPics = shuffle(glob('*png')); $pic = array_slice($allPics, 0, 3);
Now $pic[0], $pic[1], and $pic[2] hold your images.
Personally, I Think You Should Use JavaScript if you're just trying to return 3 images. That code would look something like this this:
First the External picloader.js file:
//+ Jonas Raoni Soares Silva - Google
//# http://jsfromhell.com/array/shuffle [v1.0]
function shuffle(o){ //v1.0
for(var j,x,i=o.length; i; j=parseInt(Math.random()*i),x=o[--i],o[i]=o[j],o[j]=x);
return o;
}
//everything else by Jason Raymond Buckley
function E(e){
return document.getElementById(e);
}
function picLoader(clickId, outIdsArray, imageArray){
E(clickId).onclick = function(){
var oa = outIdsArray, il = oa.length, sh = shuffle(imageArray), pic = sh.slice(0, il);
for(var i in oa){
E(oa[i]).innerHTML = "<img src='"+pic[i]+"' />";
}
}
}
The code on your page should now look like:
<body>
<div id="wrapper">
<input type='button' value='CLICK HERE' id='showPics' />
<div id="content"></div>
<div id="content2"></div>
<div id="content3"></div>
</div>
<script type='text/javascript' src='picloader.js'></script>
<script type='text/javascript'>
var imageArray = ['img1.png', 'img2.png', 'img3.png', 'img4.png', 'img5.png', 'img6.jpg', 'img7.jpg'];
picLoader('showPics', ['content', 'content1', 'content2'], imageArray);
</script>
</body>
</html>
This should work for any amount of output elements, as long as the imageArray is at least as long as your array that contains output content ids.

Javascript Popup Windows

I have a popup window code that I have used before in login forms. The code displays an in-page popup.
This is the code:
<?php
//In Page Popup Box with Faded Background by Jerry Low #crankberryblog.com
//Find other useful scripts at the Crankberry Blog
//SETTINGS
$fade_amount = 60; //In Percentage
$box_width = 400;
$box_background = 'FFFFFF'; //Hex Color
$box_border_width = 2;
$box_border_color = '999999'; //Hex Color
$close_box = 1; //Do You Want The Close Bar on Top 1 = Yes, 0 = No
$extension = ""; // Other Variables that maybe needed, page number etc.
//Begin Popup Box
$left_margin = ( 0 - ($box_width*0.5) );
$page_url = basename($_SERVER['PHP_SELF']);
if ($extension!="") $page_url .= '?' . $extension;
if (isset($_GET['popup'])) {
echo '<div class="popup" style="width:'.$box_width.'px; background: #'.$box_background.'; margin-left:'.$left_margin.'px;';
if ($box_border_width>1) echo ' border: '.$box_border_width.'px solid #'.$box_border_color.';';
echo '">';
//Close Box
if ($close_box===1) echo '<div class="popup_close">Close (x)</div>';
?>
<!–- START YOUR POPUP CONTENT HERE -–>
Popup content goes in here!
<!–- END OF YOUR POPUP CONTENT HERE -–>
<?php
echo '</div>
<div class="fade" onclick="location.replace(\''.$page_url.'\');" style="opacity: 0.'.$fade_amount.'; -moz-opacity: 0.'.$fade_amount.';filter: alpha(opacity: '.$fade_amount.');"></div>
<div class="fade_container">';
}
?>
Activated Box
This code contains a link that reloads the page with parameters/arguments to show the popup.
I want to update this code to make the popup appear/hide without
This is what I have done so far, yet the popup doesn`t show.
Now I want to update the code to work as follows.
<link rel=StyleSheet href="css/popup.css" type="text/css" media=screen></link>
<?php
//In Page Popup Box with Faded Background by Jerry Low #crankberryblog.com
//Find other useful scripts at the Crankberry Blog
//SETTINGS
$fade_amount = 60; //In Percentage
$box_width = 400;
$box_background = 'FFFFFF'; //Hex Color
$box_border_width = 2;
$box_border_color = '999999'; //Hex Color
$close_box = 1; //Do You Want The Close Bar on Top 1 = Yes, 0 = No
$extension = ""; // Other Variables that maybe needed, page number etc.
//Begin Popup Box
$left_margin = ( 0 - ($box_width*0.5) );
$page_url = basename($_SERVER['PHP_SELF']);
if ($extension!="") $page_url .= '?' . $extension;
{
echo '<div id="pop_up" class="popup" style="visibility:hidden; width:'.$box_width.'px; background: #'.$box_background.'; margin-left:'.$left_margin.'px;';
if ($box_border_width>1) echo ' border: '.$box_border_width.'px solid #'.$box_border_color.';';
echo '">';
//Close Box
if ($close_box===1) echo '<div class="popup_close"><a href="#" ChangeStatus()>Close (x)</a></div>';
?>
<!–- START YOUR POPUP CONTENT HERE -–>
Popup content goes in here!
<!–- END OF YOUR POPUP CONTENT HERE -–>
<?php
echo '</div>
<div id="fade_div" class="fade" onclick="location.replace(\''.$page_url.'\');" style="visibility:hidden; opacity: 0.'.$fade_amount.'; -moz-opacity: 0.'.$fade_amount.';filter: alpha(opacity: '.$fade_amount.');"></div>
<div class="fade_container">';
}
?>
Activated Box
<script>
function ChangeStatus()
{
div = document.getElementById('fade_div').style.visibility;
popup = document.getElementById('pop_up').style.visibility;
alert(popup);
if(popup == "hidden")
{
div = "visible";
popup = "visible";
}
else
{
div = "hidden";
popup = "hidden";
}
}
</script>
ignore the CSS files as it is working fine.
I guess the problem is with the JS. Can anyone help me?
change your javascript to this:
if(popup == "hidden")
{
document.getElementById('fade_div').style.visibility = "visible";
document.getElementById('pop_up').style.visibility = "visible";
}
and
else
{
document.getElementById('fade_div').style.visibility = "hidden"
document.getElementById('pop_up').style.visibility = "hidden";
}

Hide / Show divs from url string in php

A complete beginners question.
I have a large number of divs (>80) on a page (page2.php) and what I would like to do is open page1.php, click on a link to open page2.php and show only one of these divs depending on which link was clicked.
I have a basic working version of this by adding an if else to the divs. I've only done this on 5 of the divs so far and it works but it also seems a fairly in-eloquent way of doing things.
Page 1:
this is a link
Page 2:
<?php
$divID = $_GET['id'];
?>
<div id="r0101" <? if($divID == r0101): ?>class="show"<? else: ?>class="hidden"<? endif; ?> >
This then applies a css class to hide or show the div.
Would it be possible to have a function or whatever at the top of the page that takes the id from the url, figures out that there is a div with that id also, show it and hide all the others? This is probably an easy thing to do but it has me stumped.
Any help greatly appreciated.
Thanks.
Let alone the divs and work on css (as you relay on that to hide/show the divs).
You can generate not only markup but css stylesheet too. Use a similar one (put it at
the end of your head section). And let the browser do the work for you ;)
<style type="text/css">
div {
display: none;
}
div#<?php echo $_GET['id']; ?>:{
display: block;
}
</style>
$divs = array('r0101', 'r0102', 'r0103');
$divID = $_GET['id'];
foreach($divs as $div)
{
echo '<div id="'.$div.'" class="';
if ($div == $divID)
{
echo 'show';
}
else
{
echo 'hidden';
}
echo '">';
}
Assuming I have read the question correctly, you have a set of divs (r0101, r0102, etc.) and wish to show only one of these depending on the page you are on. The code above creates an array of these divs, loops through and creates the div. The class of the div is 'show' if the div matches the div from the page url, and 'hidden' otherwise.
First of all, you should consider a way of making your divs to be printed dynamically. Something like:
<?php
for($i = 1; $i <= 80; $i++):
?>
<div id="r<?php print $i; ?>">div contents</div>
<?php
endfor;
?>
Also, if you find a way of doing what's stated above, you can also do something like:
<?php
for($i = 1; $i <= 80; $i++):
if($i == $_GET['id']){
$class = 'show';
} else {
$class = 'hidden';
}
?>
<div id="r<?php print $i; ?>" class="<?php print $class; ?>">div contents</div>
<?php
endfor;
?>
or
<?php
for($i = 1; $i <= 80; $i++):
$class = ($i == $_GET['id']) ? 'show' : 'hidden';
?>
<div id="r<?php print $i; ?>" class="<?php print $class; ?>">div contents</div>
<?php
endfor;
?>
which is exactly the same but (using the ternary operator) spares a few lines and (some people think) it decreases readability.
If you want to make your download faster, you should output only the div you want to show. You could do something like this:
$divs = array('r0101', 'r0102', 'r0103');
$divID = $_GET['id'];
foreach($divs as $div)
{
if($div == $divID){ echo '<div> /* CONTENT HERE */ </div> };
}
Hope this helps.

Categories