Using php to display content in jquery tabs - javascript

I have a page with a few jquery tabs, each of which I want to display the result of a php function, as follows:
<ul id="tabs" class="ccm-dialog-tabs">
<li class="ccm-nav-active">Tab 1 Title </li>
<li>Tab 2 Title></li>
</ul>
<div id="tabs-1-tab">
<?php echo "This is tab 1<br>"; ?>
</div>
<div id="tabs-2-tab">
<?php echo "This is tab 2<br>"; ?>
</div>
The jquery to make the tabs work is:
<script type="text/javascript" language="javascript">
var ccm_activeTransactionsTab = "tabs-1";
$("#transaction_tabs a").click(function() {
$("li.ccm-nav-active").removeClass('ccm-nav-active');
$("#" + ccm_activeTransactionsTab + "-tab").hide();
ccm_activeTransactionsTab = $(this).attr('id');
$(this).parent().addClass("ccm-nav-active");
$("#" + ccm_activeTransactionsTab + "-tab").show();
});
</script>
The problem I am having is that when the page loads, the active tab shows the result of both php statements - i.e. it shows:
echo "This is tab 1<br>;
echo "This is tab 2<br>;
If I click between the tabs a few times then the extra information disappears. These tabs work fine normally, the problem only arises when they show the output of a php function.

I would suggest you use hide then at start using simple CSS
<div id="tabs-1-tab" style='display:none'>
<?php echo "This is tab 1<br>"; ?>
</div>
<div id="tabs-2-tab" style='display:none'>
<?php echo "This is tab 2<br>";?>
</div>
Also you have missed closing quotes in statement <?php echo "This is tab 1<br>; ?>

You missed the qoute on echo "This is tab 1<br>; but echo "This is tab 1<br>";

Related

Does include or require refresh a page? Help on changing .active in nav-bar echoed by PHP

