-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; 
5
  • 2
    You need to echo it as a string. Commented Jan 8, 2019 at 23:56
  • wrap it as a heredoc. php.net/manual/en/… Commented Jan 8, 2019 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. Commented Jan 8, 2019 at 23:57
  • Thank you very much friends, but the problem was opening and closing php for javascript output stackoverflow.com/a/54101489/7560197 Commented Jan 9, 2019 at 0: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! Commented Jan 9, 2019 at 0:14

2 Answers 2

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;
Sign up to request clarification or add additional context in comments.

Comments

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.

5 Comments

Thanks a lot, buddy, but the problem was opening and closing php for javascript output stackoverflow.com/a/54101489/7560197
@WillJohn yes you can escape PHP or capture it as a String. Either way.
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 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 Fair enough!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.