分离PHP和Javascript代码的最佳方法

Is there a best way to separate javascript and php code. for example:

//php code
if(condition1)
{
    ?>
    // javascript code
    $card_typej = $(this).val().trim();
    if(condition2)
    {
        $("#id1").html('<?php echo($var1); ?>');
    }
    else
    {
        $("#id1").html('<?php echo($var2); ?>');
    }
    <?php
}
?>

If yes then, how to separate the above code?

First store required PHP variables in Javascript vars and then manipulate it.

<script>
var var2 = <?php echo json_encode($var2); ?>;
var var1 = <?php echo json_encode($var1); ?>;
if(condition1)
{
    ?>
    // javascript code
    $card_typej = $(this).val().trim();
    if(condition2)
    {
        $("#id1").html(var1);
    }
    else
    {
        $("#id1").html(var2);
    }
    <?php
}
?>
</script>

You can see, complicated php+js code mixture is not there now.