PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, July 26, 2022

[FIXED] How do I insert PHP variable inside jQuery/JavaScript properly?

 July 26, 2022     dreamweaver, javascript, jquery, php     No comments   

Issue

This code works when running the application, but Dreamweaver is giving a syntax error. It doesn't like the question mark there. I like DW to be syntax error free. Is there a different way to write this? I have DW cs5.5 I can't upgrade Dreamweaver version.

    if ( $('#postage6').val() == "Your Permit Standard" ) {
        $('#postage6rate').val('<?php echo $your_permit_standard; ?>');
    }

Putting a backslash before the question mark just makes it print like this, which is not right.

    if ( $('#postage6').val() == "Your Permit Standard" ) {
        $('#postage6rate').val('<\?php echo $your_permit_standard; ?>');
    }

when it renders, there is supposed to be a value like this:

    if ( $('#postage6').val() == "Your Permit Standard" ) {
        $('#postage6rate').val('0.333');
    }

Also this doesn't work:

    if ( $('#postage6').val() == "Your Permit Standard" ) {
        var somevar = "<?php echo $your_permit_standard; ?>";
        $('#postage6rate').val(somevar);
    }

The syntax error just transfers from the line where the PHP variable was to the new line where the PHP variable is.


Solution

You could define the value in a separate php block:

<script type="text/javascript">
   var value = '<?=$your_permit_standard?>';
</script>

And then use it in your JS:

if ( $('#postage6').val() == "Your Permit Standard" ) {
    $('#postage6rate').val(value);
}

But then you would be introducing JS dependency in PHP, which I wouldn't recommend, but since you're mixing both anyway...



Answered By - Samuel
Answer Checked By - Terry (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing