Chris Nizzardini, Salt Lake City Utah, Web Developer Specializing in LAMP+Ajax Since 2006

My Blog

Here is my awesome blog. You can find information on programming, linux, documentation, tips for code and database optimization, my thoughts and rants, and whatever else I feel like sharing. Feel free to contribute to the blog by posting comments and asking questions.

Archive for 2007

using JSON to pass JavaScript arrays to PHP via Ajax

Posted by chris on November 26th, 2007 Comment(1)

We don’t use PHP 5.x at work so I needed to install JSON via PEAR. In your PHP script include the JSON.php file and instaniate the object.

1
2
include_once('JSON.php')
$json = new Services_JSON();

In your javascript include a reference to json.js minus the comment marks:

1
(<)script src="json.js" type="text/javascript"(>)(<)/script(>)

Now create a simple javascript method that will perform an HTTP GET and pass an array broken down into JSON to your PHP script:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
	function testJSON()
	{
		var testArr = new Array();
		testArr[0] = 0;
		testArr[1] = 1;
		testArr[2] = 2;
		testArr[3] = 3;
		testArr[4] = 4;
		var testJSONArr = testArr.toJSONString();
		var url = "mypage.php?func=testJSON&jsonArr=" + testJSONArr;
		if(XMLHttpRequestObject)
		{
			XMLHttpRequestObject.open("GET", url, true);
			XMLHttpRequestObject.onreadystatechange = function()
			{
				if (XMLHttpRequestObject.readyState == 4 && XMLHttpRequestObject.status == 200)
				{
					try
					{
						var txtDocument = XMLHttpRequestObject.responseText;
						txt.innerHTML = txtDocument;
					}
					catch(err)
					{
						txt.innerHTML = "Description not found.";
					}
				}
			}
			XMLHttpRequestObject.send(null);
		}
	}

At the top of mypage.php you should have this:

1
2
3
4
5
6
7
	switch ($_GET[func])
	{
		case 'testJSON':
			echo $myPHPObj->testJSON(urlencode($_GET[jsonArr]));
			break;
	}
	return;

Your PHP object will have a method in it like this:

1
2
3
4
5
6
7
8
9
	function testJSON($jsonArr)
	{
		$json = new Services_JSON();
		$jsonArr = $json->decode(urldecode($jsonArr));
		foreach($jsonArr as $element)
		{
			echo "js array element: $element<br/>"; 
		}
	}

Thats it. My first use of JSON. I was really getting tired of packing data in long strings with strange explode points and felt XML was to bloated for what I was doing.

In JavaScript and Ajax, Programming ()

MySQL Case Statement

Posted by chris on November 8th, 2007 Comments(0)

The database I was working on the other day is FAR from normalized. It stores shipping types as regular VARCHAR strings. We needed to orderby Overnight and International orders so they print first in the batch. Using a case statement I was able to create a temporary sane column in this query, using the integer values in this temporary shipType column I was then easily able to orderby and it only added 1/10 of a second to the query’s execution time. Here is an example of the MySQL case statement:

				CASE SUBSTRING_INDEX( shipping, '|', 1 )
				     WHEN 'Overnight' THEN 1
				     WHEN 'Overnight Delivery' THEN 2
				     WHEN 'International' THEN 3
				     WHEN 'USPS International Shipping' THEN 4
				     WHEN '' THEN 5
				     WHEN ' * Product(s) qualify for Free shipping * ' THEN 6
				     ELSE SUBSTRING_INDEX( shipping, '|', 1 )
				    END AS shipType 
In SQL ()

Querying MS SQL database looking for a specific column

Posted by chris on November 2nd, 2007 Comments(0)

At work we interact with a MS SQL server that our shipping software runs on. We are a MySQL shop so don’t use MS SQL too much and the database in this proprietary shipping system is pretty large (about 100 tables). I needed to find a table that another table had a relation too and only knew the column name. So I ran this

SELECT name FROM sysobjects WHERE id IN ( SELECT id FROM syscolumns WHERE name = ‘Alias_ID’ )

in MS SQL 2000 Query Analyzer and returned a list of 6 tables.

A lot better to troll through 6 tables than 100 tables.

In SQL ()

Mod-Log-SQL – Storing Apache Access Logs in a MySql Database

Posted by chris on October 27th, 2007 Comments(0)

Mod log sql is an awesome way of getting away from those old log files and is really handy for both web development and system administration. It’s been a while since I’ve posted a blog and this is something I’ve never done before so here we go. If you are ever doing any kind of parsing of your apache access log and run a relatively high traffic website (the one I’m doing this for, mp3crib.com, averages over 5,000 hits a day and some days gets over 10,000) you will begin eating up huge amounts of CPU and memory (if storing the information in an array). Well lately it’s gotten so bad that my PHP script fails due to memory exhaustion. I can’t have that. I heard somewhere that databases are better than flat files, go figure. If I knew a lower level language then I would of course write my parser in that…but I don’t. So luckily libapache2-mod-log-sql exists.
Read the rest of this entry »

In Linux, SQL (, , , )

More JavaScript Array Methods (push and join)

Posted by chris on September 25th, 2007 Comments(0)

I found some other badly needed javascript methods today. Push (similiar to PHPs array_push function) and Join, which converts a simple array into a string. The Join method is great if you want to pass a dumb string to a server side language using an HTTP GET or POST.

