2

I'm building an app with JQuery Mobile. I have a page called list.php which gets data from server with PHP. I need the script to run every 15 seconds and notify user if there are changes in database. I am beginner with PHP and Javascript so I have no idea how to do this or if it is even possible.

This is the code I'm currently using.

<?php
$number = $_GET['number'] ;

mysql_connect('localhost','username','password');
$link = mysql_connect('localhost', 'username', 'password');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}


//specify database 
mysql_select_db("database") or die("Unable to select database"); 

// Build SQL Query 
$query = "select * from table where tablenumber = \"$number\" and state = 0  
  order by time";

 $result = mysql_query($query) or die("Couldn't execute query");

?>





<!DOCTYPE html> 
<html> 
    <head> 
    <title>title</title> 

    <meta name="viewport" content="width=device-width, initial-scale=1"> 

    <link rel="stylesheet" href="http://code.jquery.com/mobile/1.0.1/jquery.mobile-1.0.1.min.css" />
    <script src="http://code.jquery.com/jquery-1.6.4.min.js"></script>
    <script src="http://code.jquery.com/mobile/1.0.1/jquery.mobile-1.0.1.min.js"></script>

</head> 
<body> 


<div data-role="page">

    <div data-role="header" > 
    <h1>Transpanel</h1>
</div>
    <div data-role="content">   


        <div data-role="collapsible-set">

    <?php 
// display the results returned
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
?>
<div data-role="collapsible" data-theme="b" data-content-theme="d">
   <h3><?= $row["OSO"] ?></h3>
   <p><?=$row["AIKA"]?><p>
</div>
<?php } ?>



</div>


    </div><!-- /content -->

</body>
</html>
user1256852
  • 53
  • 4
  • 13

6 Answers6

1

Simply use AJAX, and call the AJAX function every 15 seconds by setInterval('checkfornew()', 15000);. So:

function checkfornew() {
    var http = new XMLHttpRequest();
    var url = "get.php";

    http.open("GET", url, true);

    //Send the proper header information along with the request
    http.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8");
    http.setRequestHeader("Content-length", params.length);
    http.setRequestHeader("Connection", "close");

    http.onreadystatechange = function() {
        if(http.readyState == 4 && http.status == 200) {
            if(http.responseText != "") {
                alert(responseText);
            }
        }
    }
    http.send(params);
}

and change the body-tag to

<body OnLoad="setInterval('checkfornew()', 1500);">
Dion
  • 3,145
  • 20
  • 37
  • instead of alert() you can of course print it out in an element with e.g. `document.getElementById('status').innerHTML = http.responseText;` – Dion Apr 05 '12 at 11:12
  • currently all the php is in the same file as everything else. Should I make a new php file with the sql query which that xmlhttprequest will get? The collapsing content part is important in my app, is it possible to make that widget work with xmlhttprequest? Sorry for my stupid questions :D – user1256852 Apr 05 '12 at 11:20
  • Yes this has to be in a different PHP-file. The function gets all the content which this PHP-file prints out and stores it in the http.responseData variable. This you can put into an element (see comment above) or a textfield or something else. – Dion Apr 05 '12 at 11:22
  • How can i make this `

    = $row["OSO"] ?>

    =$row["AIKA"]?>

    ` work with xmlhttprequest? I can't just put it to get.php as it is, can I?
    – user1256852 Apr 05 '12 at 11:30
  • @Bondye - this answer DOES address the OP's request. A user's data limit is their own issue. The problem is the question ("do something every 15 seconds"), not the answer. – ghoti Apr 05 '12 at 11:42
  • Cron Jobs? Cron Jobs are totally different from what is requested. Cron Jobs are for example to delete old mysql_entries every month. Cron Jobs run on the server and don't have anything to do with clients. – Dion Apr 05 '12 at 11:59
  • @user1256852 better print out this structure in the PHP file and put it into a simple
    in HTML.
    – Dion Apr 05 '12 at 12:00
  • He's using jQuery (jqm) at least use `$.ajax` method. (or `$.getJSON` or similar) – VDP Apr 05 '12 at 12:44
0

Why not instead modify your update logic so that it kicks off a notify thread that notifies your users? Polling in this way is very inefficient.

