63

How do I access PHP variables in JavaScript or jQuery? Do I have to write

<?php echo $variable1 ?>
<?php echo $variable2 ?>
<?php echo $variable3 ?>
...
<?php echo $variablen ?>

I know I can store some variables in cookies, and access these values via cookies, but values in cookies are relatively stable values. Moreover, there is a limit, you can not store many values in cookies, and the method is not that convenient. Is there a better way to do it?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Steven
  • 24,410
  • 42
  • 108
  • 130
  • 3
    if you are going to mark things as 'dups' post links to those threads, otherwise its just postcount ++. – whispers Jun 23 '15 at 20:47

6 Answers6

161

Your example shows the most simple way of passing PHP variables to JavaScript. You can also use json_encode for more complex things like arrays:

<?php
    $simple = 'simple string';
    $complex = array('more', 'complex', 'object', array('foo', 'bar'));
?>
<script type="text/javascript">
    var simple = '<?php echo $simple; ?>';
    var complex = <?php echo json_encode($complex); ?>;
</script>

Other than that, if you really want to "interact" between PHP and JavaScript you should use Ajax.

Using cookies for this is a very unsafe and unreliable way, as they are stored clientside and therefore open for any manipulation or won't even get accepted/saved. Don't use them for this type of interaction. jQuery.ajax is a good start IMHO.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Karsten
  • 14,572
  • 5
  • 30
  • 35
6

If AJAX isn't an option you can use nested data structures to simplify.

<?php
$var = array(
    'qwe' => 'asd',
    'asd' => array(
        1 => 2,
        3 => 4,
    ),
    'zxc' => 0,
);
?>
<script>var data = <?php echo json_encode($var); ?>;</script>
Bram Vanroy
  • 27,032
  • 24
  • 137
  • 239
stroncium
  • 1,430
  • 9
  • 8
3

You're asking kind of a two-part question. As far as syntax (I think since PHP4?) you can use:

<?=$var?>

... if PHP is configured to allow it. And it is on most servers.

As far as storing user data, you also have the option of storing it in the session:

$_SESSION['bla'] = "so-and-so";

for persistence from page to page. You could also of course use a database. You can even have PHP store the session variables in the db. It just depends on what you need.

Greg
  • 7,782
  • 7
  • 43
  • 69
  • 1
    As you say, this syntax is configured on *most* servers, but not all. For truly portable code, I'd still recommend using the full – ZombieSheep Nov 27 '09 at 11:13
  • you don't have access to $_SESSION inside javascript – Karsten Nov 27 '09 at 11:16
  • @Karsten: I wasn't suggesting that you do. I was just suggesting using session variables instead of cookies, when cookies aren't necessary. You would still have to echo them inside your script, of course. – Greg Nov 27 '09 at 11:43
2

I ran into a similar issue when building a custom pagination for a site I am working on.

The global variable I created in functions.php was defined and set to 0. I could output this value in my javascript no problem using the method @Karsten outlined above. The issue was with updating the global variable that I initially set to 0 inside the PHP file.

Here is my workaround (hacky? I know!) but after struggling for an hour on a tight deadline the following works:

Inside archive-episodes.php:

<script>
    // We define the variable and update it in a php
    // function defined in functions.php
    var totalPageCount; 
</script>

Inside functions.php

<?php
    $totalPageCount = WP_Query->max_num_pages; // In my testing scenario this number is 8.
    echo '<script>totalPageCount = $totalPageCount;</script>';
?>

To keep it simple, I was outputting the totalPageCount variable in an $ajax.success callback via alert.

$.ajax({
        url: ajaxurl,
        type: 'POST',
        data: {"action": "infinite_scroll", "page_no": pageNumber, "posts_per_page": numResults},
        beforeSend: function() {
            $(".ajaxLoading").show();
        },
        success: function(data) {
                            //alert("DONE LOADING EPISODES");
            $(".ajaxLoading").hide();

            var $container = $("#episode-container");

            if(firstRun) {
                $container.prepend(data);
                initMasonry($container);
                ieMasonryFix();
                initSearch();
            } else {
                var $newItems = $(data);
                $container.append( $newItems ).isotope( 'appended', $newItems );
            }
            firstRun = false;

            addHoverState();                            
            smartResize();

            alert(totalEpiPageCount); // THIS OUTPUTS THE CORRECT PAGE TOTAL
        }

Be it as it may, I hope this helps others! If anyone has a "less-hacky" version or best-practise example I'm all ears.

  • Please, do rate other users when they make good constructives answers, doesnt matter if they are old or fresh. We are responsible to provide positive feedback on the ones who make a good effort. Even if this didnt help you just voting up means you find this helpful (not always to you) – Mbotet Apr 05 '21 at 17:20
1

Basically, yes. You write alert('<?php echo($phpvariable); ?>');

There are sure other ways to interoperate, but none of which i can think of being as simple (or better) as the above.

miku
  • 181,842
  • 47
  • 306
  • 310
0

I would say echo() ing them directly into the Javascript source code is the most reliable and downward compatible way. Stay with that unless you have a good reason not to.

Pekka
  • 442,112
  • 142
  • 972
  • 1,088
  • 4
    This is a poor answer. It does not utilize and example. Yes, using imbedded PHP to echo a value into a script is a common concept. However, since the user is asking, we can presume that they don't know. Your answer would just be frustrating. It is as un-helpful as some those that say such things as "Yes, I think you can do that", or "It should not be hard". Not trying to be too critical. Just saying we should keep our answers very clear, and provide required details. – Don Briggs Sep 24 '12 at 21:09
  • 5
    @Don Then write a better answer, or refer to the others given that come with plenty of examples. This topic is 3 years old, and has a highly upvoted accepted answer. I don't think there is anything to do here – Pekka Sep 24 '12 at 21:22