0

i would like to pass PHP code through JS, because I want to change dynamically the HTML attribute.

I have a problem with echoing string. I know why I have the problem(i think), but I don't know how to deal with it.

<?php echo $string1; ?>

the number "1" in code above had to be dynamic, based on ID of clicked link. This is code I have

  <script>
    $(function(){

      $('#myTab a').click(function (e) {
        e.preventDefault()
        $(this).tab('show')
        alert(this.id)

        var complete = ''.concat('<?php echo $string', this.id, '; ?>');

        document.getElementsByName('amount')[0].value=complete;
      })
    });
  </script>

and it returns me error:

Parse error: syntax error, unexpected T_CONSTANT_ENCAPSED_STRING, expecting ',' or ';' in

I know that the error is because of the part with '

please, don't ask why I'm trying to do this any that i shouldn't create strings like that, i just wanna help with existing code i have.

thanks!

  • 2
    AJAX. Learn about it. – Niet the Dark Absol Jun 11 '14 at 22:38
  • You can't concatenate javascript variables with PHP ones. PHP is executed before the page is even rendered on the client. So you can either populate some javascriot variable with your PHP data so it is there for js to work with, or you can make AJAX calls to the PHP backend to get the PHP data you need to work with. – Mike Brant Jun 11 '14 at 22:39
  • look: when I type then it works perfectly, but once I try to change the 1 inside, then PHP syntax error is shown. – Patryk Cieszkowski Jun 11 '14 at 22:41
  • PHP literally sees `echo $string', this.id, ';`, which as you hopefully agree looks invalid. – Felix Kling Jun 11 '14 at 22:46

1 Answers1

1

PHP is ran before it even gets to the user. Javascript is ran as the page is loaded. What your trying to do will not work. You can however use ajax to send data to a PHP page that spits out formatted code for what ever your trying to accomplish. Then pull that data back and do all your styling over js.

Bioto
  • 1,127
  • 8
  • 21
  • however, I've noticed that when I do "document.getElementsByName('amount')[0].value=complete;""", then it works perfectly, but it gives error when i'm not closing string tag an doing it at the end, to join three strings together. – Patryk Cieszkowski Jun 11 '14 at 22:47