Home » Php » How to access PHP variables in JavaScript or jQuery rather than <?php echo $variable ?>

How to access PHP variables in JavaScript or jQuery rather than <?php echo $variable ?>

Posted by: admin April 23, 2020 Leave a comment


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?

How to&Answers:

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:

    $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); ?>;

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.


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

$var = array(
    'qwe' => 'asd',
    'asd' => array(
        1 => 2,
        3 => 4,
    'zxc' => 0,
<script>var data = <?php echo json_encode($var); ?>;</script>


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


… 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.


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.


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.


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:

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

Inside functions.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.

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

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

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


            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.