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?
This question is related to
php
javascript
jquery
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.
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 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.
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.
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>
Source: Stackoverflow.com