简体   繁体   中英

echo javascript from php not working?

So, in an html page I'm trying to have a php segment echo some javascript code, as seen here:

<?php
    echo "This was legitimately hit";
    if(!empty($_POST['name']))
    {
        echo '<script type="text/javascript">alert("We got the name");</script>';
    }
    else
    {
        echo '<script type="text/javascript">alert("We DID NOT get the name");</script>';
    }
?>

and from what I've read online, this seems to be a legitimate way of doing things, but the page seems to be reading the first part up until the first closing chevron (seen just below here) as a comment.

<?php
    echo "This was legitimately hit";
    if(!empty($_POST['name']))
    {
        echo '<script type="text/javascript">

Then it reads the else and next echo as plain text, and puts it on the webpage. the next javascript code block then gets read as a regular javascript code block, so the page does a pop-up saying it did not get the name. The closing bracket and closing chevron then just get output as more text.

So in the end the page just ends up having

alert("We got the name")'; } else { echo ''; } ?>

printed on it as plain text, and has a pop-up that says we received no name.

What is going wrong here?

Sounds like the file isn't being processed as PHP. Does the file name end in .php? Are you sure PHP is installed and hooked up correctly to the web server?

edit: To handle the Facebook requests in the same page:

<?php

if (isset($_POST['facebook_request_field'])) {
  // handle the Facebook request, output any necessary response
  // then exit
  exit;
}

?>
<!-- display the web page normally here -->

So for your test page:

<?php

if (isset($_POST['name'])) {
  echo '<script type="text/javascript">alert("got a name!");</script>';
  exit;
}

?>
<script type="text/javascript">alert("No name.");</script>

(That's actually identical in function to what you already have, so maybe I'm misunderstanding the purpose.)

Between We got the signed request and We got the name , I think you haven't given us the actual code that's causing the error. Double check that, and make sure you don't have any stray single quotes before your alert call.

There are missing ; after the alert . Have you tried correcting this first?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM