2

I have a variable $salary which is dynamic. How can I refresh specific div every 5seconds.

index.html

<html>
    <body>
        <img src="<?php echo $filename.'.jpg'; ?>" />
        <p id="salary"><?php echo $salary; ?></p>
    </body>
</html>

Is there any javascript/jquery way to refresh #salary only. Please help..

schutte
  • 1,949
  • 7
  • 25
  • 45
  • Possible duplicate of [change php variable with ajax](https://stackoverflow.com/questions/20572601/change-php-variable-with-ajax) – dustytrash Sep 21 '18 at 14:27
  • 1
    If you need to keep the server and client data in sync to this level I'd suggest using WebSockets instead. AJAX polling scales terribly badly, and will eventually DDOS your server. – Rory McCrossan Sep 21 '18 at 14:32

4 Answers4

6

You can execute an ajax call:

function ajaxCall() {
    $.ajax({
        method: 'POST',
        url: 'path/to/asyncHalndler.php',
        data: { ... },
        success: function (data) {
            if (data) {
                $('#salary').html(data);
            }
        }
    });
}

// Execute ajax call every 5 seconds
setInterval(function() {
    ajaxCall();
},5000);
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
kapantzak
  • 11,610
  • 4
  • 39
  • 61
2
var salary = document.getElementById('salary');

Now, the value of your variable salary will be the DOM node where you would like to change the value. When you get new data, you can refresh text inside your p tag with salary id by adding salary.innerText = yourNewValue;

This is pure JavaScript way of updating that element with id.

Lazar Nikolic
  • 4,261
  • 1
  • 22
  • 46
1

You will need an jquery ajax call for that. first you should create php file get_salary.php where you send id from jquery ajax if you want to update the salary for unique id:

in get_salary.php you need to get salary from database so the code in this php file will be like that

$id = $_POST['ID']
$query = mysql_query("SELECT * FROM sallaries WHERE id='$id'") or die("Can't connect");
$fetch = mysql_fetch_array($query)
$salary = $fetch['salary']
echo $salary

after that you will need javascript file(e.g script.js) from where you will send the request and id to the get_salary.php and grab the data from it, after that you will be able to update salary in html, so code in javascript file will be like that:

function updateSalary(){}
var id=25;
$.ajax({
    url: "get_salary.php",
    type: 'POST',

    //sending id
    data:'id='+id,
    success: function(result){

        //updating html
        $("#salary").html(result);
    }
});
}

//setting interval to update in every second
setInterval(updateSalary, 1000)

so it will update your salary in the div

jwebb
  • 1,119
  • 12
  • 23
Dato DT
  • 129
  • 1
  • 1
  • 9
1

It's better to use ajax way. But if u are looking for a very simple solution then jQuery .load will be the best

setInterval($("#salary").load("<url to get the value>"), 1000);
Shreesha
  • 71
  • 2
  • 5