4

This question already has an answer here:

This is my phtml file ....

    <?php 
$currentCategory = $block->getCurrentCategory();

//echo $currentCategory;
?>

I want to set $currentCategory value in js file and display in alert ...How to set it in js file?

marked as duplicate by Siarhey Uchukhlebau, Fabian Schmengler, Moose, Rakesh Jesadiya, liyakat May 6 '17 at 16:19

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

4

You can simple use echo in js for print or pass php variables

require(['jquery', 'jquery/ui'], function($){ 

    var yourvariable = <?php echo $currentCategory; ?>

    alert(yourvariable);

 });

If you have diffrent file for phtml and js you can try 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
}
  • 2
    phtml and js file both are different....js code is not used in phtml file... it is separate file.. – Rohan Hapani May 5 '17 at 5:34
  • 1
    Refer my updated answer. if you have diffrent file for phtm and js – Prince Patel May 5 '17 at 5:43
  • Cool.....It's working for me... Thanks @Prince Patel :) – Rohan Hapani May 5 '17 at 5:58
  • @RohanHapani Although this will work it is not following best practices. – Ben Crook May 9 '17 at 16:12
  • I'm currently writing one, hopefully I have time to finish it. – Ben Crook May 9 '17 at 16:17
4

Pass with Div id you will get the value in js file.

Try below code :

Your phtml file should be :

<?php 
$currentCategory = $block->getCurrentCategory();
?>
<?php if(isset($currentCategory) && $currentCategory !== "")
      {
?>
<div id="currentCategory"><?php $currentCategory ?></div>
<?php } ?>

Your js file should be :

require(['jquery', 'jquery/ui'], function($){ 

    var categoryvalue = $("#currentCategory").val();
    alert(categoryvalue);

 });
  • 1
    Happy To help !!! keep helping :) – Manthan Dave May 5 '17 at 6:00

Not the answer you're looking for? Browse other questions tagged or ask your own question.