PostMessage Calculator Primer Tutorial

PostMessage Calculator Primer Tutorial

PostMessage Calculator Primer Tutorial

We’re keen to revisit window.postMessage concepts, in terms of how it can be used to link web applications together with their own private messaging arrangement, that can be cross-domain, in its scope. We last touched on this with the TimeZone Country Places Data Tutorial if you want some other looks into this.

Today, we have to thank the Simple Web Worker for the huge basis of code for today’s work.

We like to simplify window.postMessage in our minds, as an alternative idea to …


  • <iframe id="myiframe" src="//www.ozemail.com.au/~mkuulma/PostMessage/index.html"></iframe>

    … HTML iframe element (src=[someHTML]) approach with a window.PostMessage External Javascript (src=[someExternalJavascript]) approach …

  • <script id="myscript" src="//www.ozemail.com.au/~mkuulma/PostMessage/main.js"></script>

    … and with that External Javascript, main.js, it sets up a messaging conduit via a Web Worker object

    var first = document.querySelector('#number1');
    var second = document.querySelector('#number2');

    var sfirst = document.querySelector('#snumber1');
    var ssecond = document.querySelector('#snumber2');

    var result = document.querySelector('.result');

    if (window.Worker) { // Check if Browser supports the Worker api.
    // Requires script name as input
    var myWorker = new Worker("worker.js");

    // onkeyup could be used instead of onchange if you wanted to update the answer every time
    // an entered value is changed, and you don't want to have to unfocus the field to update its .value

    first.onchange = function() {
    var aa='', bb='';
    if (ssecond.value == '-') {
    aa = '(';
    bb = ')';
    }
    myWorker.postMessage([first.value,ssecond.value + aa + second.value + bb, document.URL.split('#')[0].split('?')[0]]); // Sending message as an array to the worker
    console.log('Message posted to worker ... ' + document.URL.split('#')[0].split('?')[0]);
    };

    second.onchange = function() {
    var aa='', bb='';
    if (ssecond.value == '-') {
    aa = '(';
    bb = ')';
    }
    myWorker.postMessage([first.value,ssecond.value + aa + second.value + bb, document.URL.split('#')[0].split('?')[0]]);
    console.log('Message posted to worker ... ' + document.URL.split('#')[0].split('?')[0]);
    };

    myWorker.onmessage = function(e) {
    result.textContent = e.data;
    console.log('Message received from worker');
    };
    }

    … and that Web Worker object receives and sends messages via window.postMessage calls, calls that can be cross-domain in nature, and so you should have some security checks and balances in place at the Web Worker object External Javascript, worker.js


    onmessage = function(e) {
    if (e.data.length < 3) {
    console.log('Message not processed');
    } else if (e.data[2].toLowerCase().replace('ozemail.com.au/~mkuulma/','rjmprogramming.com.au/').replace('localhost:8888/','rjmprogramming.com.au/').indexOf('rjmprogramming.com.au/') != -1) {
    console.log('Message received from main script ... ' + e.data[2]);
    var workerResult = '';
    if (e.data[1].indexOf('/') != -1) {
    workerResult = 'Result: ' + eval(eval(e.data[0]) / eval(e.data[1].replace('/','')));
    } else if (e.data[1].indexOf('-(') != -1) {
    workerResult = 'Result: ' + eval(eval(e.data[0]) - (eval(e.data[1].replace(')','').replace('-(',''))));
    } else if (e.data[1].indexOf('+') != -1) {
    workerResult = 'Result: ' + eval(eval(e.data[0]) + eval(e.data[1].replace('+','')));
    } else if (e.data[1].indexOf('*') != -1) {
    workerResult = 'Result: ' + eval(eval(e.data[0]) * eval(e.data[1].replace('*','')));
    } else {
    workerResult = 'Result: ' + (Math.pow(e.data[0], e.data[1]));
    }
    console.log('Posting message back to main script');
    postMessage(workerResult);
    } else {
    console.log('Message unprocessed');
    }
    }

    … where the “Business Logic” of today’s proof of concept lives, that being for a Rudimentary Calculator of operations on two numbers …

… it being the job of the HTML you call in the first place, square_caller.html, to allow the user to enter data for those two number input type=text (and we do our own validation) textboxes. The HTML iframe “overlay” look of the web application is encouraged by the CSS style.css stylesheet.

You can try a live run single domain (rjmprogramming.com.au) link …

You can try a live run cross domain (rjmprogramming.com.au to members.ozemail.com.au/~mkuulma/) via minutely changed square_caller.htm link …

You can try a live run cross domain (members.ozemail.com.au/~mkuulma/ to rjmprogramming.com.au) link …

We hope these ideas spark your interest.


Previous relevant TimeZone Country Places Data Tutorial is shown below.

TimeZone Country Places Data Tutorial

TimeZone Country Places Data Tutorial

Data takes many forms, and we tend to organize it in an orderly fashion, often with the use of …

  • database
  • flat files, perhaps delimited … like CSV (comma separated values)
  • mechanisms with the HTML such as data attributes

… but today, we use PHP code itself, in the sense that it has a level of data hiding, but without usernames and passwords coming into play. Today we start with three simple array definitions in the PHP code for our TimeZone Places web application where building on the work of yesterday’s TimeZone Country Places Emoji Tutorial as per …


// Use URL like ./tz_places.php?upto= to populate arrays below ...
$nearname=[""];
$nearlatitude=[" "];
$nearlongitude=[" "];

… and this to us, is the “backbone” of our data (like the table structure of our database, if you like). Sounds implausible, but now what is needed to attain useful data to use in a “Find Nearest TimeZone Places” piece of functionality driven by user entered Place,Latitude,Longitude fields in an HTML form element (with its HTML input type=submit button) that “recalls” tz_places.php in yet another usage to populate a “nearest 3″ HTML select “dropdown” (size=4 … to show it in its entirety on non-mobile platforms), for user perusal … is …

  • like in a CMS a means to hive off “database” management from normal user usage … as simple as URL //www.rjmprogramming.com.au/PHP/tz_places.php?upto= for “database”=”PHP array” management (and any other URLs for normal user usage) … and …
  • a place in the code to intervene to reference the PHP code itself … and

    function ourtimezonelist($ididea) { // thanks to //php.net/manual/en/function.timezone-identifiers-list.php
    // ...
    // lots of code
    //
    // ... then ...

    $versus=file_get_contents("tz_places.php");

    $zones = timezone_identifiers_list();
    foreach ($zones as $zone) {
    $origzone=$zone;
    $zzbit=$zone;
    $zone = explode('/', $zone); // 0 => Continent, 1 => City
    // Only use "friendly" continent names
    if ($zone[0] == 'Africa' || $zone[0] == 'America' || $zone[0] == 'Antarctica' || $zone[0] == 'Arctic' || $zone[0] == 'Asia' || $zone[0] == 'Atlantic' || $zone[0] == 'Australia' || $zone[0] == 'Europe' || $zone[0] == 'Indian' || $zone[0] == 'Pacific') {
    if (isset($zone[1]) != '') {
    if (strpos($versus, '"' . $zzbit . '"') === false && strpos($versus, '"' . '' . '"];') !== false && strpos($versus, '"' . ' ' . '"];') !== false && strpos($versus, '"' . ' ' . '"];') !== false) {
    $ourtz=new DateTimeZone($zzbit);
    $versus=str_replace('"' . '' . '"];', '"' . $zzbit . '","' . '' . '"];', $versus);
    $versus=str_replace('"' . ' ' . '"];', '"' . $ourtz->getLocation()[latitude] . '","' . ' ' . '"];', $versus);
    $versus=str_replace('"' . ' ' . '"];', '"' . $ourtz->getLocation()[longitude] . '","' . ' ' . '"];', $versus);
    @file_put_contents("tz_places.php", $versus);
    echo '<html><body onload=" location.href=' . "'" . "./tz_places.php?upto=" . $zzbit . "'" . '; "></body></html>';
    exit;

    }

    $selstuff=str_replace("</select>", "<option title='" . $origzone . "' value='" . str_replace("/" . $zone[-1 + sizeof($zone)], "", $zzbit) . '/' . explode(",",$zone[-1 + sizeof($zone)])[0] . "'>" . str_replace('_', ' ', str_replace("/" . $zone[-1 + sizeof($zone)], "", $zzbit). '/' . $zone[-1 + sizeof($zone)]) . "</option></select>", $selstuff);
    }
    }
    }
    // ...
    // more code
    //
    }

    … so that these bits of code update the PHP array (“database”) and rerun it to look for another new TimeZone place whose latitude,longitude geographicals we should save into our PHP code … and further down the code the code snippet …

    if (isset($_GET['upto'])) {
    ourtimezonelist($ideais);
    }

    … as a piece of code occurring before any HTML is ever written ensures “database” management has a chance of getting that first look in

