Reputation: 1118
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?
Upvotes: 1
Views: 9912
Reputation: 11
<script style="text/javascript" language="javascript">
<!--
function check_country()
{
var sel_country = document.getElementById("country");
if(sel_country.value == "US")
{
<?php
$query = "SELECT stateName, stateAbbrev
FROM states
WHERE stateEnabled = '1'
ORDER BY stateName ASC";
$result = mysql_query($query);
$prov = "<select name=\"state\" id=\"state\" class=\"widthed\">";
while($row = mysql_fetch_row($result))
{
$prov .= "<option value=\"$row[1]\">$row[0]</option>";
}
$prov .= "</select>";
?>
document.getElementById("tab1").rows[2].cells[3].innerHTML = "*State:";
document.getElementById("tab1").rows[3].cells[0].innerHTML = "*Zip Code:";
document.getElementById("tab1").rows[2].cells[4].innerHTML = <?php echo $prov; ?>;
}
}
-->
</script>
Upvotes: 1
Reputation: 342635
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
Upvotes: 1
Reputation:
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.
Upvotes: 0
Reputation: 526633
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.
Upvotes: 3