Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grab Server Code on refresh every few seconds and update form elements

To start off here's how the application works: (note: there are multiple users on the page like Patient M, Patient E, so on)

1) Next to Patient X's name is a button labeled Check In. This is logged in the server side.

2) Upon clicking the Check In button , the user is then presented with a dropdown (replacing the initial button) with the multiple locations the user could choose. Upon selecting a location from the select, the server side is updated again.

3) The user then might decide to choose multiple locations, repeating step 2

4) At the end, when the user is done selecting locations, he clicks on the Check Out button in the same select where the user had clicked locations in steps 2 and 3, titled Check Out. Upon clicking this, it is sent to checkloc.php and logged.

5) Finally, the dropdown dissapears and the words Checked Out appear.

Unfortunately, the problem is that right now if I am Computer 1, and go through the process of clicking Check In, selecting a location, and checking out, this is completely apart from Computer 2 doing this.

Heres a diagram:

what I want to happen

So basically I need a way to grab the server code every few seconds and update the form elements with the current values. I'm a pretty new programmer, so code and tutorials would be extra helpful. Also, like I just mentioned, I am a new programmer, so if my code could be cleaned up in any ways that would be fantastic.

Thanks for any and all help! I'm glad to clarify any questions you have!

Heres the code:

<script src="http://code.jquery.com/jquery-1.8.2.js"></script>

<script type="text/javascript">
$(document).ready(function() {
$('.locationSelect').hide();  // Hide all Selects on screen
$('.finished').hide();        // Hide all checked Out divs on screen
$('.checkOut').hide();

$('.checkIn').click(function() {
    var $e = $(this);
    var data = $e.data("param").split('_')[1] ;
    // gets the id  of button
    // You can map this to the corresponding button in database...
    $.ajax({
        type: "POST",
        url: "checkin.php",
        // Data used to set the values in Database
        data: { "checkIn" : $(this).val(), "buttonId" : data},
        success: function() {
            // Hide the current Button clicked
            $e.hide();
            // Get the immediate form for the button
            // find the select inside it and show...
            $('.locationSelect').show();
            $('.checkOut').show();
        }
    });
});

$('.locationSelect').change(function() {
    $e = $(this);
    var data = $e.data("param").split('_')[1] ;
    // gets the id  of select
    // You can map this to the corresponding select in database...
    $.ajax({
        type: "POST",
        url: "changeloc.php",
        data: { "locationSelect" : $(this).val(), "selectid" : data},
        success: function() {
            // Do something here
        }
    });
});

$('.checkOut').click(function() {
    var $e = $(this);
    var data = $e.data("param").split('_')[1] ;
    // gets the id  of button
    // You can map this to the corresponding button in database...
    $.ajax({
        type: "POST",
        url: "checkout.php",
        // Data used to set the values in Database
        data: { "checkOut" : $(this).val(), "buttonId" : data},
        success: function() {
            // Hide the current Button clicked
            $e.hide();
            $('.locationSelect').hide();
            // Get the immediate form for the button
            // find the select inside it and show...
            $('.finished').show();
        }
    });
});

});
</script>

and html:

<button class="checkIn" data-param="button_9A6D43BE-D976-11D3-B046-00C04F49F230">Check In</button>

<form method='post' class='myForm' action=''>
  <select name='locationSelect' class='locationSelect' data-param="location_9A6D43BE-D976-11D3-B046-00C04F49F230">
    <option value="0">Select a location</option>
    <option value='1'>Exam Room 1</option>
    <option value='2'>Exam Room 2</option>
    <option value='3'>Exam Room 3</option>
    <option value='4'>Exam Room 4</option>
  </select>
</form>
<button class="checkOut" data-param="cbutton_9A6D43BE-D976-11D3-B046-00C04F49F230">Check Out</button>

<div class='finished' style='color:#ff0000;'>Checked Out</div>

heres the server side code ( I split it into three pages just for testing)

checkin.php

<?php

date_default_timezone_set('America/Denver');

$apptid = $_REQUEST['buttonId'];
$currentlocationstart = date("Y-m-d H:i:s"); 

if(isset($_REQUEST['checkIn'])){
    $checkin = 0;
}


$hostname = 'localhost';

$username = '*******';

$password = '******';


$conn = new PDO("mysql:host=$hostname;dbname=sv", $username, $password);

$sql = "UPDATE schedule SET currentlocation = ?, currentlocationstart = ? WHERE apptid= ? ";
$q = $conn->prepare($sql);
$q->execute(array($checkin,$currentlocationstart, $apptid));


?>

locationchange.php

<?php

date_default_timezone_set('America/Denver');

$apptid = $_REQUEST['selectId'];
$currentlocationstart = date("Y-m-d H:i:s"); 

