3

I'm new in ajax. I have try to find solution but failed. I want to refresh MySQL query in every second but how? I have no idea how to do it so please help me.

CODE

$sql="SELECT * FROM `user`";
$result = mysql_query($sql);


while($row = mysql_fetch_array($result)) {
  echo  $row['fname'];
  echo  $row['email'];

}
3
  • In javascriot,you can use var timer=setInterval(functionName,1000) to call the PHP Skript by Ajax. I can't say more you don't give many details to work with. Another more brutal solutuion: set the meta refresh tag in HTML.
    – Adder
    Jun 27, 2014 at 12:13
  • @Khushboo I know it can handle with ajax but i have no idea about ajax coding.
    – Ayaz Shah
    Jun 27, 2014 at 12:14
  • I have add example in answer
    – Khushboo
    Jun 27, 2014 at 12:15

3 Answers 3

11

Try below

<div class="result"></div>

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
    function refresh_div() {
        jQuery.ajax({
            url:'YOUR PHP page url',
            type:'POST',
            success:function(results) {
                jQuery(".result").html(results);
            }
        });
    }

    t = setInterval(refresh_div,1000);
</script>
9
  • About as simple as it gets, but I would add a <div class="result"></div> to your answer so OP knows to put it on the page somewhere. Jun 27, 2014 at 12:16
  • oh.. sure. I am adding that
    – Khushboo
    Jun 27, 2014 at 12:17
  • What you have tried ? Please paste your code in your question
    – Khushboo
    Jun 27, 2014 at 12:25
  • @Khushboo I have put my php code in <div class="result"></div> and add your function but it does not working..
    – Ayaz Shah
    Jun 27, 2014 at 12:28
  • @AyazShah Do you have the jQuery library embedded on your page? Jun 27, 2014 at 12:28
2

You can use jQuery with $.ajax() to get data, setInterval() to call a function every x seconds and $.html() to insert your data into an element.

Here is an example :

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

function getUsers()
{
  $.ajax({
    url: 'myphppage.php',
    type: 'post',
    success: function(data) {
      $('.htmlelement').html(data);
    }
  });
}

<div class="htmlelement">data will appear here</div>

.htmlelement is an HTML element (ex: a div with a class "htmlelement"), where your results will be inserted.

0

Brutal solution: set the meta refresh tag in HTML:

<meta http-equiv="refresh" content="1">
1
  • This is refreshing the whole page instead of just one MySQL query. Not good and definitely doesn't answer the question properly.
    – momal
    Dec 8, 2017 at 12:09

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.