简体   繁体   中英

Embedding PHP within javascript

I'm trying to create a messaging system that opens when you click the "New Message" button. I'm using HTML, PHP, and javascript.

I have a button set up with a container to append a textarea into. I am doing this with javascript DOM. This part I have no problem with, it is trying to get PHP inside javascript.

So let's say I have a variable:

<?php $my_name = "Eric" ?>

Would I be able to call this in javascript? If not, are there any any other ways to approach this?

Here is my full code:

HTML:

<html>
<head>
    <link type="text/css" rel="stylesheet" href="message.css"/>
    <script type="text/javascript" src="js/message.js"></script>
</head>

<body>
    <div id="container"></div>

    <button id="new_message" onclick="createMessage()">New Message</button> 
</body>
</html>

CSS:

#container {
    position: absolute;
    height: 443px;
    width: 743px;
    border: 1px solid black;
    border-radius: 0 0 20px 0;
    margin-top: 100px;
}

Javascript:

function createMessage() {
    var form = document.createElement("form");
    form.name = "form_input";
    form.method = "POST";
    form.action = "messages.php";
    container.appendChild(form);

    var textarea = document.createElement("textarea");
    textarea.name = "message_input";
    textarea.cols = 84; 
    textarea.rows = 16; 
    textarea.id = "message_input"; 
    container.appendChild(textarea);
};

I'm trying to do something similar to Facebook, that when you click on the messages button, a pop up box appears with php inside of it.

Can this be done the way I'm doing it with javascript or do I have to use something else?

Thanks for your help!

The best way to think of this is to go back to the order of execution for the different scripting languages used in the page. That order of execution is something like this:

(1) PHP is run on your server. It spits out a bunch of HTML and/or Javascript and/or CSS which is sent as a response to the user's browser.

(2) The user's browser receives a response, renders the HTML, and executes the Javascript.

In practical terms, this means you can make your Javascript dependent on your PHP , but not the other way around.

From your question, it looks like it would be OK for you to always execute the PHP and simply display the result when a user clicks on a button. So have your PHP spit out some Javascript like so:

<script type="text/javascript">
    var myName = '<?php echo addslashes($my_name)?>';
</script>

[Note: you may want to do additional, or different, sanitization.]

would make sense to pass the variable to the javascript via the button. eg.

<button id="new_message" onclick="createMessage('<?php echo $my_name;?>')">New Message</button>

I'm assuming your real question is "how can I take data in PHP and make a copy of that data available to Javascript".

There are two main approaches you could take:

  1. Have your Javascript, when triggered, attempt to get information from the server via AJAX call. That would be a separate PHP script and the JS would have to pass in some sort of ID or other information to help you figure out what it needs.
    • Requires a separate PHP script and extra plumbing.
    • Better when the amount of data is large
    • Better when there are a lot of these buttons and users won't use that many of them
    • Forms the foundation of much fancier stuff later on
  2. Embed the information into the HTML, and have the Javascript read it out.
    • Easier to do
    • Page is bigger
    • May become a problem once you start doing it a lot
    • You'll probably need to do this just a little bit even after AJAX gets used, to pass IDs and things.

I'd suggest you try the "quick and dirty" way for the moment, just to get a feel for it. For example, in your PHP page:

<?php
/* ... */
$defaultMessage = "Hello world! Watch me contain single quotes (') and double quotes(\") and other things!";
/* ... */
?>
<button id="new_message" onclick="createMessage(<?= htmlentities(json_encode($defaultMessage))?>">New Message</button>

I'm not 100% sure on the escaping, but test with single and double quotes in the data to ensure nothing goes awry, and remember that you need to escape it one way to avoid breaking HTML, and again in another way to avoid breaking javascript. Then in your JS file:

function createMessage(defaultMessage) {
    // ...
    textarea.value = defaultMessage;
    // ...
}

In this way you've put data from PHP into the HTML output, and then later (after the PHP script has stopped running) the user's browser gets the HTML and can can pull that data back out for whatever purpose it needs.

PHP is executed server side while javascript runs client side. To pass variables or any other data between javascript and php you need to either call your server via ajax requests or (for static data) put the data into your page source to process it with javascript. Anyway you need to convert the data on the server side to allow for processing. For example create an interface.php file containing something like the following:

<?php
  $mydata = array("username"=>"john");
  echo "window.serverdata=".json_encode($mydata).";";
?>

And then include it in your page:

<script type="text/javascript" src="interface.php"></script>
...
<script type="text/javascript">
  alert(serverdata.username);
</script>

Note that ajax requests are the de facto standard since you do not want to reload your page every few seconds. The above mentioned method can be useful if you want to exchange static data.

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