How to access a php variable into external .js(my.js) file - javascript

How can I gain access to a PHP variable from an external javascript (my.js) file? I want to get the dynamic id or class into external js file
PHP
<div id="tabs<?php echo str_replace(' ', '',$child1['id']); ?>" class="<?php echo $activetab1; ?> tab-pane">
<?php if ($child1['children1']) { $category2=$child1['children1']; ?>
<ul class="tabs<?php echo str_replace(' ', '',$child1['id']); ?>" id="tabs<?php echo str_replace(' ', '',$child1['id']); ?>" data-count="15">
<?php foreach ($category2 as $child2) { ?>
<li>
<?php echo $child2['name']."------------main"; ?>
</li>
<?php if ($child2['children9']) { $category9=$child2['children9']; ?>
<?php foreach ($category9 as $child9) { ?>
<li>
<?php echo $child9['name']; ?>
<?php echo str_replace(' ', '',$child1['id']); ?>
</li>
<?php } } ?>
<?php } ?>
</ul>
<?php } ?>
</div>
External JavaScript
var container = $("ul.tabs25"),
count = container.data("count"),
column;
container.children().each(function(index) {
if (index % count == 0)
column = $("<li/>").css({"float": "left", "margin-right": "50px"}).appendTo(container);
var hello=$(this).appendTo(column);
console.log(hello);
});
I want to dynamically change this $child1['id'] within JavaScript.