Scott C Wilson
  • 19,102
  • 10
  • 61
  • 83
  • That is theoretically the best option... But using php & javascript I don't know if it is possible... except when u use websockets (which is not supported on the majority of mobile devices) How would you allert the user when an update is made (from the backend?) – VDP Apr 05 '12 at 13:23
0

If you are on a linux machine add the script to a cronjob

EDIT AFTER COMMENT

# crontab -e
00 * * * * /usr/local/bin/php /home/john/myscript.php

or if it is on url

 00 * * * * lynx -dump http://www.thegeekstuff.com/myscript.php
NoobTom
  • 555
  • 1
  • 9
  • 21
0

The code on the server can't run by itself and notify the browser of changes, it simply isn't built into the HTTP protocol.

A simple solution would be to simply reload the page every 15 seconds:

<body onload="window.setTimeout(function(){document.location.reload(true);},15000)">

If you want the browser to get updates without reloading the page, you should look into AJAX. Basically you set up another PHP page that can return the changes, for example in JSON format. Using Javascript in the page (e.g. the ajax method in the jQuery library), you can get the changes and let the script react to them.

Guffa
  • 687,336
  • 108
  • 737
  • 1,005
0

In order to update every 15 second you better use cron jobs. In order to notify user whenever database is changed, here is my solution: Create another table which contains records of actions that user have made. Another option is implementing hash function over the db, but I don't know how efficience that would be.

0

I think you are trying to create a mobile web app. Loading whole page every 15 seconds via setTimeout() might burden your browser with unnecessary loads, its like every 15secs clicking on browser refresh button annoying!!! Instead, all you need to do is use json web-services and parse the php-json response in jquery.getJSON method. use 2 different files: list.html for jquery & list.php for json-web-services. Below is an example to parse a json with response result:{key1:OSO;key2:AIKA}

$(document).ready(){ 
//always include jquery code in $(document).ready(){ your javascript here} loads faster
setInterval(function() {
    $.getJSON('list.php', function(json) {
    //assuming list.php resides with list.html directory
    //console.log(json)
      console.log(json.result.key1);
       console.log(json.result.key2);

    });
  }, 15000); //request list.php every 15 seconds
});
nuthan
  • 465
  • 2
  • 5
  • 19
  • What do I need to change in this code to make this work? I have a list.php file which gives me results like: [{"key1":" streetname 123, City ","key2":"2010-03-11 10:00:00"}] But when I paste this code to my list.html it shows nothing? – user1256852 Apr 10 '12 at 05:38
  • did u remove the comments on console.log()? did u check the browser console? plz paste ur list.html in pastebin.com and send the pasted link... – nuthan Apr 10 '12 at 05:53
  • it still doesn't work. When i go straight to list.php it prints out [{"key1":" streetname 123, City ","key2":"2010-03-11 10:00:00"}], but list.html just doesn't show anything... – user1256852 Apr 11 '12 at 04:38
  • I believe u r facing Access-Control-Allow-Origin [CORS](http://stackoverflow.com/questions/3595515/xmlhttprequest-error-origin-null-is-not-allowed-by-access-control-allow-origin) problem. Run the `http://hostname/list.html` (via apache server), instead of `file:///blah/blah/list.html` – nuthan Apr 11 '12 at 05:16
  • files are located on external server if that's what you mean? – user1256852 Apr 11 '12 at 05:48
  • Doesn't matter files on external server or development server. What i mean is, access the list.html via web-server, like u usually access .php files. Got it? – nuthan Apr 11 '12 at 05:53
  • When i look at the browser console it shows "streetname 123, 2010-03-11 10:00:00" but it doesn't show anything in browser and console only shows 1 row, but there are much more rows in list.php – user1256852 Apr 11 '12 at 05:57
  • This is your json response `[{"key1":" streetname 123, City ","key2":"2010-03-11 10:00:00"}]`. code i posted will parse only this structure, if u need to parse other keys/values... u have to code ur own parser dynamically..... U see console printing values, u r almost done!!! all u need is learn some jquery [load](http://api.jquery.com/load/) div tags to handle those keys/values n display in html tags. – nuthan Apr 11 '12 at 07:11
  • my json response is [{"key1":" streetname 123, City ","key2":"2010-03-11 10:00:00"},{"key1":" streetname 123123123, City2 ","key2":"2011-04-01 12:03:00"}] but console shows only the first one – user1256852 Apr 11 '12 at 07:31