I have a question on include, on whether require_once something.php triggers a refresh or not? It seems every new require call does trigger a refresh.
Actually, my actual question is something different but it directed my attention to the above. Please bear with a beginner like me.
On Bootstrap 5 navbar, a nav-items has a .active to make it stand out. I want to move the .active to the relevant nav-item clicked and tried this on codepen. The script works fine, but it doesn't work when using it on my toy website, where the navbar html codes are echoed out by php depending on $isLoggedIn == true || false.
The index page is composed of a header.php (which the nav-bar resides) and a requestedPage.php (which includes whatever page being requested).
When a page on the header is clicked, that generates index.php?reqPage=SomePage and included in index.php by require_once __DIR__."/pages/$reqPage.php";, which reloads the page (including header.php), so those nav-bar items start afresh with .active in Home rather than the item clicked. Whenever I click on a nav-item, the alert Link clicked! is first shown followed by document loaded!, suggesting .active is changed and then nav-bar reloaded.
Please comment and/or advise on how to make the .active work. I am new to php and backend.
files
index.php
header.php
js/header.js
pages/page1.php
pages/page2.php
pages/page3.php...
header.php
<html>
<head>
<!--bootstrap and jquery CDNs are here-->
<script src="js/header.js"></script> //for changing .active in nav-item
</head>
<body>
<?php //use php to echo out the nav-bar
if ($isLoggedIn) { //show bootstrap nav-bar for a logged-in user
echo "
<nav class='navbar navbar-expand-lg navbar-dark bg-primary'>
<div class='container'>
<a class='navbar-brand' href='#'>Trump</a>
<button class='navbar-toggler' type='button' data-bs-toggle='collapse' data-bs-target='#loggedInMenus'>
<span class='navbar-toggler-icon'></span>
</button>
<div class='collapse navbar-collapse' id='loggedInMenus'>
<ul class='navbar-nav'>
<li class='nav-item'>
<a class='nav-link active' href='index.php?reqPage=page1'>Home</a>
</li>
<li class='nav-item'>
<a class='nav-link' href='index.php?reqPage=page2'>Lions</a>
</li>
<li class='nav-item'>
<a class='nav-link' href='index.php?reqPage=page3'>Tigers</a>
</li>
</ul></div></div></nav>
";
} else { //show nav-bar for an unlogged-in visitor
echo "
<nav class='navbar navbar-expand-lg navbar-dark bg-primary'>
<div class='container'>
<a class='navbar-brand' href='#'>Trump</a>
<button class='navbar-toggler' type='button' data-bs-toggle='collapse' data-bs-target='#unloggedInMenus'>
<span class='navbar-toggler-icon'></span>
</button>
<div class='collapse navbar-collapse' id='unloggedInMenus'>
<ul class='navbar-nav'>
<li class='nav-item'>
<a class='nav-link active' href='page1.php'>Home</a>
</li>
<li class='nav-item'>
<a class='nav-link' href='index.php?reqPage=page4'>Dogs</a>
</li>
<li class='nav-item'>
<a class='nav-link' href='index.php?reqPage=page5'>Cats</a>
</li>
</ul></div></div></nav>
";
}
?>
index.php
<?php
require_once __DIR__."/init.php"; //this contains $isLoggedIn
require_once __DIR__."/header.php"; //load the menus
$reqPage = isset($_REQUEST["reqPage"]) ? $_REQUEST["reqPage"] : null;
require_once __DIR__."/pages/$reqPage.php"; //load the requested page
header.js
$(document).ready(function(){
alert("document loaded!");
$(".nav-link").on("click", function() {
alert("Link clicked!");
$(".navbar-nav").find(".active").removeClass("active");
$(this).addClass("active");
}
);
});
This approach uses purely PHP to achieve the goal of setting the "active" class on the correct link. I don't know if your website is database driven or not, but for simplicity, I'm using an array to store your pages
<body>
<?php
// DON'T use php to echo out the nav-bar. Instead just close the PHP tag
$pagesArray = array('page1' => 'Home',
'page2' => 'title2',
'page3' => 'title3',
'page4' => 'Dogs',
'page5' => 'Cats');
if ($isLoggedIn) {
//show bootstrap nav-bar for a logged-in user
?>
<nav class='navbar navbar-expand-lg navbar-dark bg-primary'>
<div class='container'>
<a class='navbar-brand' href='#'>Trump</a>
<button class='navbar-toggler' type='button' data-bs-toggle='collapse' data-bs-target='#loggedInMenus'>
<span class='navbar-toggler-icon'></span>
</button>
<div class='collapse navbar-collapse' id='loggedInMenus'>
<ul class='navbar-nav'>
<?php
// Open PHP tag again
foreach($pagesArray AS $key => $value){
// Loop through your pages array (or sql loop, etc)
$active = "";
if ( stripos($reqPage, $key) !== FALSE) {
// if $key (page name) matches $reqPage make this link active
// if no match, $active remains empty, so when it is echo'ed,
// there is no class printed on the page for that anchor tag
$active = "class='active'";
}
echo "<li class='nav-item'>
<a class='nav-link' ".$active." href='index.php?reqPage=".$key."'>".$value."'</a>
</li>";
} // END while loop
// close PHP tag again
?>
</ul></div></div></nav>
<?php
} // END if logged in
?>
</body>
Given my code organization where the navbar is inside header.php and included into index.php, and that the requested page variable $reqPage only resides in index.php, I cannot test $reqPage = $page inside header.php to identify the selected page before echoing out each nav-item.
$page exists in header.php before echoing out each nav-item
when user clicks on a link, its value goes to index.php as $_GET[""]
it is assigned to $reqPage in index.php
so $page and $reqPage exist in different places at different times, and cannot be tested before echo out, so testing for equality and then add .active to the echo doesn't work
Instead, I echo out the nav-bar in header.php and only identify the requested page and then add .active in index.php using JS.
header.php
<nav class='navbar bg-primary'>
<div class='container'>
<a class='navbar-brand' href='#'>Trump</a>
<button class='navbar-toggler' type='button' data-bs-toggle='collapse' data-bs-target='#menus'>
<span class='navbar-toggler-icon'></span>
</button>
<div class='collapse navbar-collapse' id='menus'>
<ul class='navbar-nav'>
<?php //php to dynamically echo out each navbar menu dependent on login
//array to contain nav-items for logged-in / unlogged-in users
$loggedInMenu = ["Home" => "home", "Lions" => "lions", "Tigers" => "tigers", "Log Out" => "logout"];
$unloggedInMenu = ["Home" => null, "Log In" => "login", "Sign Up" => "signup"];
//produce either Logged-in menus or Unlogged-in menus
if ($isLoggedIn) {
produceNavMenu($loggedInMenu);
} else {
produceNavMenu($unloggedInMenu);
}
//helper function to echo out the nav-menu by nav-items one by one
//#param $menu must be associative array having Title => reqPage
function produceNavMenu(array $menu) {
foreach($menu as $title => $page) {
echo "<li class='nav-item'>
<a class='nav-link' id='$page' href='index.php?reqPage=$page'>$title</a>
</li>";
}
}
?>
</ul></div></div></nav><!--end of navbar-->
index.php
<?php
require_once __DIR__."/init.php"; //this contains $isLoggedIn
require_once __DIR__."/header.php"; //load the menus
$reqPage = isset($_REQUEST["reqPage"]) ? $_REQUEST["reqPage"] : null;
require_once __DIR__."/pages/$reqPage.php"; //load the requested page
?>
<script> //js to add .active to the relevant nav-item
$(document).ready( function() {
var reqPage = "<?php echo "$reqPage"; ?>"; //php var to js var
var activeID = "#"+reqPage; //html id
$(activeID).addClass("active"); //add .active to the requested page
});
</script>

