5

I have the following code and it works great, I just want to convert it to live so it updates every 10 seconds or so without a page refresh, I'm guessing I'll need to use AJAX or Jquery but I lack the knowledge on how to do so.

=====VIA <?php include("database.php"); ?>====
<?php
// Create connection
$con=mysqli_connect("ip/host","user","pass","db");
// Check connection
if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>

====ON THE PAGE====
<? php

$result = mysqli_query($con, "SELECT * FROM sql347511.1 ORDER BY ID DESC LIMIT 1;");

while ($row = mysqli_fetch_array($result)) {
    echo "<div class='infobox_data'>Temperature: ".$row['TEMP']."&deg;C</div>";
    echo "<div class='infobox_data'>Humidity: ".$row['HUMID']."%</div>";
    echo "<div class='infobox_time'>Captured: ".date("g:i:s a F j, Y ", strtotime($row["TIME"]))."</div>";
}

mysqli_close($con); ?>
Sam
  • 185
  • 1
  • 3
  • 16

2 Answers2

7

Got it working, thanks for the help everyone.

Javascript

$(document).ready(function(){    
    loadstation();
});

function loadstation(){
    $("#station_data").load("station.php");
    setTimeout(loadstation, 2000);
}

station.php

<?php
include ("database.php");

$result = mysqli_query($con, "SELECT * FROM sql347511.1 ORDER BY ID DESC LIMIT 1;");

while ($row = mysqli_fetch_array($result))
    {
    echo "<div class='infobox_data' id='infobox_temp'>" . $row['TEMP'] . "&deg;C</div>";
    echo "<div class='infobox_data' id='infobox_humid'>" . $row['HUMID'] . "%</div>";
    echo "<div class='infobox_time'>At " . date("g:i:s a F j, Y ", strtotime($row["TIME"])) . "</div>";
    }

mysqli_close($con);
?>

Where to put the data

<div id="station_data"></div>
Sam
  • 185
  • 1
  • 3
  • 16
  • This is a working solution. Did you test it on large scale model, did you try to run on multiple PC. I got on 20PC over a 3000 connection a my server CPU is getting 100% worikng – rtstorm Aug 28 '18 at 14:00
0

You can make inputs from div on double click and then get this inputs value through jquery:

$().val;

then using ajax send this value to php:

$.ajax({
    url: 'url_to_php_which_update_mysql',
    data: {'data': 'value_from_input'},
    cache: false,
    success: function(response){
        $(input).val(response);
    }
});

And in php file you need to upload $_GET['data'] in Database

  • Thanks Masiama, any chance you could elaborate more on the code required? – Sam Jul 25 '14 at 04:12
  • How would I change or convert my existing code to make it work with the AJAX request? – Sam Jul 25 '14 at 07:07
  • @Sam Do you have textbox on page? –  Jul 25 '14 at 09:58
  • No, at the moment I'm just echoing the result into a
    should I change it to an input and do it that way?
    – Sam Jul 25 '14 at 10:14
  • You need to gve unique id for every
    and them you $('this_id').val(); to get value and then use ajax which is in my answer.
    –  Jul 25 '14 at 13:42