How to pass a variable from php to javascript -



How to pass a variable from php to javascript -

if pass hard coded numeric value php javascript, works perfectly. if pass numeric value variable, error:

javascript file (gallery.js)

function goto_anchor(id) { var anchor = $("#anchor_" + id); $('html,body').animate({ scrolltop: anchor.offset().top - 20 }, 1200); }

php file

.... <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js" type="text/javascript"></script> <script src="js/gallery.js" type="text/javascript"></script><?php $get_cat = 4; if (isset($get_cat)) { ?> <script> $(document).ready(function() { goto_anchor(4); // work perfectly!!! goto_anchor(<?php echo $get_cat; ?>); // not work !!! }); </script><?php } ?>

i need pass $get_cat variable in php, not harcoded numeric value. how ?? thanks

i have such kind of problems before, can not fill

javascriptfunction(<?php echo $phpvirable ?>)

inside javascript function causes error; instead , according code, can echo javascript virable first before using it;

echo '<script> var get_cat = '.$get_cat.'</script>';

into php

<?php $get_cat = 4; ?>

surely, php $get_cat can captured such $_request['cat'] dynamic value form submit event towards page. u convert javascript virable utilize in function.

<?php if(isset($getcat)): echo '<script> var get_cat = '.$getcat.'</script>'; endif; ?> // javascript function read predefined javascript virable confirm work. // u avoid using mixed php , javascript statements looks messy <script> $(document).ready(function() { goto_anchor(get_cat); // work then. }); </script>

javascript php jquery

Comments

Popular posts from this blog

c# - ASP.NET MVC Sequence contains no matching element -

java - Parsing XML, skip certain tags -

rest - How to invalidate user session on inactivity in a stateless server? -