PHP read more read less - Magento 2

I made an read more read less script for my Magento 2 webshop. This is used on a category page where there are serval subcategorie blocks to choose, each subcategory has a description with.
The problem: if I click read more all the descriptions of the subcategories will expand in stead of only the description of the subcategory I clicked read moreI am starting to learn PHP and Magento 2 but I can't fix this, does someone know the solution?
<div class="product description product-item-description">
<div class="more">
<?php if ($_subCategory->getDescription()) {
$string = strip_tags($_subCategory->getDescription());
if (strlen($string) > 250) {
// truncate string
$stringCut = substr($string, 0, 250);
$string = substr($stringCut, 0, strrpos($stringCut, ' ')).'... Lees meer';
}
echo $string;
?>
</div>
<?php
}else {?>
<?php /* #escapeNotVerified */ echo $_attributeValue;
}
?>
</div>
<div class="less" style="display:none">
<?php echo $_subCategory->getDescription(); ?>
Lees minder
</div>
<script type="text/javascript">
console.log('test');
require(["jquery"],function($){
$('.readmore').on("click",function(){
$('.less').show();
$('.more').hide();
});
$('.readless').on("click",function(){
$('.less').hide();
$('.more').show();
});
});
</script>
</div>
This is because, when you type $('.less').hide(); this is grabbing every element with the attribute class='less'. This is the way I would overcome this:
Start by attaching a unique attribute to each <div class="more"> or <div class="less"> - in this case, we use the class attribute: (and move 'more' or 'less' to an id)
<div id="read-more-block" class="cat-<?php echo $_subCategory->getId(); ?>">
<!-- my "read more" content -->
<a class="link" href="#read-more-block">Read Less</a>
</div>
<div id="read-less-block" class="cat-<?php echo $_subCategory->getId(); ?>">
<!-- my "read less" content -->
<a class="link" href="#read-less-block">Read More</a>
</div>
We now have a read-more-block and a read-less-block for each subcategory. When we click the inside link a jQuery event should fire which will hide itself and display the other.
And then, in your jQuery:
$('#read-more-block .link').on('click', function() {
var $readLessBlock = $('#read-less-block.' + $(this).parent().attr('class'));
$readLessBlock.show(); //Show the read less block
$(this).parent().hide(); //Hide the read more block
});
..and vice versa for read less.

change main image by click left or right arrow or selecting actual image from thumbnail gallery in PHP

i'm developing a pdf book page viewer, i have many books that has more than 100 pages in my mysql database. so i fetch the book pages into my thumbnail gallery and if i select that image it will add img src to main image and display it on main image div, that works perfectly, here i have right and left arrow buttons next to main image, if i click these buttons the image should select next image or previous image. i was trying to get the idea and trying different source i could not get the output, please help me with this, i have added my codes bellow,
PHP
<button class="left-arrow" id="left-arrow">Left</buttom>
<img src="" alt="book" class="main-img" id="main-img">
<button class="right-arrow" id="right-arrow">Right</buttom>
<ul class="book-list id="book-list">
<?php if ($total_page > 0) : ?>
<?php foreach ($results as $row) : ?>
<li class="book p-2">
<span class="page-number"><?php echo $page_num++ ?></span>
<img src="<?php echo PAGE_URL . "/" . $b_id . "/" . $row->page_name ?>" alt="Book Image">
</li>
<?php endforeach ?>
<?php endif ?>
</ul>
JavaScript
<script type="text/javascript">
var bookPageList = $('#book-list');
$(bookPageList).click(displayImage);
function displayImage(e) {
if (e.target !== e.currentTarget) {
var target = e.target;
var src = target.src;
// console.log(src);
$('#main-img').attr('src', src);
}
}
</script>
I have fixed this issue in this link, hope this help to other newbies
Change image by selecting from thumbnail or next prev buttons

