Ankur Tiwari
Ankur Tiwari

Reputation: 2782

Best way to separate PHP and Javascript code

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?

Upvotes: 2

Views: 262

Answers (1)

Pratik Joshi
Pratik Joshi

Reputation: 11693

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.

Upvotes: 3

Related Questions