You can access data from php script in Javascript (I'll use jQuery here) like this
Create input hidden field within you php file like this
<input type="hidden" id="myPhpValue" value="<?php echo $myPhpValue ?>" />
in your javascript file:
var myPhpValue = $("#myPhpValue").val();
//From here you can the whaterver you like with you js Value
if(myPhpValue != ''){
//Do something here
}
This will do the job

A simple way to do this is to create an inline script with PHP. Something like:
<script type="text/javascript">
var myid=<?php echo str_replace(' ', '',$child1['id']); ?>;
</script>
This way myid is included in the html output of PHP.

Related

Enable javascript within multiple if's?

I have a few if conditions in the following PHP.
I can't enable the Javascript section which needs to hide the class when the cart "quantity" is more than the balance.
jimport( 'joomla.user.helper' );
$user = JFactory::getUser();
$groups = $user->get('groups');
if(in_array(15, $groups)) {
$carts= VirtueMartCart::getCart();
foreach($carts->cartProductsData as $cartItem)
{
if($cartItem['virtuemart_product_id'] == $product->virtuemart_product_id){
echo "<br /> ".$cartItem['quantity']." already added to cart";
}
if($cartItem['quantity'] == $max_balance) <?php { ?>
<script type="text/javascript">
$('.addtocart-button').attr('disabled', 'disabled');
</script>
<?php } ?>
} }
I don't know how to close the first php instance. It refuses.
You cannot use <?php ... ?> in side <?php ... ?>, this is incorrect syntax.
Use the following:
<?php
jimport('joomla.user.helper');
$user = JFactory::getUser();
$groups = $user->get('groups');
if (in_array(15, $groups)):
$carts = VirtueMartCart::getCart();
foreach ($carts->cartProductsData as $cartItem):
if ($cartItem['virtuemart_product_id'] == $product->virtuemart_product_id)
{
echo "<br /> " . $cartItem['quantity'] . " already added to cart";
}
if ($cartItem['quantity'] == $max_balance):
?>
<script type="text/javascript">
$('.addtocart-button').attr('disabled', 'disabled');
</script>
<?php
endif;
endforeach;
endif;
This uses Alternative Syntax which is a preferred method when nesting PHP code in HTML blocks.
You have a bit of a mess inside your php code.
I find using the if () : endif; notation is more readable when dealing with php+html
<?php
jimport( 'joomla.user.helper' );
$user = JFactory::getUser();
$groups = $user->get('groups');
?>
<?php if(in_array(15, $groups)): ?>
<?php foreach(VirtueMartCart::getCart()->cartProductsData as $cartItem): ?>
<?php if($cartItem['virtuemart_product_id'] == $product->virtuemart_product_id): ?>
<br /><?php echo $cartItem['quantity']; ?> already added to cart";
<?php endif; ?>
<?php if($cartItem['quantity'] == $max_balance): ?>
<script type="text/javascript">
$('.addtocart-button').attr('disabled', 'disabled');
</script>
<?php endif; ?>
<?php endforeach; ?>
<?php endif; ?>

OwlCarousel2 cannot get jquery to work

I'm doing an slider image by using the plugin OwlCarousel2
I have added the JavaScript and CSS files that they provide on the website.
I'm also setup this on WordPress custom theme. I having a hard time trying to figure out how to setup my own custom Jquery.
Custom animation
jQuery(document).ready(function() {
$(document).ready(function(){
$('.owl-carousel').owlCarousel();
Boolean: false,
Number: 10
});
});
Wordpress Slider Image with Advanced Custom Gallery/Checkbox Fields
<?php $images = get_field('image_carousel'); ?>
<?php $activate_carousel_array = get_field( 'activate_carousel' ); ?>
<?php if( $images ): ?>
<?php if ( $activate_carousel_array ):
foreach ( $activate_carousel_array as $activate_carousel_item ):
echo $activate_carousel_item; ?>
<?php
$images = get_field('image_carousel');
if( $images ): ?>
<div id="hero">
<div class="slider owl-carousel owl-theme">
<?php foreach( $images as $image ): ?>
<div><img src="<?php echo $image['sizes']['large']; ?>" alt="<?php echo $image['alt']; ?>" /></div>
<?php endforeach; ?></div>
</div>
<?php endif; ?>
<?php endforeach; ?>
<?php endif; ?>
<?php endif; ?>
In your code you use
jQuery(document).ready(function() and
$(document).ready(function()
remove one of them.

Magento Product pag - displaying related products that are out of stock

I'm not too experienced in PHP but my goal here is to have related product swatches not display on the page if they are out of stock.(highlighted in screenshot)
Related product swatches are highlighted
Here is the PHP code:
<ol class="mini-products-list" id="block-related">
<?php foreach($this->getItems() as $_item): ?>
<li class="item">
<?php if(!$_item->isComposite() && $_item->isSaleable()): ?>
<?php if (!$_item->getRequiredOptions()): ?>
<input type="checkbox" class="checkbox related-checkbox" id="related-checkbox<?php echo $_item->getId() ?>" name="related_products[]" value="<?php echo $_item->getId() ?>" />
<?php endif; ?>
<?php endif; ?>
<div class="product">
<img src="<?php echo $this->helper('catalog/image')->init($_item, 'thumbnail')->resize(50) ?>" width="50" height="50" alt="<?php echo $this->escapeHtml($_item->getName()) ?>" />
<div class="product-details">
<p class="product-name"><?php echo $this->escapeHtml($_item->getName()) ?></p>
<?php echo $this->getPriceHtml($_item, true, '-related') ?>
<?php if ($this->helper('wishlist')->isAllow()) : ?>
<?php echo $this->__('Add to Wishlist') ?>
<?php endif; ?>
</div>
</div>
</li>
<?php endforeach ?>
</ol>
And here is the related jQuery/JS:
<script type="text/javascript">
//<![CDATA[
$$('.related-checkbox').each(function(elem){
Event.observe(elem, 'click', addRelatedToProduct)
});
var relatedProductsCheckFlag = false;
function selectAllRelated(txt){
if (relatedProductsCheckFlag == false) {
$$('.related-checkbox').each(function(elem){
elem.checked = true;
});
relatedProductsCheckFlag = true;
txt.innerHTML="<?php echo $this->__('unselect all') ?>";
} else {
$$('.related-checkbox').each(function(elem){
elem.checked = false;
});
relatedProductsCheckFlag = false;
txt.innerHTML="<?php echo $this->__('select all') ?>";
}
addRelatedToProduct();
}
function addRelatedToProduct(){
var checkboxes = $$('.related-checkbox');
var values = [];
for(var i=0;i<checkboxes.length;i++){
if(checkboxes[i].checked) values.push(checkboxes[i].value);
}
if($('related-products-field')){
$('related-products-field').value = values.join(',');
}
}
//]]>
</script>
Any help would be appreciated, thank you!
Are you sure that you have the option Display out of stock products set to No? (System -> Configuration -> Inventory)
You can also try to add $_item->isAvailable() to if statement.
The Solution I ended up going with: adding $_item->isAvailable() to if statement gives the desired effect of related products that are out of stock will not display as a related product swatch on the product page.

how to get value from php loop to div

i want to change div value when clicking php while loop.,
My php code
<?php $query = mysql_query("select * from tbl_sub_product where product_id='$id'");
while($row=mysql_fetch_array($query))
{ ?>
<div><a href="#" class="showElement" id="showElement" >
<?php echo $row['name']; ?><?php echo $row['id']; ?></a></div>
<?php } ?>
my query was
<script type="text/javascript" charset="utf-8">
$(document).ready(function(){
var $target = $('#target');
$(".showElement").click( function(e) {
e.preventDefault();
$target.append( $(this).text() );
});
});
</script>
i want the result in this div
<div id="target">user Id:<php echo $id ?>User Nmae:<?php echo $name ?>user designation :<?php echo $designation ?></div>
what changes i want to do my code for getting data in my second div
You're asking to take the mysql data from php and magically know what it is without querying again with AJAX or some other request.
There are many ways you can do this, but the simplest is to store the exact view of what you want in a child div below the a tag.
You need to change to prepared statements too.... If you don't want to fine just change the stmt stuff back to what you have and row will do what you want.
<style>
.hidden{
display: none;
}
</style>
<?php
$stmt = mysqli_prepare("select * from tbl_sub_product where product_id='$id'");
$stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_assoc()){
?>
<div>
<a href="#" class="showElement" >
<?php echo $row['name']; ?> <?php echo $row['id']; ?>
</a>
<div class="hidden getTarget">
user id: <php echo $row['id']; ?>
User name: <?php echo $row['name']; ?>
user designation: <?php echo $row['designation']; ?>
</div>
</div>
<?php
}
?>
<script>
$(document).ready(function(){
var $target = $('#target');
$(".showElement").click( function(e) {
e.preventDefault();
$target.append( $(this).parent().find('.getTarget').text() );
});
});
</script>
Don't use ids in a loop. Unless you have a specific identifier to separate each one.
Don't copy and paste as well.. please read the code and understand it.

Lighbox only showing data of the current post in Wordpress

I wanted to show some lightbox funtionality with the use of shortcodes. The code is working fine except for the data shown in the ligthbox. It only shows the data from the latest post in the loop. How can i manage to get lightbox showing the data belonging to the post?
<?php
// Posts are found
if ( $posts->have_posts() ) {
while ( $posts->have_posts() ) :
$posts->the_post();
global $post;
?>
<center>
<div id="su-post-<?php the_ID(); ?>" class="su-post">
<?php if ( has_post_thumbnail() ) : ?>
<a class="su-post-thumbnail" href="<?php the_permalink(); ?>"><?php the_post_thumbnail(); ?></a>
<?php endif; ?>
<div class="su-post-excerpt">
<!-- Shows the button and the hidden lightbox -->
<?php echo do_shortcode ('[su_lightbox type="inline" src="#showInfo"][su_button] Info[/su_button][/su_lightbox]'); ?>
<!-- Shows the lightbox if button is clicked with the data -->
<?php echo do_shortcode ('[su_lightbox_content id="showInfo"][su_meta key="info" default="Geen tekst"][/su_lightbox_content]'); ?>
<?php echo do_shortcode ('[su_lightbox type="inline" src="#showVideo"][su_button] Video[/su_button][/su_lightbox]'); ?>
<?php echo do_shortcode ('[su_lightbox_content id="showVideo"][su_video url="{su_meta key=video}"][/su_lightbox_content]'); ?>
<?php echo do_shortcode ('[su_lightbox type="inline" src="#showFoto"][su_button] Foto[/su_button][/su_lightbox]'); ?>
<?php echo do_shortcode ('[su_lightbox_content id="showFoto"][su_meta key="fotos" default="Geen fotos"][/su_lightbox_content]'); ?>
</div>
</div>
</center>
<?php
endwhile; echo do_shortcode ('[su_lightbox_content id="showInfo"][su_meta key="info" default="Geen tekst"][/su_lightbox_content]');
}
// Posts not found
else {
echo '<h4>' . __( 'Posts not found', 'shortcodes-ultimate' ) . '</h4>';
}
?>
By adding a counter in the while loop and using the variable in the shortcode SRC and ID fields. I needed unique ID's for each post.
$n = 0; /* Outside While Loop */
echo do_shortcode( '[su_lightbox type="inline" src="#showInfo'.$n.'"][su_button] Info[/su_button][/su_lightbox] ');
echo do_shortcode( '[su_lightbox_content id="showInfo'.$n.'"][su_meta key="info" default="Geen tekst"][/su_lightbox_content]' );
$n++; /* Inside While Loop */

Categories