Push

/* this can be defined as a global variable and then accessed by many different functions */
var myArr = new Array();
myArr.push("another element");

This simply adds another element to the end of the array.

Join

var myArr = new Array();
myArr[0] = "element 1";
myArr[1] = "element 2";
myArr[2] = "element 3";
var myStr = myArr.join(', ');

Now you have converted an array into a comma seperated string.

In JavaScript and Ajax ()

JavaScript forEach

Posted by chris on September 25th, 2007 Comments(0)

I’m used to using PHPs foreach function to iterate through an array. I finally found support for this in javascript the other day. Here is an example of its use.

var myArr = new Array();
myArr[0] = "element 1";
myArr[1] = "element 2";
myArr[2] = "element 3";
myArr.forEach(yell);
function yell(element, index, array)
{
	alert(index+' '+element);
}

This will alert each key in the array and its associated element. Obviously you can do a lot more with this.

In JavaScript and Ajax ()

HTTP POST via AJAX HTTP Request Object

Posted by chris on September 6th, 2007 Comments(0)

Doing an HTTP POST has several advantages over an HTTP GET. For one, a GET is limited to 2000 characters, it can’t really send XML formatted data, and it’s not as secure as a POST. Though a POST isn’t too secure either unless sent over HTTPS. The first thing you will want, especially if you have multiple JavaScript functions performing HTTP POSTS is the following function:

	function httpPost(url, params, stateChangeFunc)
	{
		/* HTTP POST to be passed to PHP method via http request */
		if(XMLHttpRequestObject)
		{
			XMLHttpRequestObject.onreadystatechange = stateChangeFunc;
			XMLHttpRequestObject.open("POST", url, true);
			XMLHttpRequestObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			XMLHttpRequestObject.setRequestHeader("Content-length", params.length);
			XMLHttpRequestObject.setRequestHeader("Connection", "close");
			XMLHttpRequestObject.send(params);
		}
	}

You would call this function like this:

		var params = 'strArr=' + escape(encodeURI(strArr));
		/* call httPost function to make request */
		httpPost('mypage.php', params, showOrderConfirmation);

The first parameter in the httpPost function is the page that you would like to POST the data too. I suggest posting it to the exact same page as where it came from, and having server side code at the top of the page that will handle the post. I use a pretty nice design pattern for my ajax, that I may have mentioned in a previous article, if not I’ll have to blog it some time. The second parameter is well your parameters, the actually post elements. Each post element must be in this format “name=” + escape(encodeURI(strArr)). The JavaScript function’s that encapsulates the variable you are sending is very important. Remember, for multiple post elements, you must include an ‘&‘ as a separator. The third and final parameter is the javascript function you would like called on completion of the post. This function typically formats the data that your server-side code echoed to the page.

Your server-side code would then have to know exactly what to do with this.

In JavaScript and Ajax ()

rsync debian linux

Posted by chris on August 10th, 2007 Comment(1)

Install rsync on the server you want to backup apt-get install rsync

To backup the entire server create a cron job with the following command in it (you can choose how often you'd like it to run yourself if you know how the time syntax in a cronjob, otherwise search the blog for information on crontab):

rsync -a -e ssh / username@10.10.10.10:/path/to/destination/

Since you will be doing this over SSH you will be prompted for a password, but we can't really enter in a password if this is a cronjob. So on the source system and source user that the cron job will run as enter in the following command and when it asks for a password leave it blank, take the default file location:

ssh-keygen -t rsa

Do the same thing on the destination system, but remember to run the command as the user who will be logging in via SSH for the rsync conrjob.

Open ~/.ssh/id_rsa.pub on the source system and create a new file on the destination system called /home/username/.ssh/authorized_keys, copy the line in the id_rsa.pub to the authorized_keys files. Verify you can SSH into destination system from the source system.

This has just made your backup server pretty insecure, but since it is just a backup server you can restrict who can log into the system via SSH to the source computer.

In Linux ()

Doing Math in JavaScript umm…sucks

Posted by chris on August 10th, 2007 Comments(0)

So I’ve been writing a new point of sale page for use by our customer service reps in accepting orders by phone. It will be replacing a very old, ugly, slow, and inefficient strictly php/html web application with one which is heavy javascript/ajax/dom, css, html, and php. I noticed when working on a point of sale page for another department months ago that javascript was a pain in the ass when doing math based on values stored inside form fields.

Javascript views everything stored in a form field as a string. Which is very different for me because I’m use to the PHP model where it doesn’t classify variables as strings or integers, it just knows when to do math based on the operator you use. Now there are a few tricks I’ve come up with on my own, and a few I found googling to work around these nuances. I’d love some feedback and additional work-arounds from anyone who reads this though.

Here we go:
Read the rest of this entry »

In JavaScript and Ajax (, , )

looping through form fields in javascript

Posted by chris on August 2nd, 2007 Comments(0)

I needed to loop through a bunch of form fields in javascript, serialize them into a string, and then pass them to a PHP script for further manipulation. Here’s an easy way to loop through form fields that I found on the google:

for(i=0; i

Here's what my code ended up looking like:

var strArr = "";
for(i=0; i(<)document.posfrm.elements.length; i++)
{
	strArr += document.posfrm.elements[i].name + '*' + document.posfrm.elements[i].value + '|';
}
In JavaScript and Ajax ()