-3

I want to make something like tables which refresh every 1 second and show to all the users on the website. You see, like, when the user loads the page, every 1 second, a new table row gets added to the table on the body. He should be able to see that change without having to refresh manually or press F5.

Here is what I have tried, returns an empty page:

<html>
<head></head>
<body>
<script type="text/javascript">
function myFunction()
{
    <?php

        echo "<tr>";
        echo "<td>Hey</td>";
        echo "</tr>";
    ?>
}
setTimeout(myFunction, 1000);
</script>
</body>
</html>
Panos Kalatzantonakis
  • 12,525
  • 8
  • 64
  • 85
  • 6
    Where does the new information come from? Do you realise that the PHP will be executed once only? – Joe May 15 '14 at 13:16
  • 1
    You're echoing HTML inside a javascript function? That's a syntax error – adeneo May 15 '14 at 13:17
  • I amnot even seeing 1 output.. Haven't I added a setTimeout to re-do the function every 1 second? Also, what if I just want each to just be saying "hey" – user3624894 May 15 '14 at 13:17
  • @adeneo then how do i do it? :3 – user3624894 May 15 '14 at 13:17
  • That depends on what you're trying to do, this doesn't really make much sense? Why echo with PHP, and what's the timeOut for etc ? – adeneo May 15 '14 at 13:20
  • Maybe like this -> http://jsfiddle.net/adeneo/Z4mAt/ – adeneo May 15 '14 at 13:21
  • @adeneo - That outputs Hey "; ?> – user3624894 May 15 '14 at 13:22
  • 2
    You need to create a PHP file and retrieve that file, via AJAX, each time that setInterval() (mentioned in a follow up answer) calls myFunction(). – Jay Blanchard May 15 '14 at 13:23
  • First of all, setTimeout will only be triggered once.. use setInterval instead – Mark Rijsmus May 15 '14 at 13:25
  • @MarkRijsmus I was commenting on your follow up to let you know that even though you started with "first of all" you didn't finish baking the answer before submitting. That's why all the DV's - and those are not personal. – Jay Blanchard May 15 '14 at 13:27
  • Of course it outputs something strange, jsFiddle doesn't execute the PHP, you have to try it on your webserver. – adeneo May 15 '14 at 13:28
  • Learn to use a console. Firebug for Firefox is excellent. Set it up to show javascript errors, and then watch your console when you reload your page. – random_user_name May 15 '14 at 13:28

9 Answers9

2
<!DOCTYPE html>
<html>
<body>

<table border="1px">
<tr><td> dgfdgfdgf </td></tr>
<p id="demo"></p>
</table>


<script>

var myVar = setInterval(function(){myTimer()},1000);

function myTimer() {
    document.getElementById("demo").innerHTML += '<tr><td>erewrwewr</td></tr>';
}
</script>

</body>
</html>
Anahit Serobyan
  • 432
  • 1
  • 6
  • 17
1

Server code will only generate a table row for every response; you need to either send multiple responses using ajax, or get a collection of data to loop through using PHP if you're filling the table with data.

A simple non-data way to achieve your current functionality using only Javascript is like so:

    function rowGenerator(){

// Find a <table> element with id="myTable":
var table = document.getElementById("myTable");

// Create an empty <tr> element and add it to the 1st position of the table:
var row = table.insertRow(0);

// Insert new cells (<td> elements) at the 1st and 2nd position of the "new" <tr> element:
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);

// Add some text to the new cells:
cell1.innerHTML = "NEW CELL1";
cell2.innerHTML = "NEW CELL2";

}

setInterval(rowGenerator, 1000);
Reece
  • 396
  • 3
  • 11
  • I do have a collection of data in JSON, but for the sake of simplicity, isn't is possible to print out "Hey" in a new table row every 1 second? – user3624894 May 15 '14 at 13:23
  • works man <3.. I will accept the answer in 2 mins when SO allows me – user3624894 May 15 '14 at 13:28
  • 1
    What is the closure in the last line of code for? Wouldn't it work the same if you simply wrote `setInterval(rowGenerator, 1000);`? – rhino May 15 '14 at 13:32
1

In your snippet, you are effectively outputting HTML into a javascript function. That's not going to achieve what you want.

There are quite a few ways to do it, but here's one:

Give your container table an ID so you can access it easily in JS

<table id="containerTable"></table>

Then you can grab the element and append to innerHTML

<script type="text/javascript">

function myFunction()
{
    document.getElementById('containerTable').innerHTML += "<tr><td>Hey</td></tr>";    
}

setInterval(myFunction, 1000);

</script>

Now you're going to need to work out how to communicate with your server in order to achieve your user list. Start reading into using AJAX with PHP: http://www.onextrapixel.com/2012/02/06/a-beginners-guide-to-using-ajax-in-your-website/

Or even consider using jQuery if you want: http://webdevelopingcat.com/jquery-php-beginner-tutorial-ajax/. Why? http://sixrevisions.com/javascript/the-power-of-jquery-with-ajax/

Josh Davenport-Smith
  • 5,456
  • 2
  • 29
  • 40
1

What you're asking for is to perform an AJAX call every second to select all users and display them on your page.

You're asking for something like this:

setInterval(function()
{
    updateTable();
},1000);

Where updateTable contains the AJAX call that performs a POST to a specific function on a specific server-side page that will query the database and return an object (JSON I suggest) which you can parse in the client to replace the table with the new data.

You can make the AJAX with Raw JavaScript but I really recommend using jQuery to achieve the task but the earlier link shows how to do it with JavaScript only since the question is tagged without jQuery.

This is okay for a very low number of users, once you reach a decent amount of users the overload of the database queries and the posts will be overwhelming, even with low number of users the performance and the lag will probably begin to be noticeable by the user.

What you want to do is to NOT check every second if new users exists, instead you want the server to tell you once it happens. It means you want the server to push a notification to the client once a new user appears, that way you loose the overload but get perfect precision of when new users signs up.

Creating push can be hard for less-advanced users but is much better for a decent amount of users. What you're doing right now is called long-polling. You should read more about the push technology.

Before you (and after) you read more about the phenomena you should ask yourself: do you really need to update the user table? Does a new user matter that much that it can't wait until the next refresh?

Jonast92
  • 4,964
  • 1
  • 18
  • 32
1

You are approaching the problem at hand wrongly. First you have to understand how a website works. The code on the server side (PHP) is run once per request anything you echo will become a static part of the HTML document.

And because javascript runs on the client, you simply cannot mix and match PHP & javascript like the way you are trying.

What you probably wanted to do was to make a XHR request to a PHP interface (eg. a file named updates.php) that responds with the new information you want.

Try to look up DOM and XHR.

If you are looking for an easy way, look into jquery - BUT YOU STILL NEED TO UNDERSTAND WHAT DOM IS AND THE PAGE LIFE-CYCLE!

EJTH
  • 2,178
  • 1
  • 20
  • 25
1

Using setInterval, you can repeat the execution of a function:

setInterval(function() {
    console.log("test");
}, 1000);

As for your function body, bear in mind that the PHP is executed once only. If you wish to update the table, you need to:

  • make an AJAX call to your backend server or any other service that will provide the current state of the table's contents
  • modify the DOM of the table

The frontend code for the AJAX call could look like this:

setInterval(function() {
    var xhr = new XMLHttpRequest();
    xhr.onload = function(data) {
        // DOM manipulation goes here
    };
    xhr.open("get", "/tableContents.php", true);
    xhr.send();
}, 1000);

As for the DOM manipulation part, this depends on what format your PHP backend will return. Let's assume it's this JSON:

[
    {"value": 10, "label": "foo"},
    {"value": 20, "label": "bar"}
]

The DOM manipulation could look like this:

function(data) {
    var i, j = data.length, html = "";
    for(i = 0; i < j; ++i) {
        html += '<tr><td>' + data[i].label + '</td><td>' + data[i].value + '</td></tr>';
    }
    document.getElementById("myTableContents").innerHTML = html;
}

In short: iterate over the server's response and build the new HTML. Then, replace the old HTML with the new one.

The above also assumes your HTML already contains a matching table:

<table>
    <thead>
        <tr>
            <th>Label</th>
            <th>Value</th>
        </tr>
    </thead>
    <tbody id="myTableContents"></tbody>
</table>

Of course, the backend could as well generate a ready HTML, in which case the parsing of the returned data is not needed at all - you just replace the HTML.

Also, as a side note: I would advise against making HTTP requests every second; in case of a high traffic moment, the server could take longer than a second to respond, in which case you'd effectively flood it with requests it wouldn't manage to handle effectively. Calling the new request in the previous request's callback might be a better idea - this way you'd guarantee that a new request is sent only after the previous one has already been handled.

mingos
  • 23,778
  • 12
  • 70
  • 107
0

What you need to do is make 1 sep. page from where you can fetch latest content and call ajax on that page lets say you want to show name fields.

so first make 1 new page called ajax.php

<?php
 echo "<tr>";
 echo "<td>".$YOUR_DYNAMIC_VALUE_VARIABLE."</td>";
 echo "</tr>";
?>

You need to run your query to get latest results then need to improve your javascript

<script type="text/javascript">
function myFunction()
{
    $.post('ajax.php',{},function(r){
        $('#containerTable').html(r);
    });

}

setInterval('myFunction()', 1000);

</script>

Make sure jQuery is included in your page.

Mohit Bumb
  • 2,466
  • 5
  • 33
  • 52
0

Php will be executed once on when you open a page. So you can not re-execute that php lines with javascript. You have to make a request if you want to get a response.

If you want to reload / refresh your div every second, just use create element or make a request to php-file / route.

Javascript: (jquery)

function myFunction() {
    var $newElement = $('<tr><td>Hello!</td></tr>');

    $newElement.appendTo($('#your-table'));
}

setTimeout(function(){
    myFunction();
}, 1000);

Javascript (jquery) + Php

function myFunction(){

    $.ajax({
        url:'your-php-file.php', 
        dataType: 'html',
        success: function(response){
            $('#your-table').append(response);
        }
    });

}

setInterval(function(){
    myFunction();
}, 1000);

<?php
//your-php-file.php

echo "<tr><td>Hello!</td></tr>";

Second example is making request to your php file everysecond and waits for it's response so, javascript can append returned response.

miken32
  • 42,008
  • 16
  • 111
  • 154
Canser Yanbakan
  • 3,780
  • 3
  • 39
  • 65
0

here is a fiddle doing what you want: http://jsfiddle.net/jr3UA/

Basically you want

window.setInterval not time out

but you also need to fix the function you call myFunction as that won't parse valid JavaScript

DrogoNevets
  • 1,456
  • 3
  • 18
  • 34