University of Washington CSE 190M

Section 9: PHP Web Services and Scriptaculous

Except where otherwise noted, the contents of this document are Copyright 2012 Marty Stepp, Jessica Miller, and Victoria Kirst. All rights reserved. Any redistribution, reproduction, transmission, or storage of part or all of the contents in any form is prohibited without the author's expressed written permission.

Valid HTML5 Valid CSS

Exercise : Prime Factors (by Eli White)

Write a PHP web service, factors.php, which will return (in text/plain) the prime factors of a provided number. For example, the request factors.php?n=264 would return:

2 * 2 * 2 * 3 * 11

You can make queries to the working solution to test. One simple algorithm for prime factorization of num is as follows:

for fact from 2 to num:
	while num % fact = 0:
		num = num / fact
		add fact to the list of prime factors of the original num

Make your web service return a 400 Invalid Request HTTP error code with an instructive error message if the parameter n is not provided.

Exercise Prime Factors

<?php
	header('Content-type: text/plain');
	if (!isset($_GET['n'])) {
		header('HTTP/1.1 400 Invalid Request');
		print "Please provide a parameter n.";
	} else {
		$factors = factorize($_GET["n"]);
		print implode(" * ", $factors);
	}
	function factorize($num) {
		$factors = array();
		for ($factor = 2; $factor <= $num; $factor++) {
			while ($num % $factor == 0) {
				$num /= $factor;
				array_push($factors, $factor);
			}
		}
		return $factors;
	}
?>

Exercise : Prime Factors 2 (by Roy McElmurry)

Modify your PHP web service, factors.php to return the prime factors of a provided number in JSON format. For example, the request factors.php?n=264 would return:

{"number": 264, "factors": [2, 2, 2, 3, 11]}

You can try out the service here.

Exercise Prime Factors 2

header('Content-type: application/json');
if (!isset($_GET['n'])) {
	header('HTTP/1.1 400 Invalid Request');
	print "Please provide a parameter n.";
} else {
	$n = $_GET["n"];
	$ret = array(
		"number" => $n,
		"factors" => factorize($n),
	);
	print json_encode($ret);
}

Exercise : Address Book (by Alex Miller)

You are given HTML and JS files for an address book web application. The javascript file sends requests to a web service that reads and saves address data. You can view the working application here. Write the PHP file, addressbook.php, that provides the following behavior:

Extra: Edit addressbook.js to add jQuery UI effects to the page.

Exercise Address Book

header("Content-type: text/plain");
$file_text = file_get_contents("addresses.txt");
if ($_SERVER['REQUEST_METHOD'] == "GET") {
    $lines = explode("\n", $file_text);
    if (isset($_GET["name"])) {
        $name = $_REQUEST["name"];
        foreach ($lines as $line) {
            $info = explode(",", $line);
            if ($info[0] == $name) {
                print $info[1];
            }
        }
    } else {
        $names = array();
        foreach ($lines as $line) {
            $info = explode(",", $line);
            array_push($names, $info[0]);
        }
        print(implode($names, ","));
    }
}

Exercise Address Book

if ($_SERVER['REQUEST_METHOD'] == "POST") {
    $name = $_REQUEST["name"];
    $address = $_REQUEST["address"];
    $file_text = file_get_contents("addresses.txt");
    $file_text .= "\n" . $name . "," . $address;
    file_put_contents("addresses.txt", $file_text);
}

Exercise : Address Book 2 (by Roy McElmurry)

Modify your addressbook.php web service to return data in JSON format. You should use these HTML and JS files for this version.

For example, if a GET request is made without any parameters, you should return

{"names": ["name1", "name2", ...]}

And if a GET request is made with the name parameter, you should return

{"name": "some_name", "address": "some_address"}

You can try out the service here.

Exercise Address Book 2

header('Content-type: application/json');
if (isset($_GET["name"])) {
	$name = $_REQUEST["name"];
	$ret = array("name" => $name, "address" => "");
	foreach ($lines as $line) {
		$info = explode(",", $line);
		if ($info[0] == $name) {
			$ret["address"] = $info[1];
		}
	}
	print json_encode($ret);
} else {
	$names = array();
	foreach ($lines as $line) {
		$info = explode(",", $line);
		array_push($names, $info[0]);
	}
	print json_encode(array("names" => $names));
}

Exercise : Garbage Collector (by Morgan Doocy)

Write the necessary JavaScript / jQuery UI code to complete the skeleton HTML and JS, which removes each icon with an effect("puff") when it is dragged and dropped onto the trash can as in this working solution.

You will first need to inject 20 IE6 icons (imgs of class .browser, with a src of ie6.png) into the #browsers div. Use the provided positionRandomly function to give each img that you inject a random location.

Exercise : Garbage Collector (by Morgan Doocy)

Refer to the jQuery documentation for Draggables, Droppables, and Effects to figure out how to configure your objects so that:

Exercise Garbage Collector

$(function() {
	createBrowsers();
	$("#trashcan").droppable({
		"accept": "browser",
		"hoverClass": "full",
		"drop": removeBrowser
	});
});
function createBrowsers() {
	for (var i = 0; i < 10; i++) {
		var img = $("<img>", {
			"class": "browser",
			"src": "http://webster.cs.washington.edu/cse190m/sections/8/trashcan/ie6.png"
		}).draggable({
			"revert": "invalid"
		}).appendTo($("#browsers"));
		positionRandomly(img);
	}
}

Exercise Garbage Collector

function removeBrowser(e) {
	$(elem).effect('puff', {}, 0.5, function() {
		$(this).remove();
	});
}