Russ Russ - 3 years ago 86
Javascript Question

Pass a php variable to a jQuery function

I have searched and tried several different methods to pass a php $variable to a jQuery function. I can pass a string simply by using myfunction("Hello");. But if I try myfunction(); or myfunction($variable); with or without quotes it fails to run.

function wholesection(val) {

$( "#whole-section" ).slideUp( "fast", function() {

The above works if I send a literal string enclosed in double quotes, using:

echo '<script>',

$variable = "Hello";

echo '<script>',

Or other similar variants do not work.


Thank you in advance,


Answer Source

Suppose your $variable has value "Hello".

Then this code:

echo 'wholesection('.$variable.');',

is rendrered in html like


See? You're passing Hello to a function. Not "Hello" but Hello. And Hello is considered a javascript variable. I bet you don't have it.

So, the fix is - add quotes:

echo 'wholesection("'.$variable.'");',

which will be rendered as:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download