BTC640/ProcessingAjax

From CDOT Wiki
Jump to: navigation, search

Lecture

Despite the title of this page the stuff this week doesn't have anything to do with Processing. If you've done the lab for last week (where you used requestImage()) that was a very similar concept.

Ajax is simply a way to make asynchronous (non-blocking) requests over the internet. Normally to make a request to a server you need to "go" to a URL, perhaps with some parameters. This is the traditional flow:

  1. The user clicks on a button or a link.
  2. The browser creates a URL for that action and queries the server for it.
  3. The server sends back a new page.
  4. The browser leaves the old page and displays the new page.

All web applications were built on this model originally. The problem is that reloading the page is expensive (both in bandwidth and time) and depending on what you're trying to do the user experience can be unacceptable. Just try to imagine Google Maps if you had to reload the page for every pan or zoom request.

Two sort-of-solutions for this problem before Ajax were frames and later iframes. Frames amost everybody hated (for various reasons). Iframes are better in many ways but they have some problems: a reload of the iframe is required to change its content, and the iframe itself has a fixed size.

Modern websites just use Ajax to create dynamic pages. An example of a flow with Ajax is:

  1. The user clicks on a button or a link.
  2. The request is handled 100% in JavaScript code, where:
    1. An XMLHttpRequest object is created
    2. A callback function is associated with that object
    3. A URL is created for the request (same as in the traditional flow but you have to do it yourself)
    4. The request for that page is sent to the server asynchronously (in the background), the user cannot see anything happening at this point.
    5. When the response is received from the server the callback function is called automatically.
    6. The callback function modifies a part of the page dynamically using DOM access methods.

Ads

Popup windows with ads became so hated over the years that popup blocking became the default behaviour in all the popular browsers. But the motivations for displaying those popups have not gone away.

There are now two popular ways to display ads to the user of a webpage:

  1. The old-school banner ad, which can also take the form of text without images. This is currently the most popular and accepted form of advertising.
  2. HTML5 popups. These are not popup windows that would show up in your window manager but rather DIV tags that float over the normal content of the page. Sometimes the page content is blocked until the popup is dismissed and sometimes you can still interact with the page. Depending on the implementation of this - the reaction can range from quite acceptable to "get me out of here".

Almost always the HTML5 popup category has its content loaded using Ajax. It can be the simplest way to implement it and also it can allow the base page to load more quickly, and the ads will show up later after the user started reading the page they wanted to see.

Ajax disadvantages

One thing you cannot do with a page partially requested through Ajax is bookmark it. Some website designers go overboard with Ajax and make very link/button action an Ajax request. The result is that only the start page can be bookmarked. This is similar to all-flash webpages.

Also you cannot open an Ajax link in a new window or tab. This can seriously piss of your power users who do a lot on your website and need to manage their multitasking.

Also back and forward buttons don't work with Ajax requests. Again this can confuse and annoy your users.

Spy on User Example

Depending on how much time there is left in the lecture I may implement this from scratch or just show you what I've done already.

The example will listen for mouse moves, mouse clicks, and ctrl+c. That information will be sent via Ajax to a my server script (written in PHP). That will record the time, ip address, and action in a file on the server.

It's nasty stuff (don't do this for your clients) but shows you how much power Ajax gives you as the website owner.

My PHP script looks like this:

<?php

if (isset($_GET["k"]) && isset($_GET["v"]))
{
  $file = fopen("logs/log.txt", "a");
  if ($file === FALSE)
  {
    echo "Failed to open file for writing\n";
    return;
  }

  fwrite($file, date(DATE_RFC822) . ": " . $_SERVER['REMOTE_ADDR'] . ": " . $_GET["k"] . ":" . $_GET
["v"] . "\n");
  echo "Log done\n";
}
else
  echo "Wrong parameters given";
?>

Note that none of the echos will show up anywhere in the calling webpage if it's done by an Ajax call, unless the javascript that made the call decides to do something with the returned data. In this case I don't need to.

And my client-side code:

<script type="text/javascript">
function setup()
{
    document.onmousedown = mousedown;
    //~ document.onmousemove = mousemove;
    document.onmouseup   = mouseup;
    document.oncopy = copy;
    //~ document.onkeydown = keydown;
}

function mousedown(event)
{
    //~ alert("down at" + event.clientX + "x" + event.clientY);
    logStuff("mousedown", event.clientX + "x" + event.clientY);
}
function mousemove(event)
{
    //~ alert("move to " + event.clientX + "x" + event.clientY);
    logStuff("mousemove", event.clientX + "x" + event.clientY);
}
function mouseup(event)
{
    //~ alert("up at" + event.clientX + "x" + event.clientY);
    logStuff("mouseup", event.clientX + "x" + event.clientY);
}
function copy(event)
{
    //~ alert("copied " + window.getSelection());
    logStuff("copy", window.getSelection());
}
function keydown(event)
{
    if(event.ctrlKey && event.keyCode == 67)
        alert("ctrl+c " + window.clipboardData);
}
function logStuff(event, data)
{
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function()
        {
            //alert(xmlhttp.readyState + " " + xmlhttp.status);
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
            {
              alert(xmlhttp.responseText);
            }
        }
    // This won't work on newer browsers because of a security restriction:
    xmlhttp.open("GET", "http://littlesvr.ca/spy/spy.php?k=" + event + "&v=" + data);
    // But this will:
    xmlhttp.open("GET", "spy.php?k=" + event + "&v=" + data);
    xmlhttp.send();
    //alert('sent ' + "spy.php?k=" + event + "&v=" + data)
}
</script>

Resources

Lab

Create a PHP page with an HTML button.

  1. When the button is pressed an Ajax request will be made to the server (the same or a different PHP file).
  2. The server will generate a random number using the rand() function and send the result back to the client.
  3. The client will display that number somewhere on the page.

Submit

  • Leave your PHP scripts on the server.
  • Submit to moodle (lab7) the same php script(s)
  • In the comments for the submission - mention where on the server I can find your working page.