Hướng dẫn jquery get variable php

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

Nội dung chính

  • How set PHP variable value in jquery?
  • Can I use PHP variable in JavaScript?
  • Can we write PHP in jquery?
  • Can PHP and JavaScript share variables?

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.

Hello @kartik,

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. 

Hope this works!!

To know more about Java, It's recommended to join our Java Training in Chennai today.

Thank You!!

Hi Guys,

In this post, we will learn how to access php variable in jquery with small example. We always require to get php array variable or data variable in javascript.

If you have simple string value store on php variable and you require to get in jquery then you can do it easily by using echo of php. But if you need to get array variable then you have to do it using json_encode.

So, just see bellow example and learn how it works:

Example:

<!DOCTYPE html>

<html>

<head>

<title>How to pass PHP variables in JavaScript or jQuery? - HDTuto.com</title>

</head>

<body>

<?php

$simple = 'demo text string';

$complexArray = array('demo', 'text', array('foo', 'bar'));

?>

<script type="text/javascript">

var simple = '<?php echo $simple; ?>';

console.log(simple);

var complexArray = <?php echo json_encode($complexArray); ?>;

console.log(complexArray);

</script>

</body>

</html>

I hope it works for you...

Posted 6 years ago By 247784

In this post, I will tell you how to access PHP variables in JavaScript or jQuery.

Most of the time you will need to access php variables inside jquery or javascript.

If you have simple string value then you can echo this in javascript directly but if you have array type of value and you want to get it in javascript then you have to use json encode method.

See the example below :

  1. <?php
  2. $simple = 'demo text string';
  3. $complex = array('demo', 'text', array('foo', 'bar'));
  4. ?>
  5. <script type="text/javascript">
  6. var simple = '<?php echo $simple; ?>';
  7. console.log(simple);
  8. var complex = <?php echo json_encode($complex); ?>;
  9. console.log(complex);
  10. </script>

This code will work in php file.

How set PHP variable value in jquery?

If at all you want to send php value to php page using jquery and ajax, then first of all, create input text with type hidden. put your php value in it. and when you click then get that value from that input type hidden in jquery and then pass it to whichever page you want.

Can I use PHP variable in JavaScript?

Inside the JavaScript, we can use the PHP tag to echo the PHP variable assigning it to a JavaScript variable. For example, assign a value Metallica to a variable $var inside the PHP tags. Write a script tag and inside it, write a PHP tag. Inside the PHP tag, echo a JavaScript variable jsvar .

Can we write PHP in jquery?

Sure, as long as you keep in mind that PHP code will be executed by the server before the page is sent out.

JavaScript is the client side and PHP is the server side script language. The way to pass a JavaScript variable to PHP is through a request. This type of URL is only visible if we use the GET action, the POST action hides the information in the URL.