CS71 – Ass1 – Finance – Part 3 – javascript and common php page

I am doing the Harvards building dynamic websites called CS-75 (also could be called E-75), because someone told me about it and I just thought might as well, it is all learning 🙂 even if allot of it you may already know.

Before any of the actual pages start, they will all call this php file so that it will build up the classes and connect to the database, so to start with need to pull in there classes and also start the session. The two functions are the HTML header and footer parts of each page, so that do not have to alter every page to just add in another style as such, the last part is when we are creating the objects for the database/users/stocks.


 

  
    <?php echo $titleTag;?>
	
	
  
 



Because in the HTMLHeader function I am linking to the ass1.js file, which is the javascript code that will allow for a better user experience because we can do some input tests before sending to the server.

This is the function that checks the users input when they are trying to sell some of the stock that they have

function checkSell()
{
	var formElem = document.forms[0];
	var elemsEmpty =0;
	for (var i = 0; i < formElem.length; i++)
	{
		var elem = formElem[i];
		if (elem.type == "checkbox" && elem.checked)
			elemsEmpty++;
	}
	if (elemsEmpty ==0)
	{
		alert("Please select a item to sell");
		return false;
	}
	return true;
}

When the user is on the buying stock page, it would be good to make sure that the value is a integer value before the user actually sends the request to the server, it will also check to make sure that there is a symbol to search for, saves on just clicking on the submit without any data.

function CheckBuy()
{
	var symbol = document.getElementById("searchSymbol");
	var amount = document.getElementById("AMOUNT");
	
	if (symbol.value.length < 3 && amount == null)
	{
		alert("Please insert a search symbol");
		symbol.focus();
		return false;
	}
	
	if (amount != null && amount.length >0)
	{
		if (isNaN(amount) && amount.value > 0)
		{
			if (!document.getElementById("BUYME").checked)
			{
				alert("Please select the tick box next to the amount");
				return false;
			}	
		}
		else 
		{
			alert("Please enter a valid amount to buy");
			document.getElementById("AMOUNT").focus();
			return false;
		}
	}
	return true;
}

This function actually checks the users input on the amount of stock to buy and making sure that it is only numeric values.

// only allow integer values within the box
function CheckKey(boxToCheck)
{
	var boxValue="";
	for (i = 0; i < boxToCheck.value.length; i++)
	{
		if (!isNaN(boxToCheck.value[i]))
			boxValue += boxToCheck.value[i];
	}
	boxToCheck.value = boxValue;
}

This function, checks to make sure that the registration screen has a valid email address (does another check on the server if the user turns off javascript), and also checks the password for the correct format.

function CheckRegister(justUsername)
{
	var username = document.getElementById("username");
	var password = document.getElementById("password");
	if (username.value.match(/^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/)) {
		if (justUsername)
			return true;
		return CheckPassword(password);
    }else{   
		alert("Incorrect email format"); 
    }
	return false;
}

This the actual function that will check the password is in the correct format, e.g. 1+ numeric/alpha characters. and more than 6 in length.

function CheckPassword(password)
{
	if (password.value.length >=6) {
		var addLet = 0;
		for (var i =0; i < password.value.length; i++) {
			if (isNaN(password.value[i]))
				addLet++;
		}
		if (addLet == password.value.length)
		{
			alert("Please enter a password that contains at least 1 aplha/numeric character");
		} else
			return true;
	} else
		alert("Please enter a password that is at least 6 characters long");
	return false;
}

Here on the change password, I am making sure that the first password conforms to the above function check and also that the two passwords are the same in value.

function CheckChangePasswords()
{
	if (CheckPassword(document.getElementById("password1"))) 
	{
		if (document.getElementById("password1").value == document.getElementById("password2").value)
			return true;
		else
			alert("Passwords do not match");
	}
	return false;
}

Next is the actual php pages that the user will interact with.

CDATA, With, Match and Regular Expression

CDATA

Sometimes when you get errors within your HTML validation can sometimes just get bogged down with javascript code that has not been “told” to be ignored by the parser, for example the javascript code

if (a < b)

is fine within that context, but within HTML the < could be a start of a tag and thus would fall over with some old parsers and also the validator, so best to wrap the javascript code within the CDATA

 

WITH

The with syntax will allow you to work on a object of a HTML form elements within having to constantly referencing the object fully, for example if you had a HTML as

and so within the javascript you could do something like this without using the with statement,

var theinput = document.form.theform.theinput;

well if you wanted to you could use the “with” syntax and thus if you wanted to access all of the elements within that HTML object then

with (document.form.theform)
{
    var first = theinput;
    var second = secondinput;
}

just allot more nicer to use the objects :).

Match / Regular expression

Since a string within the javascript is capable of having regular expression actions applied to it, you can use the inbuilt method that is associated with the string class as such, which allows you to do regular expression, but for some reason you do not need to put in the ” ” around the regular expression.

var username = document.getElementById("username");
if (
    username.match(/.+@.+\.com$)
   ) {
.... 

will match with a regular expression so that the username has to end with .com for it to be valid!!.. not really a good test, but there you go!.

JQuery

JQuery is a library API within the javascript language, the API (Application Program Interface) is classes/functions that do all of the work for you and you can access them.

Both google and Microsoft host the JQuery API for you, and all you need to do is to load in the javascript from either or server hosted setup, for google it would be this to get version 1.4.2 of the JQuery language.




-- or one line


or with MS you can use

once you have the JQuery API loaded you can then access the HTML document objects by using the $ symbol and act on any part of that document object that supports the functions that you want to do, e.g. a div tag would have different options for styling compared to a span tag.

The API library set is defined abit more in that link, but in whole it is a very effective and usable API library that just makes life more fun :).

For example the code below will output a mini function that will for “each” number in the first parameter (can be anything, object, letters etc) and do the function, will in this case will square the value, but the .each command is very powerful,

$.each([1,2,3], function()
{
	document.write(this * this);
});

the reason why it is very powerful is because if you want to select a group of items and then on each of them alter there elements, then you just need to use the JQuery selection process, like so

$("div").each

and this will alter all of the div’s on the web page accordlying. Shall do some more posts on JQuery API once I have a full set of examples to attached to the post.

HTML Elements and altering them

With javascript you can alter the different elements within the HTML page, which is great when you are doing things like AJAX and you just want to alter one part of the page and not the whole page.

All you need to do is to get the element that you want to “talk” to and then alter that HTML tags element parts, so lets say that you have a HTML P tag

  

you can get that element within a variable for javascript to talk to it via

     var elem = document.getElementById("hideme");

and now you can alter all parts of that HTML P tag, e.g. the style, the inner HTML text (which is the text within the <p>innerHTML</p> tags) which gives you allot more things to do on the page that allows more of a desktop feel to the site over a static page that you need to send back and forth to the server.

Of course you cannot alter any internal parts of the HTML tag that do not exist e.g. for the HTML Input there is no innerHTML because it only has a value (the text within the input box) so if you try and do that some web browsers will error/stop/or just ignore.

Here is the full source code that will alter a HTML P style to red and also the innerHTML, and also a lower one will hide and then show the text within a HTML P tag whilst altering the link to show either “click here to hide me”/”click here to show me”, which once again helps users to now what to do.






  
  Click me
  

some text within the paragraph

hideme after the click below
you can alter the style e.g. style.display = value
and also alter the innerHTML - as I am altering the HTML A tag below text from hide/show me

click to hide me

with using more javascript on pages, you need to have a way of keeping details of the updates on a page if you browse away from that page and come back which is where some problems could arise. So you just need to freshen up on your HTML tags and what they are capable of doing and have fun 🙂

Prototypes

Prototypes are a great thing with javascript, and they really come into there own with ajax and jQuery. A prototype basically it extends the present functional aspects. So lets say that you have a basic shape of animal (legs, head etc) and then you want to extend that basic shape with the option if the animal can fly then you can write a prototype to extend that, the prototype can either be a function or a variable so for example

// variable
animal.prototype.flyable = false;
// function
animal.prototype.canFly = function() {
     return this.flyable;
}

the “this.” means access the variables/functions within the main type (in this case it would be the animal as the main type).

in the example I am just altering some text within a HTML input tag, to start with I am creating a function (that I will extend later) and create a local (this.) variable that points to the element passed by using the document object, afterwards set the value equal to “hi from the parent”. I called it the parent because it is the main type,

  function nameing(elem)
  {
      this.theelem = document.getElementById(elem);
      this.theelem.value = "hi from the parent";
  }

then to extend this type, you start with the typename.prototype.extension_name, so the examples below will either return the value from the document element value that was setup in the “parent” / main type, and also the setText function will set the text to the document element.

  
  nameing.prototype.getText = function() 
  {
    return this.theelem.value;
  }

this is how I set up the object by calling new on the main type with passing in the element that I want to link to the object.

  // sets up the link with the 'thewords' id element within the html page
    var name = new nameing('thewords');

it is all very similar to other object languages, where you reference the object itself by using the “this.” syntax.

Below is the full html code that you can copy-paste into your favourite text editor and then open up in a web browser to see what you think.






  
  Click me


Web page inputs and insert into database – Part 2

As from here, where I outlined the javascript, html part of the exercised here is the php and mysql parts of the problem.

Here is the table that I created within MySQL

CREATE TABLE `User` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `firstName` varchar(50) DEFAULT NULL,
  `lastName` varchar(50) DEFAULT NULL,
  `email` varchar(50) DEFAULT NULL,
  `phoneNum` varchar(20) DEFAULT NULL,
  `guid` varchar(36) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=9 DEFAULT CHARSET=latin1;

As from my other post about MySQL triggers, so to find out more information about why please check out that page, and here is the trigger that I created for the above table.

CREATE trigger User_insert 
BEFORE INSERT ON User 
FOR EACH ROW 
BEGIN 
        SET NEW.guid = uuid(); 
END

The reason why I created this for was because within the exercise they asked “would forward planning, i.e. adding a unique code to the user details that could be used to validate their email address”, which by using a uuid, you can use that as a unique code.

so the only part left is the PHP that will connect to the database and also sanitize the inputs within sql insert. So created a class that has a constructor that will open a database connection to a database

      private $dbLink;
      /* connect to the database*/
      function __construct($host = "localhost", $user = "user", $password = "password", $database = "database")
      {
	$this->dbLink = mysql_connect($host, $user, $password);
	if (!$this->dbLink) die("no database present");
	if (!mysql_select_db($database, $this->dbLink))
	  die("no database within the database");
      }

Here I try to sanitize the insert string so that it will use the mysql_real_escape_string, this will use a php function that helps with SQL injections, also I am using the stripslashes and then trim the string to make sure that there is no white spaces (or any valid text left).

      /* santize the input for a mysql database */
      public function santizeInput($theStr)
      {
	return trim(stripslashes(mysql_real_escape_string($theStr)));
      }

and then to insert the data, just use the mysql_query and the sanitize function above to insert data into the database.

      /* insert the data into the database */
      public function insertData($sqlData)
      {
	mysql_query($this->santizeInput($sqlData), $this->dbLink) or die("Error inserting data");
      }

And here is where I get the data from the form post from the web page and then double sanitize the data and then create a database link, which in-turn use to insert the data.

    // could use foreach loop $_POST inputs, but I personally prefer to pick them up.
    $firstname = $_POST['firstname'];
    $secondname =$_POST['secondname'];
    $email = $_POST['email'];
    $phonenumber = $_POST['phonenumber'];
    
    /* could do additional checks on input incase it is sent via backend POST and not via the webpage,  could do with regular expression as well ? */
    $db = new databaseAccess("localhost", "username", "password", "database");
    /* can santize the inputs to make sure that there is some data to "play" with */
    $firstname = $db->santizeInput($firstname);
    $secondname =$db->santizeInput($secondname);
    $email =$db->santizeInput($email);
    $phonenumber = $db->santizeInput($phonenumber);
    
    if (checkLength($firstname) && checkLength($secondname))
    {	
	$sql = "insert into User (firstname, lastname, email, phoneNum) values (\"$firstname\",\"$secondname\",\"$email\", \"$phonenumber\")";
	$db->insertData($sql);
	echo "Data inserted";
    }

I did write within the exercise that since someone may try and post the data to the server within using the webpage (naughty people that they are!!) you could also check the inputs again for there data validity.

Here is the full code for the web page in total.

dbLink = mysql_connect($host, $user, $password);
	if (!$this->dbLink) die("no database present");
	if (!mysql_select_db($database, $this->dbLink))
	  die("no database within the database");
      }
      
      /* disconnect */
      function __destruct()
      {
	if (!$this->dbLink) mysql_close($this->dbLink);
      }
      
      /* santize the input for a mysql database */
      public function santizeInput($theStr)
      {
	return trim(stripslashes(mysql_real_escape_string($theStr)));
      }

      /* insert the data into the database */
      public function insertData($sqlData)
      {
	mysql_query($this->santizeInput($sqlData), $this->dbLink) or die("Error inserting data");
      }
    }
    
    function checkLength($theStr)
    {
      if (strlen($theStr) > 0) 
	return true; 
      else 
	return false;
    }
    
    // could use foreach loop $_POST inputs, but I personally prefer to pick them up.
    $firstname = $_POST['firstname'];
    $secondname =$_POST['secondname'];
    $email = $_POST['email'];
    $phonenumber = $_POST['phonenumber'];
    
    /* could do additional checks on input incase it is sent via backend POST and not via the webpage, not sure if SOAP are looking for that as well ? 
      could do with regular expression as well ? */
    $db = new databaseAccess("localhost", "User", "PW", "Test");
    /* can santize the inputs to make sure that there is some data to "play" with */
    $firstname = $db->santizeInput($firstname);
    $secondname =$db->santizeInput($secondname);
    $email =$db->santizeInput($email);
    $phonenumber = $db->santizeInput($phonenumber);
    
    if (checkLength($firstname) && checkLength($secondname))
    {	
	$sql = "insert into User (firstname, lastname, email, phoneNum) values (\"$firstname\",\"$secondname\",\"$email\", \"$phonenumber\")";
	$db->insertData($sql);
	echo "Data inserted";
    }
    
?>






First Name : Second Name : Email : Phone number :

If you save that as insertData.php then open up within your web-server. You will be able to insert data into a database with some javascript / php checks.

AJAX – setup and test

AJAX is the way of communicating with a back end server without having to send the full information (you can of course) but for example you could just send a username check to see if it is available, but the main thing is that you do not send back a full page but only the part that you want to update.

With reference to the example of a username, you could just send the username and send back either yes or no response which saves allot of time and traffic from the client to the server (and makes the whole web page experience nicer).

All the AJAX is shorthand for “Asynchronous JAvascript and Xml”, asynchronous means that you can do something else whilst waiting for the response (put the kettle on and get a cup for the drink whilst the kettle is boiling) thus with javascript on the client web browser sends a request to a web page on the server with XML wrappings.

To get the basics lets start with the being

  // this function will return a XmlHttpRequest object that allows you to "talk" to the server.
  function GetXmlHttpObject()
  {
      // IE7+, FF, Chrome, Opera, Safari
      if (window.XMLHttpRequest) return new XMLHttpRequest;
      
      // IE6 , IE5
      if (window.ActiveXObject) return new ActiveXObject("Microsoft.XMLHTTP");
  }

the GetXmlHttpObject will return a object that will allow the javascript to talk to the backend server, the newer version is call a XMLHttpRequest whilst on older browsers it was part of the ActiveXObjects.

The next is to send a request to the backend server

    xmlHttpObject.onreadystatechange=callBackFunction;
    xmlHttpObject.open("GET", GetUrl, true);
    xmlHttpObject.send(null);

The onreadystatechange, will call a function (in javascript on the client browser) when the request alters from different states, the different states are

  • 1.open method invoked successful, open a connection with the server
  • 2.server responsed with a valid header response.
  • 3.server has sent some data, the response content is started to load.
  • 4.server has finished sending all of data

so from reading the states, you are really interested in state 4, because that will have the data (server response) that you are interested in for this.

The .open forms the request to the XmlHttpRequest object to call (“GET” in HTML) the server web site, the GetUrl is just a variable that well call a php page (“ajaxbackendcall.php”) which takes a parameter called name and returns a string with the name in reverse (shall include that source code later).

And then the .send will start the ready states to change and sends the request to the backend server, here is the function that is called on the state change

  function callBackFunction()
  {
    if (xmlHttpObject.readyState == 4)
      alert(xmlHttpObject.responseText);
  }

What is happening here, is that from the state stages I am waiting on ready state to equal 4 ( when the server has finished responding) and then output the response from the responseText which is filled from the AJAX call to the backend server.

That is mainly it, here is some full code for you to try out save this as “codingfriends.com.ajax.test.html”







click here to return text from a ajax call

Enter the name here

and then save this as the ajaxbackendcall.php file to call (in the same directory as the code above and also within a directory that has PHP plugin enable for that webserver be it apache or IIS.

 0)
    {
      // have to insert something into it so that php does not make it into a array but a string
      $namereturn="0";
      $j = 0;
      for ($i = strlen($name)-1; $i >= 0; $i--)
      {
        $namereturn[$j++]=$name[$i];
      }
      echo "normal name {$name} and in reverse {$namereturn}";
    }
    else
      return "No name inputted";
?>

The output would be similar to the below. OUTPUT

click here to return text from a ajax call
Enter the name here

END OF OUTPUT

If you do not have a PHP webserver to test with, you can just alter the codingfriends.com.ajax.test.html code by altering the backend web page to call to this

var GetUrl = "nonephpbackend.html"

and create a page within the same directory as the codingfriends.com.ajax.test.html page and place something inside it like

hi there