Rofi Fathurrohman
Rofi Fathurrohman

Reputation: 167

Auto refresh input field with javascript

I wan't auto refresh in input field. can you help me for that?

Example: Here is my php code

<?php
$result = mysql_query("SELECT * FROM datapy ORDER BY No DESC LIMIT 0,1");
$showlast = mysql_fetch_array($result);
?>
<input type="text" value="<?php echo $showlast['nilai_1']; ?>" id="last">

What should I do if I want to make the input field into an auto refresh to get last data from database. note: i will refresh on input field only

Upvotes: 0

Views: 3900

Answers (2)

Dohd
Dohd

Reputation: 379

Your javascript code and ensure your jQuery library is loaded.

var url = // Source of data url 
var sec = // Time interval in seconds for autorefresh 
$(function() { 
    setTimeout(function() {
        $('#last').load('url' + ' #last');}, sec );
});

Take note of the space in ' #last' otherwise it will return an entire page.

Upvotes: 0

ash__939
ash__939

Reputation: 1599

You can use the setTimeout().

Your html content

 <input type="text" value="" id="last">

Add the javascript

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

function refresh_field() {
  $.get("ajax_file.php", function(data) {
    $("#last").val(data);
    window.setTimeout(refresh_field, 1000);
  });
}

Where the ajax_file.php is a php file that will feed the value to be updated.

<?php
$result = mysql_query("SELECT * FROM datapy ORDER BY No DESC LIMIT 0,1");
$showlast = mysql_fetch_array($result);
echo $showlast['nilai_1'];exit;
?>

Upvotes: 1

Related Questions