0

Is it possible to insert PHP code into a webpage using javascript after the page has loaded? When a user clicks on a category, I want to show a set of images (which I insert using js), and then search for any associated comments using PHP.

Here is my code :

var temp = '<div class"comment_section">';
var html = temp + '<?php if ( post_password_required() ) return; ?><div id="comments" class="comments-area"><div class="container"><?php ?><?php if ( have_comments() ) : ?><!-- functions for displaying comments here --></div></div>';
html += '</div>';

That didn't work. I also tried swapping the brackets for &lt; and &gt; but that just inserts the above between quotes which is then diplayed as a block of text on the page.

Basically is what I'm trying to do even possible?

lenny
  • 135
  • 1
  • 11

3 Answers3

2

Is it possible to insert PHP code into a webpage using javascript after the page has loaded? The simple answer is no. The page has already been rendered, the only way to change it is using javascript running within the user's browser.

However, if you want to search for any associated comments using PHP, just send a request to the server using AJAX and set up your server to return a well-formed response to that query.

To learn more about ajax, you may want to read What is AJAX, really?.

Community
  • 1
  • 1
Femi
  • 1,332
  • 9
  • 20
1

If you want to execute some php code without reloading your page and depending on which category you selected, you can use AJAX.

caRameL
  • 633
  • 6
  • 15
0

JavaScript is a client-side language, while PHP is a server-side interpreted language. That means that the browser gets the results produced by your php script while the JS is running inside the browser. That said, it's not possible to throw any PHP code into the already rendered website - no matter if it's with JS or any other technology.

AdamC
  • 1
  • 1
  • 6