What about our user entered place names? We can’t know all their geographicals for comparing this PHP array “database” to, so what mechanism helps here? We have to thank the Google search engine and PHP’s file_get_contents for that, and to understand how that works, take a peek at the code and/or its changes, below, for the detail. In summary though, that user entered place name HTML input type=text element’s onblur event cuts out the middlemanperson HTML input type=submit to send its own tailored URL to the awaiting HTML iframe element (form) target, its special ./tz_places.php?latitude=&longitude=&place=Sydney (for example) type of URL being trapped at the other end to call on good ol’ PHP file_get_contents to do its thaing.

So our TimeZone Places web application live run is now using PHP code tz_places.php that accommodated the “find nearest timezone places” functionality, in this way, where the PHP itself is like the data source. You should try it out to see what we mean.


Previous relevant TimeZone Country Places Emoji Tutorial is shown below.

TimeZone Country Places Emoji Tutorial

TimeZone Country Places Emoji Tutorial

Maybe you’re like me, and prefer websites where there is lots of functionality, and whether you use it or not, is up to the individual user. We might be wrong about this, but this represents to us an idea in a webpage where you don’t think all users are looking for the bare minimum of what the webpage nominally does, but that for those users not interested in all the “bells and whistles” it is still fairly obvious where the main flow of “business logic” (in the webpage) goes. This is where, for us, we’ve been making more and more use of Emojis, and we do this for three main reasons …

  1. Emojis can represent the “optional” (on top of the bare minimum) functionality of the webpage … and …
  2. Emojis take up very little room in an “online” world with smaller and smaller screen size expectations … and …
  3. Emojis look like fun, and can look like buttons (which users are used to as “action” items)

So what Emoji “buttons” did we add today, building on that work from yesterday with TimeZone Country Places CSS Tutorial?

  1. Video (camera) emoji 📹 next to Country and Place names to link the user to a YouTube API for Iframe embedded videos (like we talked about at YouTube API Start and Stop Primer Tutorial) for the purposes of looking up general “where” content about these countries and places
  2. An Alarm Clock emoji ⏰ signifies TimeZones that have a Daylight Saving Mode to link the user to further information about this
  3. Time Clock emojis like 🕛 (which we found out about thanks to this link)

Which leaves us looking at a TimeZone Places web application live run with what we hope you agree is an improved functionality using PHP code tz_places.php that changed for the purposes of Emoji “button” functionality, in this way. As per usual, we hope you give it a go, as your trip planner, perhaps?!


Previous relevant TimeZone Country Places CSS Tutorial is shown below.

TimeZone Country Places CSS Tutorial

TimeZone Country Places CSS Tutorial

