简体   繁体   中英

How can i add this script in php

am trying to find out how to add this script to my php file , as i try echo it ,its not working.

am sure there is a way to add this, its my first time adding these scripts to php file ,maybe il learn something today and remmeber it thanks.

var counter = 1;
var auto_refresh = setInterval(
function () {
    var newcontent= 'Refresh nr:'+counter;
    $('#divID').html(newcontent);
    counter++;
}, 5000);

and the html div this is not needed to add to php as i have own div in php file

<div id="divID"></div>

Close the php tags, open a script tag, paste your script there, close your script tag, re-open your php tag. ;)

I recommend putting your js at the end of the file tho.

<?php
    // your php here
?>

<div id="divID"></div>
<?php
    // some php if you want to
?>

<script type="text/javascript">
  //Your javascript here
  var counter = 1;
  var auto_refresh = setInterval(
  function () {
    var newcontent= 'Refresh nr:'+counter;
    $('#divID').html(newcontent);
    counter++;
  }, 5000);
</script>

Normally, you won't put javascript in your php file... But if there's no other solution:

<?php

echo"
<script type=\"text/javascript\">
    var counter = 1;
    var auto_refresh = setInterval(
    function () {
       var newcontent= 'Refresh nr:'+counter;
       $('#divID').html(newcontent);
       counter++;
}, 5000);        
</script>
";

In PHP pass js code into variable

<?php 
    $script = "<script type='text/javascript'>
    var counter = 1;
    var auto_refresh = setInterval(
    function () {
      var newcontent= 'Refresh nr:'+counter;
      $('#divID').html(newcontent);
      counter++;
    }, 5000);  </script>";
?>

In HTML where you want to show/add

<html>
<head>
   <?php echo  $script; ?>
</head>
</html>

You can put it like this or you can put <script> part in the head of your page or in js file and include in page.

<?php
// code
?>

<script>
$( document ).ready(function() {
   var counter = 1;
   var auto_refresh = setInterval(
   function () {
       var newcontent= 'Refresh nr:'+counter;   
       $('#divID').html(newcontent);
       counter++;
   }, 5000);
});
</script>
<div id="divID"></div>

Note: you also need jquery. If you don't use one you can include this in your page also

<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>

I just tested it and it's working perfectly. Currently my counter is

Refresh nr:51

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM