Wednesday, December 7, 2011

HTML <div> tag revisited

I was abruptly forced to revisit this topic when I discovered that my <div> tag laid out login page, which seemed to look so great in Windows Internet Explorer (see below), looked absolutely crap in Firefox (see further below).

So I did some reading, and the theme seemed to be that tables were never intended to do layout. Well I reckon there should be a counter argument, that the <div> tag was never intended to present data.

It seems to me that much of the orthodoxy around HTML is written by graphic artists or publishers, and most of the web sites purported to show the power of <div> tags and CSS, are littered with graphic art and fancy fonts.

For anyone used to programming, meshing <div> tags and CSS is not technically difficult, but perhaps it is not second nature to graphic artists and literary publishers. The instructions emphasize the importance of closing tags, and they suggest using borders during the design phase to get a visual aid on the layout of the divisions.

So I tried that. I show below the HTML for the beginning of a login page:

<body>
<div id="container">
<div id="pageHeader">
<h1><span>Rasch-ItemBank</span></h1>
<h3><span>A <a class="top" href="http://www.interactived.com/softway.htm">
Softway</a> Open Source Project <br>
Hosted by <a class="top" href="http://java.net/projects">Java.net</a></span></h3>
</div><!-- end of "pageHeader" -->
<div id="pageBody">
<h3><span><h3>Initial Login Screen</h3></span></h3>
<div id="cellA1">
<p><span>Please select user or administrator</span></p>
</div><!-- end of "cellA1" -->
<div id="cellB1">
<p><span><select name="usertype" class=cbox>
<option value="user">Student User</option>
<option value="admin">Administrator</option>
</select></span></p>
</div><!-- end of "cellB1" -->
</div><!-- end of "pageBody" -->
</div><!-- end of "container" -->
</body>
</html>

And below is the CSS to go with it:

#container {
padding: 0 25px 0 120px;
margin: 0;
position: relative;
border: 1px dotted red;
}
#pageHeader {
margin: 5px;
border: 1px dotted orange;
}
#pageBody {
margin: 5px;
border: 1px dotted green;
}
#cellA1 {
margin: 2px;
height: 35px;
float: left;
border: 1px dotted fuchsia;
}
#cellB1 {
margin: 2px;
height: 35px;
float: left;
border: 1px dotted fuchsia;
}

I put little margins around each "division", and I made the borders different colors for clarity. Having rainbows on my mind, I followed a rainbow sequence: Richard of .. gave .. vain. I show below how it came out:

Notice how the red border, which is supposed to embrace everything, stops short, and leaves off two divisions. And the green border, which was created to embrace the "table" and its heading, wraps itself around the heading only.

After many hours of fiddling, I noticed that the "divisions" behave better if they contain background images, but it strikes me that padding out divisions with background images to make them behave predictably, is conceptually not far removed from padding out real tables with spacer gifs.

So I shall put my login form, and all other forms back into tables. I may use CSS to format the tables, and I may use divisions in pages and areas of pages devoted to text and graphics. But my data and forms will be laid out in the traditional manner, using tables.

Monday, November 21, 2011

Bringing a Custom Swing Component to Life

I am sometimes down on the Java documentation, but in the sand plains of lugubrious and often confusing material there is the occasional gem. One example is a lesson from The Java Tutorial entitled Performing Custom Painting. I was directed to it by a reply to this thread in the Oracle Java Desktop forum.

When I first began my efforts to create a rainbow colored Gaussian distribution curve I began with one of the Tutorial lessons on colors. I have unfortunately lost the URL for the lesson but the code began something like this:

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class Colors extends JPanel {

public void paintComponent(Graphics g) {
super.paintComponent(g);

Graphics2D g2d = (Graphics2D) g;

g2d.setColor(new Color(255, 0, 0));//vivid red
g2d.fillRect(10, 15, 90, 60);

...

}

public static void main(String[] args) {

JFrame frame = new JFrame("Colors");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new Colors());
frame.setSize(360, 300);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}

It looked as shown below.

I modified this by putting the rectangles side by side and end on to produce a crude histogram as shown below:

I reduced the width of the rectangles (to one pixel) and their number (to 800), and made their height and color the subject of mathematical functions. The colors were produced by three out of phase sine waves. That idea from that came from this article by Jim Bumgardner. His explanation is very thorough, so I shall not repeat it here, but in recognition of the idea, my first rainbow colored curve was a sine wave, as shown below:

The mathematical function for a sine wave in Java is really simple:

y = Math.sin(x);

There is, alas, no inbuilt function for a Normal/Gaussian distribution curve, but Wikipedia gives the function as:

I used the middle part of this expression to produce the rainbow colored Gaussian distribution curve shown at the bottom of my previous post. But as I said there, it did nothing. I could not send messages to it or make it change.

I will admit that when I first read the reply to my forum post recommending the Custom Painting tutorial, I was not that optimistic, and I didn't look at it properly until after I had tried all the articles described in my previous blog post. But my cynicism was misplaced, and I should have started there.

The essential code construction from the tutorial begins as follows:

import javax.swing.SwingUtilities;
import javax.swing.JFrame;

public class SwingPaintDemo1 {

public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}

private static void createAndShowGUI() {
System.out.println("Created GUI on EDT? "+
SwingUtilities.isEventDispatchThread());
JFrame f = new JFrame("Swing Paint Demo");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(250,250);
f.setVisible(true);
}

And the first essential point to note is that it uses:

The SwingUtilities helper class to construct this GUI on the Event Dispatch Thread.

I don't fully understand this, but I've been told to do it before, and it was only when I used this structure for my "custom swing component" that I could get it to work properly.

The second slightly strange thing that the tutorial did was to create its own "custom" JPanel:

class MyPanel extends JPanel {

public MyPanel() {
setBorder(BorderFactory.createLineBorder(Color.black));
}

public Dimension getPreferredSize() {
return new Dimension(250,200);
}

public void paintComponent(Graphics g) {
super.paintComponent(g);

// Draw Text
g.drawString("This is my custom Panel!",10,20);
}
}

This was all in the same source file, which was modified by replacing:

f.setSize(250,250);

with

f.add(new MyPanel());
f.pack();

It looks trivial, but by following this structure, I was able to use the .pack() command in my applet. Using my original code construction (as shown above), the first time I inserted the new component, I thought it hadn't worked at all because it did not show, and it was only after adding padding to the gridbaglayout and manually resizing the applet that I could see it.

Another point worth noting is the line which inherits functionality from the parent component. This is described in the tutorial as follows:

Most of the standard Swing components have their look and feel implemented by separate "UI Delegate" objects. The invocation of super.paintComponent(g) passes the graphics context off to the component's UI delegate, which paints the panel's background.

This avoided me having to mimic the code structure of the standard swing components. I could focus on the code that made my component different.

The third thing that the tutorial did was to create a "sprite" and code to move it around. My "sprite" is my rainbow colored histogram, and I didn't need "event" code to drag it around the page. But I did need code to alter one or more of the parameters used to build the histogram. The code used by the tutorial was:

... previous imports
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseMotionListener;
import java.awt.event.MouseMotionAdapter;

... previous unchanged code

public MyPanel() {

setBorder(BorderFactory.createLineBorder(Color.black));

addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
moveSquare(e.getX(),e.getY());
}
});

addMouseMotionListener(new MouseAdapter() {
public void mouseDragged(MouseEvent e) {
moveSquare(e.getX(),e.getY());
}
});

}

private void moveSquare(int x, int y) {
int OFFSET = 1;
if ((squareX!=x) || (squareY!=y)) {
repaint(squareX,squareY,squareW+OFFSET,squareH+OFFSET);
squareX=x;
squareY=y;
repaint(squareX,squareY,squareW+OFFSET,squareH+OFFSET);
}
}


public Dimension getPreferredSize() {
return new Dimension(250,200);
}

protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawString("This is my custom Panel!",10,20);
g.setColor(Color.RED);
g.fillRect(squareX,squareY,squareW,squareH);
g.setColor(Color.BLACK);
g.drawRect(squareX,squareY,squareW,squareH);
}
}

The fourth slightly strange thing that the tutorial did was to put the "sprite" is its own class:

class RedSquare{

private int xPos = 50;
private int yPos = 50;
private int width = 20;
private int height = 20;

public void setX(int xPos){
this.xPos = xPos;
}

public int getX(){
return xPos;
}

... more set/get functions

public void paintSquare(Graphics g){
g.setColor(Color.RED);
g.fillRect(xPos,yPos,width,height);
g.setColor(Color.BLACK);
g.drawRect(xPos,yPos,width,height);
}
}

I'm not sure whether this was strictly necessary, but I followed the same structure, putting my histogram into the paintSquare(Graphics g) method, although I called it rainbowHist(Graphics g). I also renamed MyPanel() to MyHist(). The six set/get functions I replaced with two:

public void setMaxValue(int MaxValue){
this.MaxValue = MaxValue;
}

public void setActValue(int ActValue){
this.ActValue = ActValue;
}

The moveSquare(int x, int y) function I made as follows:

public void moveSquare(int MaxValue, int ActValue){
myHist.setMaxValue(MaxValue);
myHist.setActValue(ActValue);
repaint();
}

I didn't need the mouse listeners, so I removed them altogether.

Already my custom component was beginning to look a bit like a JProgressBar, with a MaxValue and an ActValue, and "progress" indicated by the relationship between the two. In my initial version I made the number of columns in the histogram a linear function of ActValue as a proportion of MaxValue, just like the colored bit in an ordinary JProgressBar.

But I needed to revise this, because I wanted "progress" to be indicated by the area under the curve, not the distance along the x axis.

Wikipedia gives the area under the curve, or "Cumulative distribution function" as:

In this expression "erf" is an abbreviation for "error function", and I was interested to read that much of the work around and even the name of the function derives from measurement theory. Indeed, one of the approximation expressions is:

And this could almost have been lifted straight from the Rasch book. I must say, I've never liked that expression (in fact it gives me the heebie jeebies), so I moved straight down to the Abramowitz and Stegun approximations, and used the first, because I'm aiming for a visual impression here, and don't need seven decimal places of accuracy:

Because we are talking about probability here, the theoretical total area under the graph is 1. So while in the initial version, the critical parameter was number of columns:

for (double i=0; i<ActNoofColumns; i++){

I now set the histogram to build completely by default:

for (double i=0; i<MaxNoofColumns; i++){

and inserted a break to trigger when the area approximation equates to ActValue as a proportion of MaxValue:

if (jonathan > ProportionofMax) break;

I used the variable jonathan, because Wikipedia was a bit vague about the left hand portion of the curve when the mean is zero (and x<0). I guess the measurement theorists who did this work didn't care, because they were only interested in the extreme right hand end of the curve. Wiki suggested:

erf(x)=-erf(-x)

This is correct, but I missed the leading minus sign on the right hand side of the expression, so I did a bit of fiddling around. Anyway, it eventually worked. The illustration below shows my custom component under the JprogressBar it will replace (as well as the curve shown in full for an instance of the component not yet callibrated).

Tuesday, November 15, 2011

Creating a Custom Swing Component

I always return to my blog when I'm stuck, and I'm stuck right now.

I want to create a custom Swing component. Specifically, I want something like a JProgressBar, with the following changes:

  1. In place of a flat Foreground color, I want a rainbow spectrum, showing only the red range for low Values, and the whole spectrum for values close to the Maximum value;
  2. Instead of a rectangular box, I want the progress "bar" to take the shape of a normal, or Gaussian, distribution curve;
  3. I want progress to be displayed by the area under the curve, rather than by a simple linear scale along the x axis.

It's not that there isn't stuff out there. I have five tabs open in my browser, specifically addressing the creation of custom components in Swing, as well as the source code for the JProgressBar. It is that, like everything to do with Java, it is bloody difficult to read.

I shall begin from the horse's mouth as it were, with an article on the Java.net website entitled: How to Write a Custom Swing Component. It begins by defining the "building blocks" of Swing components as:

  • The component class itself, which provides an API for creating, changing, and querying the component basic state.
  • The model interface and the model default implementation(s) that handle the component business logic and change notifications.
  • The UI delegate that handles component layout, event handling (mouse and keyboard), and painting.

I understand the first four words of that lot. I hate it when documents, especially formal ones, use abbreviations without definitions, but a Google search on API produces a first page full of formal Sun/Oracle documents, which do that, even in the title.

According to an archived (by which I mean so old or unimportant that Oracle has not woven itself into the URL) glossary, API is defined as:

Application Programming Interface. The specification of how a programmer writing an application accesses the behavior and state of classes and objects.

So if you insert the full definition into the first bullet, you get:

  • The component class itself, which provides a specification of how a programmer writing an application accesses the behavior and state of classes and objects for creating, changing, and querying the component basic state.

And that is gibberish, like so much of the material used to describe Java, and the closer you get to "the horse" often the more confusing it gets. To be fair, if you insert the words behind the acronym, it looks a little better:

  • The component class itself, which provides an Application Programming Interface for creating, changing, and querying the component basic state.

But then it starts to overlap with the second "building block", which begins:

The model interface ...

When I first read that, I wasn't sure whether it said model or modal. Either way it is not clear how the model interface differs from the Application Programming Interface.

The third "building block" opens with:

The UI delegate ...

I used the same glossary to look up UI, and it wasn't even in there. A Google search on UI brings up a slew of pages on GUI, and the weight of evidence suggests "User Interface". So now we have Application Programming Interface, model interface, and a User Interface, each purportedly in their own "building block".

Are we really dealing with distinct building "building blocks" here, or a "blob" of amorphous building material with fuzzily defined functionality zones?

The next title in the article, after Basic Building Blocks, is The Component Class: UI Delegate Plumbing, which looks to me very like a composite of building blocks 1 and 3. The third heading is The Model Interface, so presumably it refers to the second building block. It includes some code, with two class declarations, and it opens with:

This (sic) is ... the most important class for a custom component.

The article continues, on and on, in a similarly confusing fashion, so I thought I'd cut to the chase and have a look at the source code and see if I could make it work. The code for the main class JFlexiSlider.java, begins with:

package org.jvnet.flamingo.slider;

import javax.swing.*;

import org.jvnet.flamingo.slider.FlexiRangeModel.Range;
import org.jvnet.flamingo.slider.ui.BasicFlexiSliderUI;
import org.jvnet.flamingo.slider.ui.FlexiSliderUI;

Three questions arise from this. Is the web address given for the imported classes in the public domain? Are the classes listed still there? And if so, is Java smart enough to navigate through the Internet to find them? When I tried to compile the class. The first of 18 errors was:

package org.jvnet.flamingo.slider.FlexiRangeModel does not exist

Out of curiosity I typed jvnet.org into my browser and it came up blank. I ran a whois on jvnet.org, and this confirmed that the domain name is registered, and to Oracle. So I guess that when this code was written, all the package and import information was meaningful, but now it certainly isn't. And to cut a long story short, the effort of addressing each error in turn to make the code run outweighed any possible benefit, so I gave up.

My next port of call was to the source code of the existing JProgressBar. One of eleven imported classes was:

import javax.swing.plaf.ProgressBarUI;

So I checked out the source code for this, which was:

public abstract class ProgressBarUI extends ComponentUI {
}

To do a proper job I should have downloaded the source code for ComponentUI as well, but to honest, the whole thing was rendered virtually unreadable by all the comments, so I reached another boredom threshold.

I then went to a much more readable article entitled Creating a custom component in Swing by a Danish gentleman called Christian Petersen. As my Rasch Itembank Project is inspired by the Danish Mathematician, Georg Rasch, I was happy to be reading something by one of his countrymen.

There were no remote or unreachable packages in the code given with this article (in fact there were no packages at all), and the code compiled and ran perfectly first time. Inspired by this success, and the simplicity of his approach, I went right back to basics, to a lesson in The Java Tutorial entitled Compiling and Running Swing Programs. This lesson gives a link to source code for a "program" called HelloWorldSwing.

HelloWorldSwing essentially displays a Swing component called JLabel, in another component called JFrame. I took this code and replaced the JLabel with the class for my rainbow colored Gaussian curve as follows:

import javax.swing.*;
public class HelloWorldSwing {
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("HelloWorldSwing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Add the ubiquitous "Hello World" label.
NormJ2 label2 = new NormJ2();
frame.getContentPane().add(label2);
//Display the window.
frame.setSize(520, 300);
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}

}

And it came up as shown below:

I've left all the comments and the HelloWorldSwing heading (and even the component name: label2) to emphasize that creating a custom swing component is really as simple as that. You don't need packages, collections of remote and difficult to find "ui" classes. You just insert one class, compiled with Swing components, into another.

As components go, mine is currently somewhat limited. It looks pretty (though I say it myself), but it does nothing else. The purpose of all the guff at the head of this post is to bring components alive, but there has to be a simpler, more commonsense, way to do it.

Saturday, November 12, 2011

Mixing and Matching

My unfamiliarity with PHP and JavaScript is illustrated by the fact that it has only just occurred to me that I don't have to choose between one or the other, but can in fact enjoy both. So for example, bringing my Add User screen into the PHP fold was simply a matter of changing the file extension and adding:

session_start();

at the top of the file. Everything else remained the same. All the JavaScript remained untouched, all the business rules remained the same, and if the business rules were satisfied, the same PHP file was called to run the data transaction. For display purposes the username was called, and usertype was called to ensure only administrators added to the database.

I had also been scratching my head about passing PHP variables back to the Applet to enrich the data stored in my database, but then it finally sunk into my head that they didn't need to be passed backwards and forwards. Variables (such as username, and IP) gathered by PHP, could simply be stored as session variables, while the user navigated from the login page to the Applet, and when the Applet called a PHP script, those same variables could be called on the page hosting the PHP script. They could then be woven into enhanced SQL commands on that page, without ever having been near the Applet itself.

Saturday, October 29, 2011

Security Points

The first point, about the security of my web site, is that Active Math Java is a test bed for code developed for the Rasch-ItemBank open source project. It is intended as a free resource for use by any child anywhere in the world with access to a computer connected to the Internet and running Java.

So the purpose of my login page is not to secure a web resource for which users pay money. Nor is it like a forum, where the login page protects the forum from spammers. It is simply there for the convenience of certain users who have requested the ability to track the performance of their children.

The second point, about the security of web sites in general, is that secure pages usually include a server side script, such as PHP, and if security is desired, all the pages have to be in the same or compatible format.

Using PHP has some advantages, besides security, such as retaining variables across pages, within sessions.

I have enjoyed writing business rules in JavaScript, for a mock login page and a mock add user page, because I have never liked JavaScript, and I enjoyed getting something to work with it. However, I am now resigned to rewriting everything in PHP, not for security, but for the convenience of retaining and passing variables about the place.

Oh boy am I glad this is a blog about learning Java and related languages and not a formal lesson. If it were a formal lesson, any readers might be really pissed off by now, because I have done about 3 180 degree turns.

Friday, October 28, 2011

Add User to Database

Having created an HTML layout and an external CSS page, and having written business rules for a login page, creating a page with a form to add users to the database was relatively easy.

The layout was almost identical to the login screen, except for what I call combo boxes for the age of the student users, and to comply with convention, a password confirmation field. But for that convention, the business rules could have been cut and pasted verbatim from the login page, and that would have made the job nice and easy.

Identification of users is not mission critical for me, and if teachers can't record and type in accurately a password on the first attempt, my first instinct was to say "who cares?". But part of the point of this exercise is to make my web site/application look "professional", so I put in the second field.

The login rules comprised four independent conditions nested within a super condition, triggered by any of the four being met, the alternative (or else) to which was the calling of the database query code. So where to put the fifth condition, the inequality of the passwords?

The nest of four are together because they are not mutually exclusive. Most often the user will click the button with nothing in either field, and you want a message to appear over both fields. Or the name might be too long, and the password field empty.

Technically the fifth condition might overlap with one or more of the other four. For example the password fields may be unequal and too long. But if they are too long, and they are told to make them equal first, they will be annoyed if they are told to shorten them after they have made them equal. I guess if I had enough space for messages I could tell them both, but I don't. So in my business rules they have to get the length right (between 1 and eight characters) first, and then make the passwords match. The rules are as follows:

function busrules(form)
{
var subtype = form.usertype.value;
var subname = form.username.value;
var subpass = form.password.value;
var subpassc = form.passwordc.value;
var subagey = form.ageyears.value;
var subagem = form.agemonths.value;
var showmessn;
var showmessp;
var ubercell1v = document.getElementById("ubercell1").innerHTML;
var ubercell2v = document.getElementById("ubercell2").innerHTML;
var myarg;
if (ubercell1v.length > 0)
{
document.getElementById("ubercell1").innerHTML="";
} //end of null check
if (ubercell2v.length > 0)
{
document.getElementById("ubercell2").innerHTML="";
} //end of null check
if (subname.length > 8 || subname.length ==0 || subpass.length ==0 || subpass.length ==0 )
{
if (subname.length > 8)
{
showmessn = "Your user name is too long. Please use 8 characters.";
document.getElementById("ubercell1").innerHTML=showmessn;
} //end of condition 1
if (subname.length ==0)
{
showmessn = "Oh Dear! You have not entered a user name.";
document.getElementById("ubercell1").innerHTML=showmessn;
} //end of condition 2
if (subpass.length > 8)
{
showmessp = "Your user password is too long. Please use 8 characters.";
document.getElementById("ubercell2").innerHTML=showmessp;
} //end of condition 3
if (subpass.length ==0)
{
showmessp = "Oh Dear! You have not entered a user password.";
document.getElementById("ubercell2").innerHTML=showmessp;
} //end of condition 4
} //end of group of 4 conditions
else if (subpass != subpassc)
{
showmessp = "Oh Dear! You need to enter the same password in both password fields.";
document.getElementById("ubercell2").innerHTML=showmessp;
} //end of condition 5

Then if all those rules are satisfied, the PHP script for the data connection is called:

else { //Code below is to set up parameters for the php script
if (window.XMLHttpRequest) //format and create request variable according to browser type
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} //end of current option
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
} // end of old option
xmlhttp.onreadystatechange=function()
{ // this code displays response text
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("untencell1").innerHTML=xmlhttp.responseText;
}
} //the code below calls the php script on the server
myarg = "('"+subname+"','"+subpass+"','"+subtype+"',"+subagey+","+subagem+")"
xmlhttp.open("POST","adduser.php?myarg="+myarg,true);
xmlhttp.send();
} //end of master conditional statement
} //end of function

I took the opportunity to tidy up the layout a bit. The "row" divisions I had set up (following the structure of a table) seemed a bit redundant, so I lost them, and I defined the warning divisions more concisely, to stop the form jumping about, when the warnings come up. And I made everything a bit wider:

.inputtable {margin:50; background-color:#BDEDFF}
.row {width:520;}
.col1 {text-align:right; float:left; width:300; height:25; margin:0 5 0 5;}
.col2 {text-align:left; float:right; width:200; margin:0 5 0 5;}
.itext {width:150;}
.cbox {width:150; margin-left:5;}
.warning {color="red";margin-bottom:0;margin-top:0;float:left; width:520; }


The PHP script was similar in structure to the login script, but differed in important details (such as running an INSERT command rather than a SELECT query):

<?php
include('newinfo.php');// collect database variables.
$myarg = $_GET['myarg']; // collect passed variable
// To protect MySQL injection
$myarg = stripslashes($myarg);
// Connect to server and select database.
$con = mysql_connect( $dbhost, $dbuser, $dbpass );
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db($dbname, $con);
$query = "INSERT INTO $table1 (Softid, PartPass, PartType, AgeYears, AgeMonths) VALUES ";
$query = $query . $myarg;
$result = mysql_query($query) or die(mysql_error() . $query );
if($result==1){
echo"<p>Hooray you have added a user</p>";
} else {
echo"<p>Oh Dear! Something went wrong. Query: <br/>$query </p>";
}
mysql_close($con);
?>

If the password were unequal, but everything else correct, the screen looked as shown below:

And after successfully adding a user is looked as shown below:

Wednesday, October 26, 2011

Check Login Details against the Database

After rewriting my business rules in JavaScript, the time now really had come to create the live database interface. So I busily changed the file extension back to .php and added back the include() statement, and started adding PHP code to the JavaScript function called by the button click event, and paused when I needed to pass a javascript variable to PHP. I had a feeling that what I was doing would not work, and a quick Google search confirmed that it would not.

The whole point of converting my business rules to JavaScript was to keep the field input checking local. But as PHP scripts run on the server, you need to call something on the server, and pass any variables to that.

It was a bit frustrating because neither of the login page examples I'd found on the web used any business rules at all; they just called a PHP script from the form submit button, one on the same page, one on another.

As a first pass I tried AJAX.

I had sidestepped the issue in my business rules test page with the line:

alert ("Well Done. Your username and password were correctly entered.");

I now replaced this with:

if (window.XMLHttpRequest) //format and create request variable according to browser type
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} //end of current option
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
} // end of old option
xmlhttp.onreadystatechange=function()
{ // this code displays response text
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("untencell1").innerHTML=xmlhttp.responseText;
}
} //the code below calls the php script on the server
xmlhttp.open("POST","logincheck.php?id="+subname+"&pw="+subpass,true);
xmlhttp.send();

I also added one more division to receive a message back from the PHP script:

<div id=untencell1></div>

This cell was placed under the button but within the form division. The PHP script was:

<?php
include('newinfo.php');// collect database variables.
$id = $_GET['id']; // collect passed variable 1
$pw = $_GET['pw']; // collect passed variable 2
// To protect MySQL injection
$id = stripslashes($id);
$pw = stripslashes($pw);
// $id = mysql_real_escape_string($id);
// $pw = mysql_real_escape_string($pw);

// Connect to server and select databse.
$con = mysql_connect( $dbhost, $dbuser, $dbpass );
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db($dbname, $con);
$query = "SELECT Softid, PartPass FROM $table1 WHERE Softid = '$id' and PartPass = '$pw'";
$result = mysql_query($query) or die(mysql_error() . $query );
// Mysql_num_row is counting table row
$count=mysql_num_rows($result);
if($count==1){
echo"<p>Hooray you are logged in</p>";
} else {
echo"<p>Oh Dear! Something went wrong. Query: <br/>$query </p>";
}
mysql_close($con);
?>

A couple of things still need fixing. First the user is not taken anywhere useful after logging in successfully. That is because there is currently nowhere to go. The second is that the diagnostic display of the query on login failure needs removing, after everything is definitely working.

After a successful login, the page currently looks as shown below:

Tuesday, October 25, 2011

JavaScript Business Rules

In my last two entries, I created the front end interface for a login screen, and wrote a couple of simple business rules in a PHP script to ensure both username and password fields are filled before running a query on the database. The time has now come to write the query and check it against the field entries.

Reading tutorials on the topic, I am first fascinated by the level of paranoia and then I become paranoid myself. So instead of getting on with writing a query, I add another business rule prohibiting usernames or passwords over eight characters. Eight is the length of the fields in the database, so it is as silly for users to enter 9 characters as no characters, so I might as well stop them doing it. It won't stop every SQL injection exploit, but it will preclude them from attempting to write essays.

I'm looking at a couple of tutorials for inspiration. They both use different SQL injection protection code. One uses the ereg() function, which is apparently being phased out, so I won't use that. The other takes the user to another page on login, which won't work with my business rules code.

I have to say I am not sure why I wrote the business rules into a PHP script. If I used Java Script for the business rules, I could take the user to a new page on successful login, and I could completely avoid unnecessary calls on the server itself, as well as on the database. But it will require a complete rethink.

To start fiddling, I change the login page back to an HTML file and remove all PHP. I then replace the PHP scripted error messages with division placed in the same place. The first is as follows:

<div id=ubercell1 class=warning></div><br/>

In the CSS file the class warning takes the color red. I then reduce the form tag down from:

<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">

to:

<form>

And the button is changed from:

<input type="submit" name="login" value="Log in to Portal" class=itext />

to:

<input type="button" value="Log in to Portal" class=itext onclick="busrules(this.form)" />

And of course the PHP code is replaced by the JavaScript function busrules(form). I spent some time fiddling with the JavaScript, because I don't know it very well. The essential logic is that any one or more of four possible errors will generate a warning and preclude the call to the database. When an error is corrected the warning message must be cleared, but where there is no warning (i.e. if the user gets it right first time) nothing needs to happen. And in this test page, if everything is OK, an alert message says everything is OK.

The rest of the page code remained the same, and the page looked the same, but without needing a call back to the server, the error messages came up a lot quicker than they did using PHP. The full JavaScript was:

<script type="text/javascript">
function busrules(form)
{
var subname = form.username.value;
var subpass = form.password.value;
var showmessn;
var showmessp;
var ubercell1v = document.getElementById("ubercell1").innerHTML;
var ubercell2v = document.getElementById("ubercell2").innerHTML;
if (ubercell1v.length > 0)
{
document.getElementById("ubercell1").innerHTML="";
} //end of null check
if (ubercell2v.length > 0)
{
document.getElementById("ubercell2").innerHTML="";
} //end of null check
if (subname.length > 8 || subname.length ==0 || subpass.length ==0 || subpass.length ==0)
{
if (subname.length > 8)
{
showmessn = "Your user name is too long. Please use 8 characters.";
document.getElementById("ubercell1").innerHTML=showmessn;
} //end of condition 1
if (subname.length ==0)
{
showmessn = "Oh Dear! You have not entered your user name.";
document.getElementById("ubercell1").innerHTML=showmessn;
} //end of condition 2
if (subpass.length > 8)
{
showmessp = "Your user password is too long. Please use 8 characters.";
document.getElementById("ubercell2").innerHTML=showmessp;
} //end of condition 3
if (subpass.length ==0)
{
showmessp = "Oh Dear! You have not entered your user password.";
document.getElementById("ubercell2").innerHTML=showmessp;
} //end of condition 4
} else {
alert ("Well Done. Your username and password were correctly entered.");
} //end of master conditional statement
} //end of function
</script>

Sunday, October 23, 2011

PHP Business Rules

The purpose of the business rules layer is to prevent gibberish being written to a database. If you have a field designated to record currency values, you don't want someone posting a long letter to their mother to it. Of course if you try to write text to a numeric field the database itself will probably reject it, but doing so wastes server resources and risks corrupting the database.

And in an age of web applications, where servers and clients are separated by long distance and heavy traffic, sending redundant requests to the server wastes time and annoys the user.

There are two aspects to the business rules layer:

  1. The coded rules;
  2. The front end manifestation when one or more of the conditions set out in the rules is not met.

In the olden days, if you tried to make an illegal entry into a database field, a new window or dialog box opened up with a rude message, and sometimes the computer would beep at you. The dialog box would then have to be closed manually by the user before they could continue with their work.

Nowadays a more subtle approach is preferred. Usually a message is written on to the data entry form itself, just above or close to the field with the inappropriate or missing entry.

In the case of a login screen, nothing is being written to the database, and a null field is conceptually similar to an incorrect entry, so some applications skip business rules in the login screen and send null fields for checking against the database along with everything else.

My server is particularly slow, and I am always aware of the implicit cost of making unnecessary calls on the database, so I shall write a couple of lines to ensure users at least put something in both username and password fields.

The login screen shown in my previous post was written in HTML and tested at home. I shall now have to migrate across to PHP and as I don't have PHP installed at home, I shall have to work on my web host server.

The PHP script will open with the include() statement and a variable declaration for the error condition:

include('dbinfo.php'); // get database information
$error = false; //boolean used to contain error condition

It will continue with the equivalent of event code for the button click event. In this case there is no need to register an actual event, because the login button is calling the containing page:

<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">

The code for the whole page is rerun when the button is clicked, so there is no need to register the event as such, but rather the condition of having been clicked:

if (isset($_POST['login'])) {
// variables filled with form inputs
$usertype = $_POST['usertype'];
$username = $_POST['username'];
$password = $_POST['password'];
// check that neither field is empty
if ( !empty($firstname) && !empty($lastname) ) {
//run crunchy code
} else {
$error = true; // error condition met
} // end of empty field check
} // end of buttonclicked conditional code

The "crunchy code" will be discussed later. For now, I need to insert a couple of extra lines into the page to use the $error variable. The first insert goes at the top of the <div> I called row2, which holds the username field:

<?php
if ( $error && empty($username) ) {
echo '<span style="gt;Oh Dear! You did not enter your name.</span><br>',"\n";
}
?>

The second insert goes at the top of the <div> I called row3, which holds the password field:

<?php
if ( $error && empty($password) ) {
echo '<span style="gt;Oh Dear! You did not enter your password.</span><br>',"\n";
}
?>

I have to admit that this is easier using the <div> tag than it would have been using a table. A table would have required a new row, and a cell spanning two column widths for each insert. Using the <div> tag, I just squashed the new code inside the containing division and above the two floating "cells".

The code for the whole page has now become:

<?php
include('dbinfo.php'); // get database information
$error = false; //boolean used to contain error condition
/**
* The code below is ignored when the page loads
* but is run on reload after button click.
*/
if (isset($_POST['login'])) {
// variables filled with form inputs
$usertype = $_POST['usertype'];
$username = $_POST['username'];
$password = $_POST['password'];
// check that neither field is empty
if ( !empty($firstname) && !empty($lastname) ) {
//run crunchy code
} else {
$error = true; // error condition met
} // end of input check
} // end of buttonclicked conditional code
?>

<html>
<head>
<title>Active Math Java Private Portal</title>
<link rel="stylesheet" type="text/css" href="pportal.css" />
</head>
<body>
<div id="container">
<div id="header">
<h1 class="top">Rasch-ItemBank</h1>
<h3 class="top">A
<a class="top" href="http://www.interactived.com/softway.htm">
Softway</a> Open Source Project <br/>
Hosted by <a class="top" href="http://java.net/projects">Java.net</a>
</h3>
</div>
<div id="left">
<b>Menu</b><br />
<a class="menu" href="http://www.interactived.com/softway.htm">Home</a><br />
<a class="menu" href="http://www.interactived.com/research.htm">Research</a><br />
<a class="menu" href="http://www.interactived.com/software.htm">Software</a>
</div>
<div id="content" style="height:400px;width:85%;">
<h1 class="main">Active Math Java</h1>
<h3 class="main">Private Portal<br/>
The Blueridge School of Apalit, Inc.
</h3>
<div id=logintable class=inputtable>
<div id=row1 class=row>
<h3>Initial Login Screen</h3>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<div id=row1 class=row>
<div id=cell11 class=col1>Please select user or admin</div>
<div id=cell12 class=col2>
<select name="usertype" class=cbox>
<option value="user">user</option>
<option value="admin">admin</option>
</select>
</div>
</div><br/>
<div id=row2 class=row>
<?php
if ( $error && empty($username) ) {
echo '<span style="gt;Oh Dear! You did not enter your name.</span><br>',"\n";
}
?>
<div id=cell21 class=col1>Please enter your name</div>
<div id=cell22 class=col2><input type="text" name="username" class=itext /></div>
</div><br/>
<div id=row3 class=row>
<?php
if ( $error && empty($password) ) {
echo '<span style="gt;Oh Dear! You did not enter your password.</span><br>',"\n";
}
?>
<div id=cell31 class=col1>Please enter your password</div>
<div id=cell32 class=col2><input type="password" name="password" class=itext /></div>
</div><br/>
<div id=row4 class=row>
<div id=cell41 class=col1>Click button to log in</div>
<div id=cell42 class=col2><input type="submit" name="login" value="Log in to Portal" class=itext /></div>
</div><br/>
</form>
</div>
</div>
</div>

<div id="footer">
Helping Children to Achieve their Potential</div>
</div>
</body>
</html>

And when I clicked the login button, with two empty fields, the page came up as shown below:

Saturday, October 22, 2011

Creating a login page

There are three steps to creating a login page, or really any page which exchanges information with a database.
  1. Creating the front end interface;
  2. Writing the business rules;
  3. Writing the interface with the database.

In a previous post I already described a form which added records to a data table. In that example I was a bit sloppy, because I omitted any business rules code. My excuse was that the data table in that example was intended to be populated automatically, so the input form would never be used in real life.

I am now dealing with a request from a school to track student performance, so I have to create a manual database portal or interface for them. The first step is the login screen. At a trivial level, this is just a couple of fields and a button, so not much thought needs to go into it.

But as I am using the exercise to stimulate a web site redesign, I have chosen to go a little deeper. My usual method of making forms look reasonably neat is to shove them in a table. But the HTML purists don't like table any more, so I decided to look into using the <div> tag instead. At the same time, I extended my use of the external CSS page, which I used in my previous post.

Whether correctly or not, I followed the pattern of a table, with a series of horizontal rows, each nested with two "cells", one floating to the left, the other to the right, and all inside a "zone" which I classified as "inputtable", which in turn lay inside the page (code not shown) created in my previous post:

<div id=logintable class=inputtable>
<div id=row0 class=row>
<h3>Initial Login Screen</h3>
<form>
<div id=row1 class=row>
<div id=cell11 class=col1>Please select user or admin</div>
<div id=cell12 class=col2>
<select name="usertype" class=cbox>
<option value="user">user</option>
<option value="admin">admin</option>
</select>
</div>
</div><br/>
<div id=row2 class=row>
<div id=cell21 class=col1>Please enter your name</div>
<div id=cell22 class=col2><input type="text" name="username" class=itext /></div>
</div><br/>
<div id=row3 class=row>
<div id=cell31 class=col1>Please enter your password</div>
<div id=cell32 class=col2><input type="password" name="password" class=itext /></div>
</div><br/>
<div id=row4 class=row>
<div id=cell41 class=col1>Click button to log in</div>
<div id=cell42 class=col2><input type="submit" value="Log in to Portal" class=itext /></div>
</div><br/>
</form>
</div>
</div>

To accommodate the extra classes, the CSS page was expanded as follows:

body {
margin:10px 0px; padding:0px;
text-align:center;
}
#container {width:800;}
#header {background-color:#151B8D;text-align:left;}
#left {background-color:#5CB3FF;height:500px;width:15%;float:left;text-align:left;}
#content {height:400px;width:85%;}
#footer {background-color:#488AC7;clear:both;text-align:center;}

a:link {text-decoration:none;} /* unvisited link */
a:visited {text-decoration:none;} /* visited link */
a:hover {text-decoration:underline;} /* mouse over link */
a:active {text-decoration:none;} /* selected link */

h1.top {margin-bottom:0;color=#FFFF00;}
h3.top {margin-bottom:0;margin-top:0;color=#FFFF00;}
a.top {color=#FFFF00;}

h1.main {margin-bottom:0;text-align:center;}
h3.main {margin-bottom:0;margin-top:0;text-align:center;}

a.menu {color=#000000;}

.inputtable {margin:50; background-color:#BDEDFF}
.row {width:420;}
.col1 {text-align:right; float:left; width:200; margin:0 5 0 5;}
.col2 {text-align:left; float:right; width:200; margin:0 5 0 5;}
.itext {width:150;}
.cbox {width:150; margin-left:5;}

And the finished page looked as follows:

Friday, October 21, 2011

Web site redesign

In my quest to get my Applet talking to a commercially hosted MySQL database, I was forced to update my knowledge of a number of related areas, including HTML. Coincidentally, I get a lot of spam telling me how dreary and old fashioned my MS Front page designed website is.

A school has asked for a private portal to the Applet, and I want the page to remain outside the main website navigation structure. I could just give them a form on a plain page. Or I could use the opportunity to play with HTML layouts and CSS.

My favorite tutorial site, W3schools, has a nice sample layout, similar to their own. I have adapted this with my own colors and text. I have also changed the behavior of links, so that they look more like surrounding test, except when they are hovered over. My HTML was as follows:

<html>
<head>
<title>Active Math Java Private Portal</title>
<style type="text/css">
a:link {text-decoration:none;} /* unvisited link */
a:visited {text-decoration:none;} /* visited link */
a:hover {text-decoration:underline;} /* mouse over link */
a:active {text-decoration:none;} /* selected link */
</style>
</head>
<body>
<div id="container" style="width:100%">
<div id="header" style="background-color:#151B8D">
<h1 style="margin-bottom:0;color=#FFFF00;">Rasch-ItemBank</h1>
<h3 style="margin-bottom:0;margin-top:0;color=#FFFF00;">A
<a href="http://www.interactived.com/softway.htm" style="color=#FFFF00;">
Softway</a> Open Source Project</h3>
<h3 style="margin-bottom:0;margin-top:0;color=#FFFF00;">Hosted by
<a href="http://java.net/projects" style="color=#FFFF00;">Java.net</a></h3>
</div>
<div id="menu" style="background-color:#82CAFA;height:400px;width:15%;float:left;">
<b>Menu</b><br />
<a href="http://www.interactived.com/softway.htm" style="color=#000000;">Home</a><br />
<a href="http://www.interactived.com/research.htm" style="color=#000000;">Research</a><br />
<a href="http://www.interactived.com/software.htm" style="color=#000000;">Software</a></div>
<div id="content" style="height:400px;width:85%;">
<h1 style="margin-bottom:0;text-align:center">Active Math Java</h1>
<h3 style="margin-bottom:0;margin-top:0;text-align:center">Private Portal</h3>
<h3 style="margin-bottom:0;margin-top:0;text-align:center">
The Blueridge School of Apalit, Inc.
</h3>
</div>
<div id="footer" style="background-color:#56A5EC;clear:both;text-align:center;">
Helping Children to Achieve their Potential</div>
</div>
</body>
</html>

And it came up as shown below:

The tutorial recommended using an external CSS style sheet, so as to facilitate site wide design changes. That's fine for colors and fonts, but a question running through my mind is how they achieve site wide menu changes. Their own source code betrays few secrets these days because it might have been generated with a script, although it certainly represents a thorough example of using the <div> tag.

I found the CSS tutorial a bit confusing when it came to classes, but part of the confusion arose because of my inability to type. Anyway, after some fiddling around, my CSS page looked like this:

a:link {text-decoration:none;} /* unvisited link */
a:visited {text-decoration:none;} /* visited link */
a:hover {text-decoration:underline;} /* mouse over link */
a:active {text-decoration:none;} /* selected link */

h1.top {margin-bottom:0;color=#FFFF00;}
h3.top {margin-bottom:0;margin-top:0;color=#FFFF00;}
a.top {color=#FFFF00;}

h1.main {margin-bottom:0;text-align:center;}
h3.main {margin-bottom:0;margin-top:0;text-align:center;}

a.menu {color=#000000;}

#header {background-color:#151B8D;}
#left {background-color:#82CAFA;height:400px;width:15%;float:left;}
#content {height:400px;width:85%;}
#footer {background-color:#56A5EC;clear:both;text-align:center;}

And the HTML became:

<html>
<head>
<title>Active Math Java Private Portal</title>
<link rel="stylesheet" type="text/css" href="pportal.css" />
</head>
<body>
<div id="container" style="width:100%">
<div id="header">
<h1 class="top">Rasch-ItemBank</h1>
<h3 class="top">A
<a class="top" href="http://www.interactived.com/softway.htm">
Softway</a> Open Source Project <br/>
Hosted by <a class="top" href="http://java.net/projects">Java.net</a>
</h3>
</div>
<div id="left">
<b>Menu</b><br />
<a class="menu" href="http://www.interactived.com/softway.htm">Home</a><br />
<a class="menu" href="http://www.interactived.com/research.htm">Research</a><br />
<a class="menu" href="http://www.interactived.com/software.htm">Software</a>
</div>
<div id="content" style="height:400px;width:85%;">
<h1 class="main">Active Math Java</h1>
<h3 class="main">Private Portal<br/>
The Blueridge School of Apalit, Inc.</h3>
</div>
<div id="footer">
Helping Children to Achieve their Potential</div>
</div>
</body>
</html>

And to my enormous surprise it ended up looking exactly the same as that produced by the single page as shown above.

Saturday, September 24, 2011

Applet to AJAX to PHP methodology

I have an Applet, which adds lines to a database one at a time, by sending an SQL string via AJAX to a PHP script. The Applet data insertion method is as follows:

private void addItem3(String newWord) {
if(LIVE) {
if(jso != null )
try {
jso.call("updateWebPage", new String[] {newWord});
}
catch (Exception ex) {
addItem2("jso call failed... ");
ex.printStackTrace();
}
}
}

Where the parameter newWord being passed to that method might look like:

INSERT INTO mytable (Partid, OpCode, ItemLeft, ItemRight, Raw, Rate) VALUES (684, 1, 2, 5, 1, 34)

The JavaScript function updateWebPage and the PHP script were given in my previous post, so I won't repeat them here.

The thing is, even a single instance of the Applet can generate new lines very quickly, sometimes once a second. So a classroom of 25 students might generate 25 lines a second. How will my ISP server react to all these requests to open a connection, insert a single line of data, and close the connection.

In my experience, a typical eCommerce interaction involves a fairly long data reading session (browsing a catalogue) and then at the end, perhaps the insertion of a single line of data into a purchase order table. And from forum browsing, most Applet games seem to download some data at the start of the game, and then perhaps upload a line of data at the the end of the game. And if it is a game like Pacman, it might last for 10 or 15 minutes, or longer. So I am inclined to believe that your average eCommerce server, and certainly not a budget one like the one I use, is not designed to cope with such frequent data updates from a single source.

This blog is intended for theory questions and problems. Practical implementation thoughts and solutions are the domain of my Rasch blog, so I think I'll transfer this one over there.

Tuesday, September 20, 2011

Applet to JavaScript to PHP post to Database

This post brings together the previous two. In the first, I called PHP code from a JavaScript function using an AJAX command. In the second, I passed an SQL command to a JavaScript function. In this post I describe bringing the two together. Instead of simply displaying the SQL in a text box on the web page, passing it to a PHP file.

The applet code was unchanged, but the JavaScript function was extended from:

<script type="text/javascript">
function updateWebPage(myArg)
{
document.getElementById("txt1").innerHTML=myArg;
}
</script>

to:

<script type="text/javascript">
function updateWebPage(myArg)
{
document.getElementById("txt1").innerHTML=myArg;
if (myArg=="")
{
document.getElementById("cbxItem").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("cbxItem").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","putitem.php?id="+myArg,true);
xmlhttp.send();
}
</script>

And the HTML table had an extra couple of cells added:

<table border=1 align='center' cellpadding=0 cellspacing=0 >
<tr><td style='text-align:center; background-color:#C0C0C0'>Compiled Java Applet</td></tr>
<tr><td><applet code="JSHelloWorld2.class"
width="500" height="80" MAYSCRIPT style="border-width:0;" name="jsap" id="jsap">
</applet> </td></tr>
<tr><td style='text-align:center; background-color:#C0C0C0'>HTML Textbox filled by JavaScript</td></tr>
<tr><td><textarea style='width:500px; height:50px' name='txt1' id='txt1'>Query goes here</textarea></td></tr>
<tr><td style='text-align:center; background-color:#C0C0C0'>HTML diagnostic messages rendered by PHP script</td></tr>
<tr><td><div id="cbxItem">PHP info will populate this space</div></td></tr>
</table>

The PH script was:

<?php
$id = $_GET['id'];
include('dbinfo.php');// collect database variables and connect.
$con = mysql_connect( $dbhost, $dbuser, $dbpass );
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db($dbname, $con);
// first use encodeURIComponent on javascript to encode the string
// receive json string and prepare it to json_decode
$jsonStr = stripslashes ($id);
$query = $jsonStr;
$result = mysql_query($query) or die(mysql_error());
echo"<p>The query is: $query </p>";
echo"<p>The result is: $result </p>";
mysql_close($con);

?>

I hate it when people put obscure references in code, so for anyone who has not been following this blog, the dbinfo.php structure was given in the Simple Web Application – Data Display page.

On opening, the web page looked as shown below:

And after clicking the button on the applet, it was as shown below:

The result of 1 (or true) returned by the query indicated that a line had been successfully inserted. Inspection of the database using the Simple Web App, confirmed that this was the case. The only minor problem was the loss of the plus sign in "Itemdet", but that can be fixed.

Monday, September 19, 2011

Pass SQL command from Applet to JavaScript function

My last post recorded an important milestone for me, because I managed to call PHP code from a JavaScript function.

On an earlier occasion, I had managed to call a JavaScript function from an Applet.

My next task was to put the two together, and I did this in two steps the first of which (reported in the current post) was to adapt the previous Applet to JavaScript example to display an SQL command. This was essentially a cosmetic exercise, but it acted as a refresher on the code.

The only change to the Applet code was to replace "Hello World" with an SQL string. There is no need to reprint that here as it was given in my previous post on the topic.

In the HTML, I modified the table to display the Applet above the text box, and I widened them both. I also removed the update Applet function, as it was not required for the current exercise. It was then as follows:

<html>
<body>
<script type="text/javascript">
function updateWebPage(myArg)
{
document.getElementById("txt1").innerHTML=myArg;
}
</script>
<form>
<table border=0 align='center' cellpadding=0 cellspacing=0 >
<tr>
<td valign='top'>
<table>
<tr><td style='text-align:center; background-color:#EEEEEE'>Applet</td></tr>
<tr><td>
<applet code="JSHelloWorld2.class"
width="500" height="80" MAYSCRIPT style="border-width:0;" name="jsap" id="jsap">
</applet> </td></tr>
<tr><td style='text-align:center; background-color:#EEEEEE'>JavaScript</td></tr>
<tr><td><textarea style='width:500px; height:50px' name='txt1' id='txt1'>Query goes here</textarea></td></tr>
</table>
</form>
</body>
</html>

It came up initially as shown below:

After clicking the Applet button it was then as shown below:

And to my amazement, I could modify the text (see below) as many times as I liked, and the modified text was transferred across every time.

Sunday, September 18, 2011

PHP and JavaScript/AJAX database query

Including the term JavaScript here is tautologous really because AJAX written out in full is Asynchronous JavaScript and XML. But as combining PHP and JavaScript has become something of a holy grail for me, I thought I'd include it anyway. In fact my September 9 blog entry was originally posted under the title PHP and JavaScript (so keen was I to use it), until I reflected on the text overnight and realised there was actually nothing about JavaScript in the post.

I have been running around in circles a bit over the last couple of months, but they have been good circles, because they have enriched my understanding of a number of web related topics. And my current circle has taken me back to the generally excellent and easy to follow W3Schools website. In my post on their AJAX tutorial, I bemoaned that fact that their exchanging data with a server example only read data from a "measly old text file", rather than a database. However, had I dug deeper in my first post on PHP, I might have noticed that the w3schools tutorial on the topic gives an example of communicating with a database, using AJAX and PHP, in one of the advanced sections. I shall now work through that example.

My first step is to cut and paste their exact web code to see if it works. Should I post it here? When I first began this blog, I posted almost no code, but included an array of links to sources. A couple of years later, when I went back to reread some of my early posts, I found that many of my sources had changed their URL or disappeared altogether. So I started posting code. But the question then arises, should the full 30 or more line copyright notice be included with every code snippet. I think not. That would render the blog unreadable. "Fair Practice Law" in most countries allows you to copy snippets, certainly from literature, as long as you acknowledge your source. Would that apply to a full working web page? Possibly not. I shall refrain from quoting it, and apologise if the source subsequently disappears.

Of course I have posted code for some working web pages in my last few entries, (and in fact below) but I think one, of a couple of important questions, is did I copy something and change it, or did I write something of my own and draw inspiration from a source. It is something of a moot point, but I think there are a couple of things to bear in mind. Did I begin with a downloaded file, or did I begin with a clean sheet of paper? In this case I began clean, because of the database communication differences. A second important question is did I use a single source for inspiration? Again, I used more than one source, for practical and cosmetic reasons.

Meanwhile, back in reality, I have cut and pasted the HTML, and it works. And while I am not posting the HTML, I shall post a screen shot (below), because on an empty page it looks a bit different. But it certainly works. I had a quick look at the dropdown box, and the names were all there as in the tutorial. Obviously I refrained from selecting one because I haven't written a PHP file. And this is where I have to put my thinking cap on, because for this to be useful to me, it has to work with my data, and there are no "names" in my database.

Getting it to work for me involved one major change to the HTML, and a few cosmetic changes. The major change was to rewrite the dropdown box from scratch to make it meaningful for my data. The cosmetic changes were to variable names - not strictly necessary, but they always say variable names should try to reflect what they contain.

An important point to note here, for the unwary, is that parameters passed by AJAX seem to in the form of strings. The index field in my database is an integer, so I was tempted to try and pass an integer through AJAX. But from my notes on AJAX the syntax of the open method is:

xmlhttp.open("METHOD","URL",async);

Where URL is, and will always be a string. So in my code (shown below), my attempts to change the idx variable (in the function, and in the dropdown box) to a number were futile, and had to be abandoned. The variable was passed as a string, but the character was included in the SQL statement (shown further below) as a number.

A final point is that I included some diagnostic lines, but these were pretty redundant as PHP errors were picked up in the parse, and SQL errors were also caught by an error trap in the code. After all this, my HTML was:

<html>
<head>
<head>
<title>AJAXPHPexpt1</title>
<script type="text/javascript">
function showItem(idx)
{
if (idx=="")
{
document.getElementById("cbxItem").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("cbxItem").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getitem.php?id="+idx,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form>
<select name="itemselection" onchange="showItem(this.value)">
<option value="">Select an item:</option>
<option value="2">2+2=</option>
<option value="4">2+3=</option>
<option value="7">4+3=</option>
</select>
</form>
<br />
<div id="cbxItem"><b>Item info will be listed here.</b></div>
</body>
</html>

And my PHP code was:

<?php
$id = $_GET['id'];
include('dbinfo.php');// collect database variables and connect.
$con = mysql_connect( $dbhost, $dbuser, $dbpass );
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db($dbname, $con);
$query = "SELECT * FROM mytable WHERE Itemid=".$id;
$result = mysql_query($query) or die(mysql_error());
echo"<p>The item id is now: $id </p>";
echo"<p>The query is: $query </p>";
echo
'<table style="text-align:center;">
<tr bgcolor="#CCCCCC">
<td width="60"><strong>Itemid</strong></td>
<td width="60"><strong>Partid</strong></td>
<td width="60"><strong>OpCode</strong></td>
<td width="60"><strong>Itemdet</strong></td>
<td width="60"><strong>Raw</strong></td>
<td width="60"><strong>Rate</strong></td>
</tr>';
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['Itemid'] . "</td>";
echo "<td>" . $row['OpCode'] . "</td>";
echo "<td>" . $row['Partid'] . "</td>";
echo "<td>" . $row['Itemdet'] . "</td>";
echo "<td>" . $row['Raw'] . "</td>";
echo "<td>" . $row['Rate'] . "</td>";
echo "</tr>";
}
mysql_close($con);
?>

And after selecting an item, the page was as shown below:

Saturday, September 17, 2011

Simple Web Application – Delete Data line

Once again I should like to acknowledge the Virginia Tech Simple Web Application sample code, which provided a template for this little project, which has really helped to improve my practical understanding of PHP.

Having said that, the code, required to delete lines from the database, is pretty slim. Once again I bloated it out with some diagnostic HTML, just to check the query. I hate running blind.

The bloated code was as follows:

<?php
$id = $_GET['id'];
if (empty($id)) {
Header("Location: listcontacts.php");
exit;
}
include('dbinfo.php');// collect database variables and connect.
$con = mysql_connect( $dbhost, $dbuser, $dbpass );
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db($dbname, $con);
$query = "DELETE FROM mytable WHERE Itemid=".$id;
$result = mysql_query($query) or die(mysql_error());
mysql_close($con); //close connection because job finished
// Header("Location: jsphp4.php"); //return to main display form
?>
<html>
<head>
<title>Delete item diagnostics</title>
</head>
<body>
<h1>Delete Item</h1>
<p>The item id is now: <?php echo $id ?> </p>
<p>The query is: <?php echo $query ?> </p>
</body>
</html>

And the page was as shown below:

After checking the query, the slimmed down “production” code was:

<?php
$id = $_GET['id'];
if (empty($id)) {
Header("Location: listcontacts.php");
exit;
}
include('dbinfo.php');// collect database variables and connect.
$con = mysql_connect( $dbhost, $dbuser, $dbpass );
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db($dbname, $con);
$query = "DELETE FROM mytable WHERE Itemid=".$id;
$result = mysql_query($query) or die(mysql_error());
mysql_close($con); //close connection because job finished
Header("Location: jsphp4.php"); //return to main display form
?>

And of course there is no pic to show, because after the delete code has run we are returned to the main page.

In fact this whole exercise derived from a desire to check how that is done - modifying data in a database while (having the illusion of) remaining on the same page.

So now I have called a JavaScript function from an Applet, and I have called a PHP script, which has modified data in a database, from a button on a web page.

My next step is to call a PHP script from an Applet.

Friday, September 16, 2011

Simple Web Application – Add Data Form

While I must still acknowledge the Virginia Tech Simple Web Application sample code, at this stage in the project I was primarily cutting and pasting from the code shown in my previous posts, and manually making a few small changes from the sample code.

The code used in the Add data line form is very similar to that for the Edit data line form, except that there is no existing data to display, and the SQL command is INSERT rather than UPDATE.

I also removed the input validation code. Any data entered manually into my database is bogus and must be deleted after this exercise has finished, so it really doesn't matter what fields are filled or left empty.

With no data to display, there no need to confirm that a data line was being correctly passed from the main display form, and no need to confirm that the line was being correctly read. I therefore left in just a couple of diagnostic messages at the top of the form:

<p>The query is: <?php echo $query ?> </p>
<p>Status is: <?php echo $jonathan ?> </p>

Of course to view these lines after clicking the add button, it is necessary to comment out the instruction to return to the main form right after adding data as follows:

// Header("Location: jsphp4.php"); //return to main display form

When everything is working the comment strokes (on the left) can be removed, and the diagnostic lines can be removed from the HTML.

My working (diagnostic) code was as follows:

<?php
include('dbinfo.php');// collect database variables and connect.
$con = mysql_connect( $dbhost, $dbuser, $dbpass );
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db($dbname, $con);
if (isset($_POST['addcontact'])) { // run this when the user hits the "Add Contact" button
$jonathan="Add loop";
$Partid = $_POST['Partid'];
$OpCode = $_POST['OpCode'];
$Itemdet = $_POST['Itemdet'];
$Raw = $_POST['Raw'];
$Rate = $_POST['Rate']; // input validation removed from under here
$query = "INSERT INTO mytable (Partid, OpCode, Itemdet, Raw, Rate) VALUES (".$Partid.",".$OpCode.",'".$Itemdet."',".$Raw.",".$Rate.")";
$result = mysql_query($query) or die(mysql_error()); //adds form inputs
mysql_close($con); //close connection because job finished
Header("Location: jsphp4.php"); //return to main display form
}
?>
<html>
<head>
<title>Add a Line</title>
</head>
<body>
<h1>Add a Line</h1>
<p>The query is: <?php echo $query ?> </p>
<p>Status is: <?php echo $jonathan ?> </p>
<form name="form1" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<table style="text-align:right;">
<tr><td>Partid:<input name="Partid" type="text" value="<?php echo $Partid; ?>"></td></tr>
<tr><td>Opcode:<input name="OpCode" type="text" value="<?php echo $OpCode; ?>"></td></tr>
<tr><td>Itemdet:<input name="Itemdet" type="text" value="<?php echo $Itemdet; ?>"></td></tr>
<tr><td>Raw:<input name="Raw" type="text" value="<?php echo $Raw; ?>"></td></tr>
<tr><td>Rate:<input name="Rate" type="text" value="<?php echo $Rate; ?>"></td></tr>
<tr><td><input type="submit" name="addcontact" value="Add Line"></td></tr>
</table>
</form>
<p><a href="jsphp4.php">Click here to return to List</a></p>
</body>
</html>

And after clicking the Add Line button, the page, with diagnostic code, was as shown below:

After removing the diagnostic code the page came up as shown below: