1

I have a simple php file that prints the date and time. I would like to load this file with jQuery so it shows the $date variable. Can't seem see why this is not working, any advice on why?

My php file:

<?php
date_default_timezone_set('GMT');

$date = date('d/m/Y H:i:s');

print $date;?>

My on page code:

<script>$(document).load(function(){
    $('#time').load('http://www.my-website.co.uk/my-php-file.php');});</script>
<div id="time"></div>
Mr Digler Sir
  • 31
  • 1
  • 6
  • 2
    You probably want `$(document).ready`. And to check your browser's JS console. Is the page making the AJAX request also on `http://www.my-website.co.uk/` or is this a cross-domain call? – ceejayoz Mar 06 '17 at 16:39
  • 1
    Maybe is a cross domain issue – Carlos487 Mar 06 '17 at 16:41
  • Why are you nesting a load inside another load? – Lelio Faieta Mar 06 '17 at 16:48
  • Try the innermost part and gradually move outwards. Does the $().load thing work? It should, but if it doesn't, you should see the request and response in the Network tab of your Console (F11). Then you can move on to the document ready event, knowing that the inside is working safely. – dkellner Mar 06 '17 at 16:48
  • @LelioFaieta http://api.jquery.com/load/ versus https://api.jquery.com/load-event/ - two different functions. – ceejayoz Mar 06 '17 at 17:08

2 Answers2

1

I would remove the print... line from the php file, include the php file in your HTML page and add an echo for the $datevariable after the include line (i.e. no jquery at all):

<div id="time">
  <?php 
    include "http://www.my-website.co.uk/my-php-file.php";
    echo $date;
  ?>
</div>
Johannes
  • 64,305
  • 18
  • 73
  • 130
  • I do understand this can be done with php alone, however I would like to use the jQuery to refresh the eventually. But trying to start off things nice and simple – Mr Digler Sir Mar 06 '17 at 16:54
  • well, in your code the loaded file is inside a `script` tag, and I suppose the "$" character in the php variable can conflict with what "$" stands for in jQuery – Johannes Mar 06 '17 at 16:56
0

code now working thanks for all the help:

<script>
$(document).ready(function(){
$('#time').load('http://www.my-website.co.uk/my-php-file.php');
});</script>
<div id="time"></div>
Mr Digler Sir
  • 31
  • 1
  • 6