Show more posts in Wordpress sidebar (like YouTube)

I am trying to create a YouTube Esque sidebar 'Show More' button.
The posts from the same category are displayed in my template sidebar using the following code:
<div class="sidebar-left">
<div class="grid-container">
<?php
global $post;
$category = get_the_category($post->ID);
$current_cat = $category[0]->cat_name;
$my_query = new WP_Query('category_name='.$current_cat.'&showposts=10');
while ($my_query->have_posts()) : $my_query->the_post(); ?>
<a href="<?php the_permalink(); ?>">
<div class="grid-item-meta">
<span><?php echo $entry_cats; ?></span>
<h3><?php the_title(); ?></h3>
<h5>Written by <?php echo get_the_author(); ?></h5>
</div>
</a>
<?php endwhile;
wp_reset_postdata();
?>
</div>
</div>
Is it possible to limit this query / offset it and fetch more on clicking a 'Show More' button. Once show more has been toggled I need to change it to 'Show Less'. I'm quite happy pulling all posts in one query and hiding them on the front end (i'm not too concerned with getting into complex AJAX).
Limiting the height of the div could cut off a post in the middle. Seems there is lots of info / answers on loading more mosts via AJAX or loading a post in a particular div, however not a simple show and hide scenario like I'm after. Many thanks in advance.
If you don't mind loading all the posts you could use some jQuery to get that effect. Check out the CodePen link.
https://codepen.io/pen/QvOpGK
declare at which point you will hide posts, 4 will be the first post we hide
#posts div:nth-child(n + 4) {
display: none;
}
Then use jQuery to show posts on click, I'm adding a class show that gives a display: block;
//We need to tell jQuery which posts to show in hiddenPosts
var hiddenPosts = $('#posts div:nth-child(n + 4)');
var button = $('#showMore');
$(button).click(function() {
hiddenPosts.toggleClass( 'show' );
//change button's text
if (button.text() == "Show More") {
button.text("Show Less");
} else {
button.text("Show More");
}
});

Refresh to show new/random taxonomy

I have an area on my Wordpress theme where I am showing info about a random taxonomy. Basically, the taxonomy is "playwrights" and I am featuring a random one on the home page. Here is the HTML:
<div id="home-top-right">
<?php
$allpw = get_terms( 'playwrights', 'hide_empty=0' );
$randpw = $allpw[ array_rand( $allpw ) ];
$randpw = get_term($randpw->term_id, 'playwrights');
$pwlink = get_term_link($randpw->term_id, 'playwrights');
?>
<div class="title">
Playwright Spotlight
<li class="fa fa-refresh refresh"></li>
</div>
<div class="content" id="p-spotlight">
<?php if (get_field('image', 'playwrights_'.$randpw->term_id)) { ?>
<div class="thumb">
<?php $imageid = get_field('image', 'playwrights_'.$randpw->term_id); ?>
<a href="<?php echo $pwlink; ?>">
<?php echo wp_get_attachment_image($imageid, 'pwthumb'); ?>
</a>
</div>
<?php } ?>
<div class="text">
<div class="sub-title">
<?php echo $randpw->name; ?>
</div>
<?php echo print_excerpt('', '200'); ?>
</div>
</div>
</div>
I want to be able to click a button (in the code, it is the <i> tag) and reload just that section (not the whole page) with a new random taxonomy term (playwright). I'm not great at JS/jquery and I'm not able to find a tutorial online that gets me where I need to go, especially considering the exchange between post data and the js function.
How should I go about this?
By default, WordPress has an admin-ajax.php file which you can send AJAX calls to. You can create a hook that is linked to your own custom function in which you can do the stuff you want, like getting the random term and send it back to the client.
Then you can pass a value to your AJAX call, called 'action'. When admin-ajax.php is getting a POST request with the action you 'hooked', your custom function is being executed.
Have a look at the links below for a more detailed explanation:
http://premium.wpmudev.org/blog/how-to-use-ajax-with-php-on-your-wp-site-without-a-plugin/
http://codex.wordpress.org/AJAX_in_Plugins

Categories