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>
echo '<script>',
'wholesection("Hello");',
'</script>'
;
</head>
<body>
<?php
$variable = "Hello";
echo '<script>',
'wholesection('.$variable.');',
'</script>'
;
'wholesection($variable);',
'wholesection("$variable");',
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");