-1

I'm having problems putting javascript inside the PHP switch case, I get this problem:

Parse error: syntax error, unexpected '<', expecting case (T_CASE) or default (T_DEFAULT) or '}' in

Here is the code:

case 'settings':
        <script type="text/javascript">
            ($('<div class="'+ currentdiv +'">').load(settings.php).appendTo
            ($(targetdiv)));
        </script>
      break; 
Community
  • 1
  • 1
Will John
  • 25
  • 7
  • 2
    You need to echo it as a string. – SudoKid Jan 08 '19 at 23:56
  • wrap it as a heredoc. http://php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc – zfrisch Jan 08 '19 at 23:56
  • 1
    You cannot put JS into PHP like this. You gotta either print (echo) it, or close the PHP tag and then reopen it when needed/after you're finished with the JS chunk. – Jeto Jan 08 '19 at 23:57
  • Thank you very much friends, but the problem was opening and closing php for javascript output https://stackoverflow.com/a/54101489/7560197 – Will John Jan 09 '19 at 00:08
  • @miken32 I'm sorry, I did not find this question, and even if I thought I would not know the answer, because I thought I could not leave javascript in switch case! – Will John Jan 09 '19 at 00:14

2 Answers2

1

Problem solved! The problem was in closing the php and opening it again as it could not leave the javascript inside php!

case 'configurations':
       ?> <script type="text/javascript">
            ($('<div class="div-content">').load("server/settings.php").appendTo
            (".content-loaded-tab"));
        </script>
    <?php
        break;
Will John
  • 25
  • 7
1

Need to capture it as String and then echo it to the document.

case 'settings':
  $script = "<script type='text/javascript'>\r\n";
  $script .= '\t$("<div>", { class: currentdiv }).load("settings.php").appendTo($(targetdiv)));\r\n';
  $script .= "</script>\r\n";
  echo $script;
  break;

Hope that helps.

Twisty
  • 30,304
  • 2
  • 26
  • 45
  • Thanks a lot, buddy, but the problem was opening and closing php for javascript output https://stackoverflow.com/a/54101489/7560197 – Will John Jan 09 '19 at 00:06
  • 1
    @WillJohn yes you can escape PHP or capture it as a String. Either way. – Twisty Jan 09 '19 at 00:07
  • 1
    I would suggest not appending html into a variable whenever possible, especially using concatenation on every line. It's clunky, slower and forces you to escape double quotes (unless you use heredoc syntax). (Additionally, some IDEs might not even recognize it as HTML at all) – Jeto Jan 09 '19 at 00:12
  • 1
    @Jeto I subscribe to keeping each separated, using templates, heredoc etc. OP didn't appear to be using this, so I provided an answer for that specific use case. – Twisty Jan 09 '19 at 00:21
  • @Twisty Fair enough! – Jeto Jan 09 '19 at 00:25