How to get Href Text from PHP loop in Jquery - javascript

I am displaying anchor tag in php loop. Now I am trying to get text of these anchor tags which is coming from PHP loop in Jquery but I am getting the wrong Result. Check the Screen Shots Below...
Anchor Tags
Wrong Result That I am getting
Now when I click on any link Like Baby Food Or Baby Furniture Or any other link then I am getting the text of all Anchor Tags instead of specific anchor tag which is clicked. For Example when I click on Baby Food then I want Just Baby Food to be displayed not all Anchor Tag Text. Please Help me. Below is my code
PHP
<h4>Related Category</h4>
<?php foreach($grouped_with_count as $relatedCat) { ?>
<b> <?php echo $relatedCat['industry']; ?> </b>
<li> <?php echo $relatedCat['product_type']; ?> (<?php echo $relatedCat['count'];?>) </li>
<br />
<?php } ?>
Jquery
function RelatedCatLink(){
var href = $('.GetHref').text();
console.log(href);
//alert($('.GetHref').attr('href'));
}
Please help me out. Thanks in advance..

Problem in your code
You are using class for selection. There will be multiple <a> with the same class.
Solution
Pass the element along with your function call
HTML
<?php echo $relatedCat['product_type']; ?> (<?php echo $relatedCat['count'];?>) </li>
JS
function RelatedCatLink(elem){
var href = $(elem).text();
}
Working Demo
function RelatedCatLink(elem){
var href = $(elem).text();
alert(href);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<li> 1 </li>
<li> 2 </li>
<li> 3 </li>
<li> 4 </li>

//PHP CODE
<h4>Related Category</h4>
<?php foreach($grouped_with_count as $relatedCat) { ?>
<b> <?php echo $relatedCat['industry']; ?> </b>
<li> <?php echo $relatedCat['product_type']; ?> (<?php echo $relatedCat['count'];?>) </li>
<br />
<?php } ?>
//JQUERY CODE
function RelatedCatLink(id){
var href = $('#GetHref-'+id).text();
console.log(href);
}

Related

how to make a dynamic sidebar active on a clicking

I'm creating dynamic menu. I wanted to highlight the menu once it is selected.
We use php. just need to figure out how to append the class active to the current page. Can anyone help me with this?
<div id="sidebar-wrapper" class="sidebar-toggle">
<ul class="sidebar-nav">
<?php
$i=1;
if(count($shipments) > 0)
{
foreach($shipments as $row)
{
$shipment_id = $row['id'];
$containerdest = $row['no']."-".$row['destination'];
?>
<li id="shipment<?php echo $shipment_id; ?>"><?php echo $containerdest; ?>
</li>
<?php $i++;
}
} ?>
<li>
Logout
</li>
</ul>
</div>
</div>
Change your html line with below line
<li id="shipment<?php echo $shipment_id; ?>" class="menu"><a href="<?php echo ite_url("users/get_details/$shipment_id");?>" shipmentid="<?php echo $shipment_id; ?>" ><?php echo $containerdest; ?></a>
And write javascript code as below (assuming you have included jquery library file)
<script>
$(document).ready(function(){
var url = location.pathname;
var arr = mystr.split("/");
var id = arr[2];
$(#shipment'+id).attr('shipmentid');
$('.menu').removeClass('active'); //this will remove all active class after page loading
$('#shipment'+id).addClass('active'); // this will append active class to the current clicked menu
});
</script>

Hide menu item according to user account

On my login mysql table, i have an account type column. If the user has a Manager account type, i want to show a management menu item and if not hide it.
This is pretty simple but its not working:
In my header, i have the following:
<script>
var logged_in_account_type = "<?php echo $_SESSION['account_type'] ; ?>";
if(logged_in_account_type === "Manager") {
document.getElementById('management_menu').style.display = 'block';
} else {
document.getElementById('management_menu').style.display = 'none';
}
</script>
I tried without the echo has well.
<div id="management_menu" style="display:none">
<li>
<i class="menu-icon fa fa-dashboard"></i><span class="mm-text">Dashboard</span>
</li>
</div>
<div class="text-bg"><span class="text-slim">Welcome,</span> <span class="text-semibold"><?php echo $_SESSION['account_type'] ?></span></div>
Have you tried using php if while rendering your menu? Something like this:
<?php if($_SESSION['account_type'] == 'Manager'): ?>
<div id="management_menu">
<ul>
<li>
Dashboard
</li>
<li>
Users
</li>
</ul>
</div>
<?php endif; ?>
Where is your javascript code in the document? If your javascript code is on the top of the document, it possibly shows or hides the <div> element properly, but, because the <div> element is at the bottom of the document, it is hidden because its "style" says so.
The solution is to move the javascript code below the <div> element, this will solve the "execution order" problem you have. Example :
<div id="management_menu" style="display:none">
<li>
<i class="menu-icon fa fa-dashboard"></i><span class="mm-text">Dashboard</span>
</li>
</div>
<?php
session_start();
$_SESSION['account_type'] = "Manager";
?>
<script>
var logged_in_account_type = "<?php echo $_SESSION['account_type'] ; ?>";
if(logged_in_account_type === "Manager") {
document.getElementById('management_menu').style.display = 'block';
} else {
document.getElementById('management_menu').style.display = 'none';
}
</script>

<li> not recognising php foreach loop (possibly including JS)

First I realise I'm talking about an external framework but please hear me out as I think it may be more of an html php issue (possibly JS). I am trying to incorporate this horizontal timeline into my web page as a school project:
https://codyhouse.co/gem/horizontal-timeline/
I am trying to print out results I got from an array. I am converting the datetime format to the same that is taken in.
Their method is as follows:
<ol>
<li>16 Jan</li>
<li>28 Feb</li>
<li>20 Mar</li>
<li>20 May</li>
............
</ol>
While mine looks like this:
<ol>
<?php foreach ($mile2[ "milestones"] as $key=>$value) { if ($key != 0) { ?>
<li>
<a href="#0" data-date="<?=date('d/m/Y',strtotime($mile2['milestones'][$key]['start_time']['date']));?>">
<?=d ate( 'd M', strtotime($mile2[ 'milestones'][$key][ 'start_time'][ 'date']));?>
</a>
</li>
<?php } else{ ?>
<li>
<a href="#0" data-date="<?=date('d/m/Y',strtotime($mile2['milestones'][$key]['start_time']['date']));?>" class="selected">
<?=d ate( 'd M', strtotime($mile2[ 'milestones'][$key][ 'start_time'][ 'date']));?>
</a>
</li>
<?php }} ?>
</ol>
The outputs are very different, this is a link to the demo https://codyhouse.co/demo/horizontal-timeline/index.html.
And this is how mine currently appears:
The first Problem I see in your code is that date is declared d ate even though im not shure if that is actually the problem. I suggest to var_dump() the contents of your array to rule out the possibility of sending in false data to your frontend.
Additionally you can make shure the javascript ist loaded after the DOM is done loading by using jQuery $(function()) as the javascript might trigger before your html is fully loaded.
Here some optimized code:
<ol>
<?php foreach ($mile2["milestones"] as $key => $value) : ?>
<?php if ($key != 0): ?>
<li>
<a href="#0"
data-date="<?= date('d/m/Y', strtotime($value['start_time']['date'])); ?>"
><?= date('d M', strtotime($value['start_time']['date'])); ?></a>
</li>
<?php else: ?>
<li>
<a href="#0"
data-date="<?= date('d/m/Y', strtotime($value['start_time']['date'])); ?>"
class="selected"
><?= date('d M', strtotime($value['start_time']['date'])); ?></a>
</li>
<?php endif; ?>
<?php endforeach; ?>
</ol>

Passing the ID of clicked link to PHP code without reloading the page

I am trying to pass the ID of a clicked link to PHP code without reloading the page.
Currently, I am using the following code to pass the ID in the href attribute in the tag:
<?php
$sql="select * from category";
$execute=mysql_query($sql);
while($row=mysql_fetch_assoc($execute)){ ?>
<li><?php echo $row['category'] ; ?></li>
<?php
}
?>
</ul>
</div>
<div id="waxing" style="display:none">
<h2 id="cat_price" style="color:#f5c658">Price Category Waxing</h2>
<ul class="ul1">
<?php
function sub() {
if(isset($_GET['did']))
{
$id=$_GET['did'];
$sql="select * from midcat where cid=$id";
$execute=mysql_query($sql);
if(mysql_num_rows($execute)>0){
while($row=mysql_fetch_assoc($execute)){
?>
<li><a href="#" id="wax_normal" ><?php echo $row['midcat']; ?> </a></li>
<?php
}
}
}
}
sub();
?>
Is it possible to do the same thing without reloading the page?
As I mentioned, you will want to use AJAX to fetch your other list. I will demonstrate and notate. I am using jQuery because I am familiar with it and I find it easy to use. Traditional javascript AJAX will work just as well:
page1.php (whatever this page is called)
Add jQuery libraries in the <head>:
<script type="text/javascript" src="https://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript" src="https://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
Change this line, it doesn't need to be a link, I like to use the data attribute:
<li data-id="<?php echo $row['id']; ?>"><?php echo $row['category'] ; ?></li>
On this same page add the ajax:
<script>
// When the page finishes loading
$(document).ready(function() {
// When the user clicks any <li>, activate script
$("li").click(function() {
// Assign the value of the data attribute
var thisBtn = $(this).data('id');
// If an <li> doesn't have this attribute, stop
if(thisBtn == undefined)
return false;
// Start the ajax
$.ajax({
// Where to send request
url: 'ajax.index.php',
// What to send
data: { did: thisBtn },
// How to send
type: 'post',
// What to do when request succeeds
success: function(response) {
// Save the contents of the response into
// whatever has the id="list"
$("#list").html(response);
}
});
});
});
</script>
Place a drop spot where you want your list to show up on this page:
<!-- this is where ajax will drop the list on your page -->
<span id="list"></span>
Create a new page and put the <ul>, function, execution of function on this new page
ajax.index.php
<?php
function sub()
{
// In the ajax, I told it to use $_POST, so change to
// post instead of get
if(isset($_POST['did'])) {
$id=$_POST['did'];
// Don't do this anymore.............vvv
$sql="select * from midcat where cid=$id";
// Don't use mysql_ anymore
$execute=mysql_query($sql);
if(mysql_num_rows($execute)>0){
while($row=mysql_fetch_assoc($execute)){
?>
<li><a href="#" id="wax_normal" ><?php echo $row['midcat']; ?> </a></li>
<?php
}
}
}
}
?>
<ul class="ul1">
<?php sub().PHP_EOL; ?>
</ul>
if you don't want to refresh page you have to use AJAX:
https://developer.mozilla.org/en-US/docs/AJAX
on your javascript onclick event pass your id and replace href attribute value with a hashtag. like this:
<?php echo $row['category'] ; ?>
Now send an ajax request in show function. and use the response.

Make a child div visible on click

Edit my code to make it work please.
Edited for latest version.
Here is what I have:
<body>
<!-- visibility toggle -->
<script type="text/javascript">
<!--
function toggle_visibility()
{
if(document.getElementById(window.event.srcElement.id+'menu').style.display=='block'){
document.getElementById(window.event.srcElement.id+'menu').style.display='none';
}
else{
document.getElementById(window.event.srcElement.id+'menu').style.display='block';
}
};
//-->
</script>
Here are my divs (edited to show exactly what I have)
<ul class="lyrics"><h3>ALL LYRICS</h3>
<?php while ( have_posts() ) : the_post(); ?>
<li ><a id="links" href="#" onclick="toggle_visibility();"><?php the_title(); ?></a>
<div id="linksmenu"><?php the_content();?></div>
</li>
<?php endwhile; // End the loop. Whew. ?>
</ul>
Here is what happens:
Regardless which link I click on, only the text associated with the very last "the_content" displays.
Here is what I need:
Initially all the "child" divs are not visible.
When I click on "Title 1" link, the "Child text 1" will become visible.
When I click on "Title 2" link, the "Child text 2" will become visible and the "Child text 1" will become not visible.
This is going to be in a WordPress blog so the number of Title divs will change. There will always be only one child.
Thanks in advance!
the reason why your first div is toggled no matter where you click, is because you use the hard-coded id foo. Pass this to toggle_visibility instead of the literal 'foo' and inside toggle_visibility function find the div that you want to toggle (this is going to be the first child of the passed parameter).
It is doing this because you are calling the_content() twice. I am assuming your file looks like:
<?php get_header();
if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<ul>
<li class="main"><?php the_title(); ?> <div class="child"><?php the_content(); ?></div> </li>
<li class="main"><?php the_title(); ?> <div class="child"><?php the_content(); ?></div> </li> <ul>
<?php endwhile; else: ?>
<p><?php _e('Sorry, no posts matched your criteria.'); ?></p>
<?php endif; ?>
You need to have two loops, but I can't supply detail without seeing more code. Read about multiple loops.
Throw the parameter away and build the id you want to set visible/invisible using the id of the element which triggers the event.
function toggle_visibility()
{
if(document.getElementById(window.event.srcElement.id+'menu').style.display=='block'){
document.getElementById(window.event.srcElement.id+'menu').style.display='none';
}
else{
document.getElementById(window.event.srcElement.id+'menu').style.display='block';
}
};
And as long as the thing you want to show always has a id+'menu' or whatever, you can show it with the function. (notice that the parent has id links and the child has id linksmenu )
<ul class="lyrics"><h3>ALL LYRICS</h3>
<?php while ( have_posts() ) : the_post(); ?>
<li ><a id="links" href="#" onclick="toggle_visibility();"><?php the_title(); ?></a>
<div id="linksmenu"><?php the_content();?></div>
</li>
<?php endwhile; // End the loop. Whew. ?>
</ul>

Categories

Resources