0

I've these codes in a simple project, I want to refresh the news ticker when the button is clicked. The src is changing, but it is not showing contents from the php file which is printing a simple javascript.

Here is th HTML

<marquee id="ticker"></marquee>
<button onclick="refresh()">Refresh</button>

Here's the JS

function refresh(){
    document.getElementById('ticker').innerHTML = "<script src='ticker.php?" + new Date().getTime() + "'></script>";
    }

Here's what inside ticker.php

<?php
 echo "document.write('It is the scrolling news');";
?>
tawsif torabi
  • 713
  • 7
  • 14

2 Answers2

2

Well actually, scripts inserted with innerHTML are not parsed by the browser and, thus, not downloaded. So your server should not receive any request here.

The way to do this (programmatically insert a new script in the page) is using the document.createElement method to create a new script element. (see this thread https://stackoverflow.com/a/13122011/2745879)

This is the way to do this:

function refresh(){
  var script = document.createElement("script");
  script.src = "/ticker.php?" + new Date().getTime();
  document.head.appendChild(script);
}

This should download your new script and run it :)

atomrc
  • 2,543
  • 1
  • 16
  • 20
  • What do you mean "native javascript"? If you mean a javascript file (no php), yes it will totally work!! – atomrc Jun 02 '17 at 19:16
  • If i change the source of the script tag with javascript and add a timestamp after the source with a '?', would the browser parse and execute the script then? – tawsif torabi Jun 02 '17 at 19:54
  • Well yes, I guess. But I am not sure what you are trying to achieve. This seems overly complicated. You might just want to fetch some data against the server and place it in the DOM, right? In that case, you should do an AJAX request and modify the `innerHTML` of your `ticker` element with the data (and not another script tag) – atomrc Jun 02 '17 at 21:49
1

Use Jquery to call an ajax function in wich you go to the php file and returns whatever you want

var refresh = function(){

    $.ajax({
        url: 'ticker.php',
        type: 'POST',
        data: yourJsonData,
    })
    .done(function(msg) {
        document.getElementById('ticker').innerHTML = "<script src='ticker.php?" + new Date().getTime() + "'></script>";
    })
    //msg is equal to "document.write('It is the scrolling news');"
    //then JSON.parse(msg); to convert to a javascript object
    .fail(function(err) {
        console.log("error"+err);

    })
    .always(function() {
        console.log("complete");
    });

}