-1

If I pass an hard coded numeric value from php to javascript, all works perfectly. But if i pass the numeric value from a variable, i get an 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); // this will work PERFECTLY!!!
            goto_anchor(<?php echo $get_cat; ?>); // this will NOT work !!!
        });
    </script><?php
} ?>

I need to pass the $get_cat variable in my php, not the harcoded numeric value. How ?? Thanks

10
  • 6
    What is being rendered when you run that? That should work. Commented Nov 9, 2014 at 16:35
  • i doesnt scroll to the anchor and i get the javascript error: Uncaught TypeError: Cannot read property 'top' of undefined Commented Nov 9, 2014 at 16:37
  • Right click and view source, what is actually written to the page? Commented Nov 9, 2014 at 16:38
  • no, the hard coded 4 works! Commented Nov 9, 2014 at 16:39
  • 1
    Look at what your PHP is actually outputting. That should be your first step in diagnosing problems like this, and it's going to give you an obvious cause in almost every case. As it stands, we can't possibly help. If your first line, goto_anchor(4) works PERFECLTY!!!, then your second line must necessarily work. You've either omitted details, or misinterpreted your error. Commented Nov 9, 2014 at 16:39

1 Answer 1

0

I have such kind of problems before, can not fill

javascriptfunction(<?php echo $phpvirable ?>) 

inside javascript function that causes error; Instead , according to your code, can echo it to javascript virable first before using it;

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

into your php

<?php   $get_cat = 4;  ?>

surely, Your php $get_cat can be captured from such as $_REQUEST['cat'] dynamic value from form submit event towards this page. then u convert it to javascript virable to use in function.

<?php
if(isset($getcat)):
echo '<script> var get_cat = '.$getcat.'</script>';
endif;
?> 
// javascript function read predefined javascript virable that confirm work.

// u also avoid using mixed php and javascript statements which looks messy
<script> 
    $(document).ready(function() {
         goto_anchor(get_cat); // this will work then.
    });
</script>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.