简体   繁体   中英

how do i access php variables so that i can work with the values using javascript/ jquery?

Question is on how to work with php variables in a webpage, using javascript/jquery. The following code represents the scenario.

PHP Code Snippet for pagination -

if($current_page>1)
$previous = $current_page - 1;          
else
$previous = $current_page;          

if($current_page==$num_pages)
$next = $current_page;          
else
$next = $current_page + 1;  

//the line below is for right arrow link - go to next page
<?php echo '<a href="gallery.php?p=' .$next. '">    
<img src="Arrow-Right.png" width="16" height="16" title="Next Page" /> </a>';   
?>

//the line below is for left arrow link - go to previous page
<?php echo '<a href="gallery.php?p=' .$previous. '">    
<img src="Arrow-Left.png" width="16" height="16" title="Previous Page" /> </a>';    
?>

Now my question - I want to disable the left and right arrow links based on the condition - if $current_page = $num_pages (meaning, if max page has reached), then use javascript to disable the right arrow link if $current_page = 1 (meaning, if min page has reached), then use javascript to disable the left arrow link

Pretty simple scenario for pagination, but my concern is over how to use the variables correctly, since $current_page, $num_pages etc..are all PHP variables, and I assume they cannot be accessed readily in any Javascript code. So how do i access them, so that I can use JS to further work on link enabling/disabling or css styling using js etc...

Appreciate any pointers on the above.

<?php

$next_page = 12;

echo "<script>var next_page=$next_page;</script>"

Javascript variable next_page will be ready for use.

<?php
  echo '<script>pagenum=' . $num_pages . ';current_page=' . $current_page . ';</script>';
?>

Just echo your values into javascript:

<script>
   var jsvarname = "<?php echo $phpvarname; ?>";
</script>

I assume you know that javascript is client side and php server side, and what that means?

If you don't want the variables showing up in when the page source is viewed, you could store the information in a cookie.

Be aware that it's trivial to look at the contents of a cookie, however.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM