tags:

views:

498

answers:

3
+1  Q: 

innerHTML and PHP

I want to do some innerHTML replacements, but using PHP includes, I dont get how. I have done innerHTML replacements before, just not with PHP.

I have:

var xmlHttp

function DisplayAerialProductListing()
{ 
    var strStartCode="<p></p>";
    document.getElementById("txtData").innerHTML= strStartCode;

    var code="";
    code = code + "<?php include 'newpage.inc'; ?>";
    document.getElementById("txtData").innerHTML= code;
}

I have the 'txtData' Div as:

initially and I want to replace with code from the .inc I mention. I use .inc to separate out pieces of the site and to make like easier for the designer so they dont go breaking stuff!

In the .inc I just have HELLO for now.

It doesn't work. What is the trick?

+3  A: 

PHP is processed server-side; Javascript is processed client-side. You can't insert PHP code via Javascript because you've already left the server. Normally what you'd do is use AJAX to run the PHP code on the server and then insert the results dynamically into the page.

Amber
@Dav - can you give me an example on how to accomplish this?
This is a decent AJAX tutorial: http://www.w3schools.com/Ajax/ajax_example.asp
Amber
@Dav - Thank you, this information will be helpful.
You're most certainly welcome. :)
Amber
A: 

That will work as long as your JavaScript file is parsed by PHP, ie. with an .htaccess that says SetHandler application/x-httpd-php .js. You'll want to escape the text inside the include, so it may be better to use PHP's file_get_contents() and addslashes(). Here's an example of how to super sanitize a string in PHP that is destined for JavaScript: http://sixohthree.com/241/escaping

An alternate solution would be to load the page content via XMLHttpRequest.

Adam Backstrom
+1  A: 

Using jQuery, you can nail that almost effortlessly:

<p id="myParagraph"></p>

<script>
//when the DOM is ready
$(document).ready(function() {
    //replace contents of p id="myParagraph" with output of specified script
    $('#myParagraph').load('myPage.php');
});
</script>

Still, make sure you understand the difference between client and server as per @Dav's answer.

See http://docs.jquery.com/Ajax

karim79
@karmin - Thanks for the sample and reference URl. I think this will work pretty darn good