dapperwaterbuffalo
dapperwaterbuffalo

Reputation: 2748

issue including external js scripts in php

so please take into account I am a newbie. I currently use the following script throughout my pages to display the time:

var currenttime = '<? print date("F d, Y H:i:s", time())?>' //PHP method of getting server date
    var montharray=new Array("January","February","March","April","May","June","July","August","September","October","November","December")
    var serverdate=new Date(currenttime)

    function padlength(what){
    var output=(what.toString().length==1)? "0"+what : what
    return output
    }

    function displaytime(){
    serverdate.setSeconds(serverdate.getSeconds()+1)
    var datestring=montharray[serverdate.getMonth()]+" "+padlength(serverdate.getDate())+", "+serverdate.getFullYear()
    var timestring=padlength(serverdate.getHours())+":"+padlength(serverdate.getMinutes())+":"+padlength(serverdate.getSeconds())
    document.getElementById("servertime").innerHTML=datestring+" "+timestring
    }

    window.onload=function(){
    setInterval("displaytime()", 1000)
    }

and display it with the following html:

<div id="header"><span class="time" id="servertime"></span></div>

what I assumed I could do, rather than having the same script in <head> of every page, put the script in an external .js file and include it using:

<script type="text/javascript" src="live_clock.js"></script>

now my root is .../ece70141/

I have just put it in the same directory (.js file as the others) just to get it to work. However its not working. Could somebody please advise me how to do this properly?

many thanks,

Upvotes: 0

Views: 127

Answers (2)

tXK
tXK

Reputation: 712

I'd say you should do something like this:

<script>
     var currenttime = '<?php echo date("F d, Y H:i:s", time()); ?>'
</script>
<script src="/your/path/to/the/javascript.js"></script>

Upvotes: 0

Felix Kling
Felix Kling

Reputation: 816790

You have to serve the JavaScript file through PHP otherwise <? print date("F d, Y H:i:s", time())?> will not be parsed.

It might be as simple as setting .php as file suffix (instead of .js) and adding

<?php 
    header('Content-type: text/javascript');
    // or  header('Content-type: application/javascript');
?>

at the top.

Upvotes: 1

Related Questions