简体   繁体   中英

how to insert php code inside javascript code

I need to store the content of story inside mysql table.

This content will later be normally loaded on another page using php .

piano.php is a third, separate file and I don't want it on the current page, but only on the target page.

So I'm trying to insert php code inside story content but it is automatically commented (see in console);

How to do this?

 $('button').on('click', function() { var a = "<div class='part partpiano'><?php include('piano.php');?></div>"; $(a).insertBefore($('.title')); console.log($('.story').html()); }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class='story'> <div class='title'>lorem</div> </div><br> <button>CLICK</button> 

It's a much better practice to avoid mixing PHP with JavaScript. PHP is a server-side language and as a result, executes differently from the browser. It can work but usually leads to unexpected behaviour and for the most part, it's much cleaner to keep everything separate.

You can achieve passing data between PHP and JS using hidden inputs or DOM elements with data-* attributes, eg

<div id="php-data" data-id="<?php echo $foo; ?>"></div>

then in your jQuery

let id = $('#php-data').attr('data-id');

However, for your problem in particular (as it's an include). It's much much better to simply include the file on load using a class of hidden:

css:

.hidden {
    display: none
}

html/php:

<div class="title">
    <div class="part partpiano hidden">
        <?php include_once 'piano.php'; ?>
    </div>
</div>

Then in your JS:

$('button').click(function()
{
    $('.part').removeClass('hidden')
})

You can't include PHP in your page in the way you've tried, as you've found. PHP is executed on the server and the results are returned to your browser, so if you add PHP with Javascript then it's not executed/parsed and is just added as text (your browser cannot execute PHP).

What you can do is add the container element to the page and then load the contents afterwards, like this...

$('button').on('click', function() {
  var a = "<div class='part partpiano'>Loading...</div>";
  $(a).insertBefore($('.title'));
  $(a).load("piano.php");
});

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