mcheah
mcheah

Reputation: 1326

How do I use php functions in javascript?

Situation: I'm building a Wordpress Site. Menu becomes 'fixed' to the top of the page when scrolling down the page (http://deerfielddesigns.com.mlseo.net/). When i am logged into wordpress, the dashboard admin bar cover the menu. I wanted to create a different class for the menu when I am logged in as opposed to when I am logged out.

Code:

    if ( direction === 'down' ) {

        $('#main-header').addClass( 'et-fixed-header' );
    } else {
        $('#main-header').removeClass( 'et-fixed-header' );
    }

I wanted to insert an "if ( is_user_logged_in() )" statement in there to change the class output but I don't really understand too much about javascript and if it plays nice with php. Does anyone have any insight as to what i need to do to make this work? Thanks all!

Upvotes: 0

Views: 98

Answers (5)

rusben
rusben

Reputation: 646

If you write inline javascript in your php files you can do this:

<?php  // some php code ?>

<script type="text/javascript">

<?php if ( is_user_logged_in() ) { ?>
    // Place some javascript here
<?php } else { ?>
    // Place some javascript here
<?php ?>

</script>

<?php  // some php code ?>

Upvotes: 0

Sam Dufel
Sam Dufel

Reputation: 17598

The simple way to identify from you javascript if a user is logged in is to populate a javascript variable with their status. In your theme's header.php, add:

<script type="text/javascript">
    var is_logged_in = <?php echo json_encode(is_user_logged_in()) ?>;
</script>

Then, in your javascript elsewhere, you can use:

if (is_logged_in) {
   //....
}

Upvotes: 0

Ohgodwhy
Ohgodwhy

Reputation: 50787

if this is not an AJAX driven login system, simply open your header.php file and perform the following

$the_class = is_user_logged_in() ? 'logged-in-class' : 'logged-out-class';

Then find your main-header and do what's required.

<header id="main-header" class="<?php echo $the_class;">

If it is an ajax driven login system, you'll need to understand how to work with wordpress' add_action, but that is an answer for an entirely different question.

Upvotes: 1

John3136
John3136

Reputation: 29265

PHP is a server side language (which quite likely is generating Javascript). Javascript is in the browser.

The short answer is "You can't easily call PHP from JS".

Upvotes: 0

user2672373
user2672373

Reputation:

Make an ajax request to the required php function whenever required. You may use ajax features of various JS libraries like jQuery, YUI etc. to do so.

Upvotes: 0

Related Questions