1

So I got this website with PHP code that reads a file(that has JSON format) and then sends it to a javascript functions which prints it in a table. This works fine for me, but I want to press this button again so that I get an updated table, the file itself get's updated about each 30 minutes. This is my code:

index.php

<?php
function clean($string){
    return json_decode(rtrim(trim($string),','),true);
}

function getLog(){
    $logLines = file('../../../home/shares/flower_hum/humid.log');
    $entries = array_map("clean",$logLines);
    $finalOutput = ['log'  => $entries];
    $json = json_encode($finalOutput);
    return $json;
}
?>

<html>
    <head>
        <script src="script.js" type="text/javascript"></script>
        <script src="sorttable.js" type="text/javascript"></script>
        <link rel="stylesheet" type="text/css" href="style.css">
        <meta charset="UTF-8">
        <title>title</title>
    </head>
    <body>

        <button type="button" onclick='createTable(<?php getLog(); ?>)'>Generate log</button>
        <br><br>
        <div id="logDiv"></div>
    </body>
</html>

script.js

function createTable(jsonObject) {
//Removes existing tables if there is any.
var myNode = document.getElementById('logDiv');
    while (myNode.hasChildNodes()) {
            alert("logDiv has nodes, removing them now!")
            myNode.removeChild(myNode.firstChild);
    }

 //...Code that prints table
}

So If I press the button once, a table is generated, but If I press it again, nothing happends, even though the JSON file has been updated. If I refresh the page, it works again. I'm not sure why this isn't working as I expect it too. A new call to my php function getLog(); should read the file a new time and generate a new JSON Object.

bubelf
  • 41
  • 3
  • 3
    You can't mix PHP and javascript. PHP runs before the page loads, javascript after. You want to look into an ajax call to get updated information from the server. – aynber Sep 26 '16 at 18:59
  • Oh no. Dont mess with client/server side code. You need to either reload or send an ajax request to update the json – Jonas Wilms Sep 26 '16 at 18:59
  • You're putting the JSON into an HTML attribute, which will cause bad HTML to be generated if there's an apostrophe anywhere in your JSON. It'd probably be easier to save the JSON to a variable inside a ` – Hayden Schiff Sep 26 '16 at 19:00
  • Or call `htmlspecialchars()` in `clean()`. – Barmar Sep 26 '16 at 19:04

1 Answers1

0

You need to distinguish between server side code and client side code.

PHP code is run on the server and it generates some output (for example a HTML page or some JSON data) which is sent to the client (usually a browser) you are using to access the page.

In your scenario the Javascript code is run on the client (in your browser). When your browser opens a page/URL it sends a request to the server, the server runs the PHP code and returns the HTML page containing the Javascript code including the JSON data as the parameter of the createTable() function. The PHP code never leaves the server, in fact, your browser and Javascript code don't know anything about the PHP code (or any server code).

Every time you press the button your createTable() function runs and shows the data on the page, however that data never changes as it is part of the "static" HTML page that the server sent to your browser. When you refresh the page you send a new request to the server and the PHP code runs again, generates the page again and possibly provides some new JSON data.

To better understand what is happening behind the scenes you can Inspect the HTML that you get from the server and you will understand why the JSON data never changes until the page is refreshed. In most browsers you can do that by pressing F12 and opening the HTML/DOM/Elements tab.

If you want to retrieve new data without reloading the page you have to look into AJAX requests. With simple words AJAX is a technique to retrieve data and update the page as needed without a page reload.

Ma3x
  • 5,761
  • 2
  • 17
  • 22
  • Alright, so what I need to do is move my PHP into a separate file and then make my javascript make a GET request (with Ajax) to the php to retrieve the JSON Object? – bubelf Sep 26 '16 at 19:31
  • @bubelf: yes, you need a php file that will just send you the JSON data. Then you call that file's URL from Javascript with AJAX to get just the JSON data and then you call your `createTable` function from the AJAX response callback function and you pass the received JSON as parameter. – Ma3x Sep 26 '16 at 19:33
  • I done some research about Ajax now and tried implementing and well...it almost works. The only problem I'm having is that my old method for converting my log file into JSON no longer works and I have no idea why this is happening. Whenever my button is cliked my js sends a get request and calls upon the getLog() method. All I changed in the method was from return to just echo instead. But all I get is {"log":null}. – bubelf Sep 26 '16 at 20:46
  • @bubelf: You will have to debug the php code to find out. Have you moved the original php file and maybe the log relative path is wrong now? – Ma3x Sep 26 '16 at 20:48
  • I have debugged it 2 hours now, still don't get it. No, the locations is right, I can print it as an array, but I can't seem to convert it into a JSON Object. – bubelf Sep 26 '16 at 20:54
  • I don't understand, I changed nothing in the php or the log itself, it should work exactly the same... – bubelf Sep 26 '16 at 20:55
  • @bubelf: Could be wrong headers. Make sure there is no other output except the JSON as well. See this: http://stackoverflow.com/questions/4064444/returning-json-from-a-php-script – Ma3x Sep 26 '16 at 20:58
  • Yes, well I can se with the console in the web browser that I get HTTP code 200, all is OK and header says JSON Object. The problem is that the Object is null in it's value. I can read the file but when I am converting it something goes wrong. – bubelf Sep 26 '16 at 21:01
  • @bubelf: can you open a new question and post the updated code, both the PHP and the JS AJAX related code. Plase include the mentioned (wrong) response as well. – Ma3x Sep 26 '16 at 21:05
  • Done https://stackoverflow.com/questions/39712501/formatting-json-formatted-text-file-in-php – bubelf Sep 26 '16 at 21:15