external, dynamic, PHP-generated javascript
I was recently working on a project which required me to insert external, dynamically generated, HTML code into a HTML page. The dynamic HTML code was being generated with PHP, as it was extracting data from a MySQL database for display. So people would be able to paste some static code into their page and this code would reference an external file on a remote server which would return content.
One approach which immediately crossed my mind came after thinking about the adsense insertion code Google provides to people who want to insert adsense ads on their site. This involves calling an external javascript file at the place where you want the ads to appear. For example:
<script type="text/javascript" src=".../show_ads.js"></script>
With this approach, I thought that if I could get the called javascript file to make an AJAX call to a PHP file which generated the code, I could then return the code from the javascript file. My attempts with this approach were fraught with difficulties. For starters, when I tried to make a document.write() call within the AJAX process, the page calling the javascript file would complete, but then act as though it had not finished loading and an hourglass icon would persist. I managed to get around this using the innerHTML property of a predefined
As far as successful options for, the simplest way to include an external file in a HTML file is to use the <iframe/> tag. However, this method is considered undesirable and only a last resort. One issue is that the iframe tag is not compliant with strict XHTML.
Another option which I came across, involves using the object tag. This seems like a good alternative to the iframe option.
I however settled for a solution I think is quite nice. It is based on the fact that we can use PHP to generate dynamic Javascript files. If we put:
Header("content-type: application/x-javascript");
at the beginning of the PHP file, we are basically telling whatever references the PHP file that it is to expect a Javascript file as output. That being said, the output generated by the PHP must be valid Javascript. Nothing better than an example to explain a concept, so here is a basic one; a file that uses PHP to randomly generate a number and output it as Javascript.
<?php
Header("content-type: application/x-javascript");$random_number = rand();
//output data in javascript format.
echo "document.write(".$random_number.")";
?>
Finally, say this file is called random.php and is located at http://example.com. The following code would be used to reference it.
<script type="text/javascript" src="http://www.example.com/random.php"></script>
Tags: Javascript, PHP

















































