How to call php from ajax in every second using Jquery

Few days ago, Mike emailed me and asked me how can i call a server script( php file) from jQuery in every second.Since, there was no built-in mechanism for this in jQuery, I came up with this solution of displaying time of server using Ajax, PHP and jQuery.You can use setinterval() method avaiable in javaScript to accomplish this task using jQuery.


View Live Demo

HTML Code:

<div align="center" id="timeval">--:--:--</div>
<button id="stop">Stop</button>

There are mainly two elements one is “div” with id “timeval” which displays the the time and the other one is “button” with id “stop” to stop the calling the PHP file in the regular interval.

JavaScript Code:

<script src="jquery.js"></script>
<script>
$(document).ready(function()
{
   //ajaxTime.php is called every second to get time from server
   var refreshId = setInterval(function()
   {
     $('#timeval').load('ajaxTime.php?randval='+ Math.random());
   }, 1000);

   //stop the clock when this button is clicked
   $("#stop").click(function()
   {
     clearInterval(refreshId);
   });
});
</script>

As you can see above, setInterval() function is used to call the php file in every second, where 1000 means 1000 millisecond which equals to one second.And, the load() function of jQuery is used to call the Ajax. And, you might be wondering why I’ve passed “randval” to “ajaxTime.php”, you can read this post of mine about the problem of getting same value from ajax. And when the button with id “stop” is called the clearInterval() functions clears the interval ID generated by setInterval() and stop calling the PHP file at regular interval.

PHP code :

<?php
   echo date("g:i:s A");
?>

As you can see the php code in the ajaxTime.php is fairly simple, it just displays the current server time.

You can download the demo by clicking here

23 thoughts on “How to call php from ajax in every second using Jquery

  1. akram

    Hello,
    How can i send another variable to ajaxtime.php.
    i did change in first fanction like this:
    var chatid=document.getElementById (usr);
    {
    $(‘#chat’).load(‘showmsg1.php?randval=’+ Math.random()+ ‘&u=’ + chatid);
    }, 1000);

    but it is not working now. can you help me to send another variable to ajaxtime.php?

  2. Doest it work with a single variable, I’ve a doubt with your function and furthermore have you included jquery framework in your project ??

  3. medo

    Hi,
    loved the post
    but can you do the same thing only this time ajax should refresh the page only when a database row is added ?
    as in chat

  4. The Post is very good..But Please guide how to send more than one element value from html form to php script using Ajax..

    I tried by adding ( for checkbox ) the code below the line of ( xmlhttp.send(“txtname=” + txtname.value) in ajaxFunction()–>

    xmlhttp.send(“gender=” + gender.value); //Posting gender to PHP File

    and tried to print $b = $_POST[‘gender’];
    echo $b;
    its not working..

    please guide ..
    Thank you…

  5. Thr above example is done using jQuery and it seems that you’re doing it also in traditional way..You can get some idea how to use ajax with jQuery from here

    http://docs.jquery.com/Ajax

  6. This is cool article. i like jQuery too. i try to write PHP Class to build jQuery Plugin automatically, so we can call php method/function from javascript using jQuery like this:
    var result=$.x_phpclass_method(var1,var2);
    or
    var result=$.x_phpfunction(var1,var2);
    I upload this class in jQuery Plugin in http://plugins.jquery.com/project/jqSajax

  7. @winoto…that is a very nice jQuery plugin..thanks for sharing the link…

  8. Zul

    Thanks for the code. It’s so usefull :)

  9. re: vsvnmurthy
    To send more than one element value from html form to php script using Ajax, in jQuery – load, you can do something like this,

    $(“#myID”).load(“test.php”,{“name” : “Adam” , “site”:”61dh.com”});

  10. Great article. Actually I had all of it and it was working in FF. But IE was not. I noticed your adding randal=. So I read the article you linked to as well.

    Both are great and it fixed my problems in IE.

    Thanks alot!!

  11. Amjad

    An Excellent effort but pls explain how can i get the same result in textfield instead of div.

  12. saltpetre

    Dude this script is perfectly..i was looking for smthing like this for the last couple of days thanks

    I need i more help…

    I m using this script int values in a table coming from mysql

    but the values are generated via a function the take 2 args and query the db and comes with a value which is update on the table every 1 sec via this scirpt.

    how can i use this script to do it for all the table entires

    my fucntion is

    function get_avail($lot_num, $type)
    {
    require (“settings/config.php”);//db connection info
    require (“settings/opendb.php”);//open connection to db

    //construct query

    $query = “SELECT * FROM” .” “. $lot_num .” “. “WHERE lot_type =” .” “.”‘”. $type .”‘”.” “. “and avail_flag =’1′”;
    $result=mysql_query($query);
    $avail=mysql_num_rows($result);

    echo $avail;

    }
    get_avail(“lot_a”,’purple’);

    plz help…thanks in advance

  13. echedey

    Thanks a lot! This howto has been very very useful for me :)

  14. your post help me alot
    thanks
    @asupna

  15. Hi, i was using the same script… but then i realize that if u keep the page open for an hour, the script would made… what… 3600 calls to the server?!

    For “security” reasons i have to change my script… I suggest to get the date(‘H’), date(‘i’) and date(‘s’) values with PHP and then increment and calculate the time with jQuery…

  16. hi

    hi a am unable to solve the ajax tripple droupdown how to solve this problemm

  17. Hi,

    Great code. Thanks Roshan.
    @Viktor – thanks for the useful tips for security.

    Thanks a lot.

  18. Very useful indeed, somehow I felt enlightened after reading this article. Many Thanks.

  19. Hello Friend I am here in Brazil and I really liked your article helped me a lot, I wonder if the clock is to continue after pressing the stop button?

  20. Gold

    I have a problem that drive me crazy .. and if some one can help .. it would be appreciated .. I have 2 pages .. page1,page2 .. page1 showing the information of page2 and continue to refresh every 5 seconds using this ajax .. page2 has javascript included and it works when I’m showing page2 only .. but when page1 calls page2 to show its contents .. the javascript dont work…I tried to include the javascript with both page1 and page2 but still wont work for me .. please help

  21. elyas

    its great tutorial it really helped.

    how can i assign the returned value of Ajax from php file to a JavaScript variable and do some calculations.

    for example i return the sum value of a field from myself table and i want to do some calculation with JavaScript on the page.

  22. Thanks thanks thanks i am looking for this.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>