2

How can I pass null PHP variable to javascript?

My code is as:

<?php

$size = null;

<< Call Rest API >>
if (<some_condition_here>) {
    $size = <rest_api_value>;
}
echo "<input name='diff_size' id='diff_limit' type='test' value='$size' />";

<script>
var initial_value = $size

function checkIfChanged() {
    if ($('diff_size').val() == initial_val )
    {
        return false;
    }
    return true;
}

</script>
?>

<< On submit javascript function is called >>

Error message:

Uncaught SyntaxError: Unexpected token ;

var initial_value = ;

1
  • 1
    You want to wrap $size in quotes otherwise the JavaScript might get parsing errors. Commented Sep 16, 2019 at 20:08

1 Answer 1

2
<?php

$size = null;

<< Call Rest API >>
if (<some_condition_here>) {
    $size = <rest_api_value>;
}
echo "<input name='diff_size' id='diff_limit' type='test' value='$size' />";
?>
<script>
var initial_value = '<?= $size ?>';

function checkIfChanged() {
    if ($('diff_size').val() == initial_val )
    {
        return false;
    }
    return true;
}

</script>
Sign up to request clarification or add additional context in comments.

Comments

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.