2

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?

2
  • First of all, don't prefix JS variables with $. That'll only lead to confusion. Commented Jul 14, 2015 at 5:57
  • @Ankur Tiwari: there is no "best way". you just need to make sure everything works as expected and the errors are handled correctly. and, of course, to make sure is easily readable by you or another coder that might need to modify your code. also, you can search for examples over the internet. Commented Jul 14, 2015 at 6:43

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

You should use <?php echo json_encode($var2); ?> to ensure that the variable has correct JS syntax.
@AnkurTiwari welcome :) And by the way your twitter is not working

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.