if(isset($_REQUEST['locationSelect'])){
    $currentLocation = $_REQUEST['locationSelect'];
}


$hostname = 'localhost';
$username = '*****';
$password = '*******';


$conn = new PDO("mysql:host=$hostname;dbname=sv", $username, $password);

$sql = "UPDATE schedule SET currentlocation = ?, currentlocationstart = ? WHERE apptid= ? ";
$q = $conn->prepare($sql);
$q->execute(array($currentlocation,$currentlocationstart, $apptid));

?>

and checkout.php

<?php

date_default_timezone_set('America/Denver');

$apptid = $_REQUEST['buttonId'];
$currentlocationstart = date("Y-m-d H:i:s"); 

if(isset($_REQUEST['checkOut'])){
    $checkin = 1000;
}


$hostname = 'localhost';

$username = '*********';

$password = '********';


$conn = new PDO("mysql:host=$hostname;dbname=sv", $username, $password);

$sql = "UPDATE schedule SET currentlocation = ?, currentlocationstart = ? WHERE apptid= ? ";
$q = $conn->prepare($sql);
$q->execute(array($checkin,$currentlocationstart, $apptid));


?>
like image 650
Muhambi Avatar asked Nov 10 '12 00:11

Muhambi


3 Answers

You are referring to a methodology known as a "heartbeat". I am going to post an example here, but first I'd like to give you a few pointers since, as you said, you are a new dev :).

1) With JQuery, try to avoid using the class selector. It's notoriously slow. Use the id selector wherever possible, or the nodename selector with a narrowed search scope if it isn't possible. The browser uses the ID as a sort of "index" or "key" to the dom element, so it is the fastest search.

2) PRELOAD! Even if you are going to use class selectors, don't do

    $('.locationSelect')

Over and over. If you are going to reference the same DOM element more than once, do this:

    var locationSelect = $('.locationSelect'); //this creates a reference
    $(locationSelect).whatever() //this uses the reference

By doing this, you are only searching the DOM once. It won't seem like a big deal with smaller apps, but as your app becomes more and more complicated, it takes more and more time to search to DOM for elements. By using a reference, you only search once.

3) (Optional) I would RECOMMEND using an MVC platform like AngularJS (which is written by Google). MVC, or Model View Controller, allows you to update a "Model" (basically a JavaScript Object) and the "View" (the HTML) automatically adjusts its value using something called UI-Bindings. It's a great way to go about developing an app from the get-go, but if you are already knee-deep in plain-jane code, it may not be practical for you. I'd still take a look at their tutorial to see what it could offer you: http://docs.angularjs.org/tutorial/

Now on to your original question! Yes, this is completely possible with jQuery by using a methodology known as a heartbeat. A heartbeat allows you to emulate data persistence between the server and client. The more frequent the heartbeat, the more in-sync your clients will be, but the greater load on your webserver as well. It's a balancing act.
In a nutshell, it works something like this:

    setInterval(function(){
        $.ajax({
           url: 'heartbeatscript.php',
           method: 'post'
           //whatever data you want to send
        }).done(function(data){
           //do whatever with the returned result
        });
    },heartbeatInterval); //heartbeatInterval will be however many MS you want    

I would also recommend using JSON to communicate between the client and server. JSON is easy to parse on both ends, and on the client end it is simply the fastest mechanism for parsing bulk data. JSON is parsed directly into a JavaScript object because the notation is literally what JS uses to store object Data within the browser anyway. XML is also a good choice. Both are very easy to get started with:

Client Side: You can use jQuery to parse rudimentary XML:

    $('nodeName',xml);

You can parse JSON into a JSO like this:

    var JSO = JSON.parse(JSONString);                           
like image 96
Andrew Rhyne Avatar answered Oct 15 '22 04:10

Andrew Rhyne


Have a look at Socket.IO, because as the site says:

What is Socket.IO?

Socket.IO aims to make realtime apps possible in every browser and mobile device

Although Socket.IO is in NodeJS/Javascript, there's quite an conversation about using PHP with Socket.IO

like image 5
Koen. Avatar answered Oct 15 '22 02:10

Koen.


Basically it seems what you are looking to do is to update data from one machine on another machine without the need to do a page reload.

It is good that you already have some familiarity with AJAX, as that will probably be one of the ways you can implement your solution. What you are needing, in essence, is to poll the server from the webpages at some specified interval (maybe every second or every few seconds depending on your need). You can do this using AJAX.

When you poll this server, you can pull down data (HTML fragments, JSON data, whatever makes sense in your application) and use this data to update the page. So when a user makes an update on Computer 1, Computer 2 will be able to poll the server and pull in updates related to the data changes on Computer 1.

like image 2
Mike Brant Avatar answered Oct 15 '22 04:10

Mike Brant