Russ Russ - 1 month ago 5
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.

<script>
function wholesection(val) {

$( "#whole-section" ).slideUp( "fast", function() {
});
$('#label-cemetery').text("Section*");
$('#poc').val(val);
}
</script>


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

echo '<script>',
'wholesection("Hello");',
'</script>'
;

</head>
<body>
<?php
$variable = "Hello";

echo '<script>',
'wholesection('.$variable.');',
'</script>'
;


Or other similar variants do not work.

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


Thank you in advance,

Russ

Answer

Suppose your $variable has value "Hello".

Then this code:

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

is rendrered in html like

wholesection(Hello);

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:

wholesection("Hello");