Today we’ve started out on the first bits of CSS styling improvements to the web application at the heart of TimeZone Country Places Iintegration Tutorial as shown below. But today, as well as …

  1. CSS styling improvements …

    <style>
    td { vertical-align: top; }
    .round, #isubmit {
    /* Safari 3-4, iOS 1-3.2, Android 1.6- */
    -webkit-border-radius: 50%;

    /* Firefox 1-3.6 */
    -moz-border-radius: 50%;

    /* Opera 10.5, IE 9, Safari 5, Chrome, Firefox 4, iOS 4, Android 2.1+ */
    border-radius: 50%;
    padding: 17px 17px 17px 17px;
    font-family: Tahoma;
    color: red;
    font-size: 32px;
    }
    select { background-color:#f0f0f0; border: 2px solid lightblue; }
    .abut { background-color:#ffffff; border: 2px solid olive; padding 3px 3px 3px 3px; color: purple; }
    </style>

    as well as “bugs” …

  2. fix for Google Maps directions map URLs that occasionally get confused by using the TimeZone Continent/Place naming as the aid to construct the URL required rather than involving Country/Place where as you will recall we can derive the Country name via our ISO two letter Country Code mappings … as exemplified by the bad Continent/Place URL compared to a good Country/Place URL version … as well as …
  3. fix for “bug” where we had assumed all TimeZone names were of the form Continent/Place whereas you can also have, as in Argentinian TimeZones, those of the form Continent/Country/Place

Basically the CSS styling above is intended to emphasise the HTML input type=buttons that when clicked start up the “when” and “where” data hookups, which is the main purpose of the web application. Those buttons, as well as the “new iframe ‘parent'” HTML a links that now look like buttons, get their increased emphasis via the use of a CSS(3) border-radius property of 50% to form an ellipse as a background “shape” to the HTML element of interest, the idea for which we got from this great link, thanks. To facilitate this styling we added into the HTML classnames for abut and round and one new ID isubmit to help with this.

The last item in the list above, first discovered in unit testing of Argentinian TimeZone places (it now works better than as shown), had implications not only for our …

Please feel free to try our TimeZone Places web application, and perhaps plan a holiday.


Previous relevant TimeZone Country Places Iintegration Tutorial is shown below.

TimeZone Country Places Integration Tutorial

TimeZone Country Places Integration Tutorial

Yesterday we set up the framework for our software integration improvements to the web application at the heart of TimeZone Country Places Iframe Tutorial as shown below. It ended up, yesterday, in its completed framework … in other words, we no longer need to add or subtract any hierarchies, to the architecture … we ended up with (what we hinted at, then) …

  1. a “parent” web application of “when” content … supervising …
  2. an HTML table row cell’s “child” HTML iframe layer combining “when” and “where” content … supervising …
  3. Google Charts Map Chart HTML “grandchildren” iframe “where” content

… where the “grandchild” Map Chart above sees the “grandparent” as top.document and the “parent” HTML table row cell’s “child” HTML iframe layer as parent.document so that with our Map Chart new functionality code …


<?php echo "\n var topdocumentURL='" . $_SERVER['HTTP_REFERER'] . "'; \n"; ?>

function mapadvice(opl) {
var tprop='';
if (topdocumentURL.indexOf('rjmprogramming.com.au') != -1) {
if (top.document.getElementById('mapphpmailbox')) {
if (parent.document.getElementById('aof_' + opl.replace(' ','_').replace(' ','_').replace(' ','_').replace(' ','_').replace(' ','_'))) {
tprop=parent.document.getElementById('aof_' + opl.replace(' ','_').replace(' ','_').replace(' ','_').replace(' ','_').replace(' ','_')).title;
if (top.document.getElementById('mapphpmailbox').value.indexOf(tprop) == -1) {
if (top.document.getElementById('mapphpmailbox').value == '') {
top.document.getElementById('mapphpmailbox').value=tprop;
} else {
top.document.getElementById('mapphpmailbox').value+=';' + tprop;
}
tprop=String.fromCharCode(10) + 'As you click multiple places see TimeZone Places supervisor dropdown options' + String.fromCharCode(10);
}
}
}
}
return tprop;
}

… we can add any Google Chart Map Chart select (onclick) event data points into the mix of the “parent” who organizes a dropdown presenting pairs of TimeZone Place From/To set proposals, showing on the dropdown …

  • From/To names … and ….
  • Distance between (as the crow flies) regarding “where” … and …
  • Time Difference regarding “when” … that, when clicked …
  • Access to a Google Maps directions map for that From/To scenario … thanks

The middle manperson data item we add, and populate via Javascript DOM techniques here is a title property to the HTML a link TimeZone name parts of the “middle” HTML table row cell’s “child” HTML iframe layer.

You’ll see from the “grandchild” code we show above, a “child” method of determining and, thus, filtering its actions according to its boolean return, where an HTML element with a particular ID property (ie. mapphpmailbox) exists, or not. With regard to this “interprocess” (web application) messaging we also use these types of techniques when we presented Emoji Overlay Primer Tutorial (though there we also checked existences of “parent” Javascript functions as well).

In a similar line of thinking regarding “interprocess” (web application) messaging we recommend the understanding of window.postMessage ideas we gave an introductory look at with Legend for and from HTML Map Element Web Server Tutorial.

And so we have our amended “parent” (and “child”) live run PHP code tz_places.php that changed in this way for integration with Google Chart Map Charts with regard to TimeZone Place From/To pairings, supervising Google Chart Map Chart “grandchild” iframe PHP map.php changed as per these changes.

Why not try it out for yourself?


Previous relevant TimeZone Country Places Iframe Tutorial is shown below.

TimeZone Country Places Iframe Tutorial

TimeZone Country Places Iframe Tutorial

Just because a concept is simple doesn’t mean it should somehow be disrespected. For the most part, we often wonder why complicated things that supercede simple things that worked well (and were well understood) become obsolete. If we were to be a little less naive perhaps we’d understand, but that’s business. What we most respect here, are simple ideas, and ones that ask little, and give a lot, and ones that are renewable or leave a small footprint on the world … EOR … end of rave.

Today’s “simple concept” is the HTML iframe element, which to us means “child” in “parent/child” or “client” in “server/client” for web applications. A “child” talks to their “parent”, and vice vera. And a “child” can influence their “parent” … you bet! That’s a (metaphor for a) web application “parent” web page, and its relationship to an HTML iframe element. We find it the easiest way to understand (and practically arrange) the modularisation of web application functionality, where all that functionality can even be contained within the one piece of code, but just called differently, with a feel of recursion.

With our TimeZone Country Places Primer Tutorial as shown below, we’d actually already started on HTML iframe work, because the Google Charts Map Chart functionality is already (contained) in an HTML iframe element. But we’re talking, today, about another level of HTML iframe use, by allowing for an HTML table row’s worth of TimeZone/MapChart cells (up to 10). Why? We’ll let you know more tomorrow, but the obvious reason for today, is that you see information sidled up next to each other horizontally … simple and effective way we humans work … we naturally compare and contrast and observe data, ideally all within eyesight of each other.

Which leaves us with our amended live run PHP code tz_places.php that changed in this way for your perusal. Perhaps, today, you can visualize this web application’s practical use and can imagine what we are tempted to do next?


Previous relevant TimeZone Country Places Primer Tutorial is shown below.

TimeZone Country Places Primer Tutorial

TimeZone Country Places Primer Tutorial

We’ve elaborated on the PHP TimeZone functionalities today to write another web application where “when” meets “where” via TimeZones.

Into the mix of the logic here, we need to venture into the world of two letter ISO Country Codes, and we work this with help from //php.net/manual/en/datetimezone.getlocation.php and //stackoverflow.com/questions/17842003/php-intl-country-code-2-chars-to-country-name and //php.net/manual/en/function.timezone-identifiers-list.php and //www.timezoneconverter.com/ to “hardcode” our HTML select “dropdown” elements we create in the process, and offer TimeZone information HTML select “dropdown” elements as well.

Also in the mix, as is so often the case for us here, when “where” is part of the “equation”, we use that wonderful Google Charts Map Chart functionality, to help us out.

And so we have written our live run of the PHP code tz_places.php for your perusal.

If this was interesting you may be interested in this too.


If this was interesting you may be interested in this too.


If this was interesting you may be interested in this too.


If this was interesting you may be interested in this too.


If this was interesting you may be interested in this too.


If this was interesting you may be interested in this too.


If this was interesting you may be interested in this too.

This entry was posted in eLearning, Event-Driven Programming, Tutorials and tagged , , , , , , , , , , , , , . Bookmark the permalink.

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=""> <strike> <strong>