Thursday, April 24, 2008

AJAX: Online-Editor

in today's article i would like to introduce the reader to the AJAX: Online-Editor which i mentioned in yesterday's post referring to the book Praxiswissen Ajax.

since the book and the source code are in german i translated it (hopefully all of it) into english and made it available for download at http://www.downintheflood.com/download/ajax-online-editor.zip

you can see it also online at: http://www.downintheflood.com/source/ajax/

however, in order to avoid people entering or deleting any code or files, or adding files with content that i wouldn't want there i have removed the [New File]   [Save File]   [Save As ...]   [Delete File] buttons from my online application. furthermore i have set the textarea field on the right to readonly. just the [update] button works.

but i won't leave you that much in the dark here, i have created a few screenshots so you can roughly see what it looks like. if you are going to use it online you should, however, keep the folder contents in a password protected area where those users whom you'd grant access to the application will have the liberty to create, alter or delete files.

the first screen shot shows the layout of the page as it comes up on the screen the first time, that is, when you load the index.html into your browser (the application requires PHP4).



once you have clicked on a file name on the left side of the screen, the content of that file shows up in the textarea element on the right side of the screen as seen below:



if you want to delete a file an alert message asks you if you really want to delete this file:



if you confirm the O.K. the contents will be removed from the screen, the file will be removed from the file list on the left and a message appears in the status bar at the bottom of the editor that the file has been deleted:



with the last screenshot i wanted to display the error message that comes up when the client (browser) is unable to load the list from the server. the browsers behave differently, Firefox pops up an alert window while Internet Explorer will show the yellow warning triangle on the bottom left of the screen. here is the screenshot with the blank editor unable to load the files:



i changed the layout somewhat from the original layout. the original is smaller. i also changed the color setting of the original layout. if you want to use the smaller version you can download the stylesheet at this link.

now i hope you'll enjoy this little toy and learn about AJAX by studying the code in greater detail and using it perhaps in other applications.

until then.

tom.paine

Wednesday, April 23, 2008

JavaScript ... PHP Array sorting plus ...

after i've spent several hours last sunday always battling to insert the code snippets into this blog without having a special facility to show code content i decided to upload one of the old source viewer scripts that i had in my archive and use links to the source viewer in future to highlight the code examples ... unless they are less complex.

in today's article i would like to take a brief look at JavaScript examples as well as the various effects of sorting an array with php.

let me start with the php examples, because they are all ready for take off:
the results of this source code can be seen here: http://www.downintheflood.com/source/examples.php5.

at the top you see the example array and below you see the various sort functions to sort the array forwards and backwards and by key forwards and backwards or naturally.

there is another issue i worked on today: one of my bigger projects involves the capturing of the Song Set Lists to all the Bob Dylan Concerts into a MySql Database. i got all the information from PDF files from another site and just needed to copy the set lists into text files for later use, when i want to insert them with the help of php (hopefully) somewhat speedily and automatically into the database.

but to capture them first i had the option of copying and pasting into a text file and save each one using Save As, but i found that to tedious after a while and was scared to make mistakes, which is what happens quickly when you have to perform a repititive function.

i got this book (here he comes with his books again) Praxiswissen Ajax



and in this book there is a chapter about an Ajax Online Editor (short: aoe). i have somewhat re-designed the layout a little to fill the whole screen with it for my purposes. (i will discuss this example in another article.) this editor uses php to read the files of a particular directory on the left part of the screen; one clicks on a filename and the contents of the file appear on the right side of the screen.

i show you a screenshot:



now i wanted all the files to exist already so i wrote myself a little code snippet that would write empty files with the names ready-made from an array in split seconds. and here is the code (the filenames just have reference numbers):


<?php
$id_number = array(
'29930',
'29940',
'29950',
'29960',
'29970',
'29980',
'29990',
'30000',
'30010',
'30020',
'30030',
'30040',
'30050',
'30060',
'30070',
'30080',
);
$inhalt = utf8_encode(" ");
foreach($id_number as $value) {
$filename = $value.".txt";
$fh = fopen($filename, "w+");
fwrite($fh,$inhalt);
fclose($fh);
}
?>


this code snippet enters a blank space (" ") into each of those files.

my next problem came when i wanted to copy those files as a backup from the server, where i will need them, to my computer. as i came back from having a shower an error message awaited me that the server had been reset and the copying had not been completed. so i thought alright, let me create a zip file and download them as a zip file. using the google search engine again i went to look for create zip files using php. i downloaded 4 examples, the last one was in php5 and i decided to try that one first and it didn't work for some reason, so i discarded that one already. then i tested the third one which looked best and easiest for me. it requires PEAR but that wasn't a big problem either. it further requires the PEAR Archive_ZIP Package.

downloaded those, unpacked and copied them to the server. then i got the code working which i took from PHPit. i made a few adjustments to it, like the path to pear and of it went. here is the code snippet i used:


<?php
// Original Source: http://www.phpit.net/article/creating-zip-tar-archives-dynamically-php/
include ('../pear/archive_zip.php');

// Create instance of Archive_Zip class, and pass the name of our zipfile
$zipfile = New Archive_Zip('bdcdb.zip');

// Create a list of files and directories
$list = array(
'00003.txt',
'00005.txt',
'00007.txt',
'......txt',
);

// Create the zip file
$zipfile->create($list);

echo 'Zip file created';
?>


of course my list has over 3.000 items, so the $list array is accordingly much longer. i waited a few seconds and then i was able to download my text files in a zip folder named bdcdb which stands for Bob Dylan Concert Data Base.

End of Project.

now for the JavaScript.

i think it's best to create a JavaScript file (i have JavaScript snippets all over my pages as well as in files). and here is an example.

the first example you can see working on the source.php file if you click into the field with the url. it clears the text in that field.

the second example you can use with a URL like
<a href="http://someurl.com" onClick="MyWindow(this.href,'name','1000','650','yes');return false">some url</a>
. it opens the link in a new window at the size of 1000x650.

the third example uses a copy and paste button (also to be seen at the lower section of the source.php file). in Firefox it only highlights the code, but using the Internet Explorer it actually puts the code into the copy and paste cache. i have explained the usage of that code already on the source.php page.

the fourth example you can use with the <select> tag of a drop-down menu as shown in the example in the source.php file.

for all these examples to work you only need one line of code in the <head> section of your .html or .php file, and that is:
<script language="JavaScript" type="text/javascript" src="javascript.code.lib.js"></script>. of course your JavaScript file's name is javascript.code.lib.js :-)

another book i'm learning from at the moment is PHP und MySQL -- Dynamik für Ihre Webseiten



one thing i learnt from it is if i want to use a variable within html and i'm just outside of the php parameters i can use <?=$color;?> instead of <?php echo $color; ?> as i used to in the past.

and that rounds off today's article on code snippets. stay tuned and see you soon.

tom.paine

Sunday, April 20, 2008

Amazon Web Services (AWS)

it's been recommended to me by some friends to start a blog on code snippets since i'm not just into music and literature, but also spend a considerable amount of time on the computer trying to figure out how i can make a script work that i've seen somewhere or whatever the case may be. i guess first i gotta go through a short and sweet amount of history on how i teach myself:

when i started off in 2001 someone showed me how to figure out the source code by clicking view --> view source code on the Netscape 4.7 browser at the time. first i created mostly pages with links of websites i liked and which i'd visit regularly, but which could also be of interested to others on a particular subject. in one such case i created a webpage for a friend of mine and she asked me to insert the right-click JavaScript.

<script language="JavaScript" type="text/javascript">
<!--
var message="You can't have this, but you can print it out or contact us for 
permission to borrow something. Have a great day and thanks for visiting us!";

function click(e) {
if (document.all) {
if (event.button == 2) {
alert(message);
return false;
}
}

if (document.layers) {
if (e.which == 3) {
alert(message);
return false;
}
}
}
if (document.layers) {

document.captureEvents(Event.MOUSEDOWN);
}
document.onmousedown=click;
//-->
</script>

that was the code i used in my page; i found that code snippet on the internet; she used a different code at the time and i noticed it wasn't working in Netscape, so i asked "what code are you talking about?" well, and that's how i got started using JavaScript.

in one of my more complicated examples i created a page with 4 framesets, whereby if one moves the cursor over a link to a music album, the album cover changes accordingly in the other frame. that was a nightmare which took me about 8 hours to resolve. here again i searched around on the internet to find a suitable code snippet.

<frameset cols="313,*" border="0" framespacing="0" frameborder="0">
<frameset rows="434,*" border="0" framespacing="0" frameborder="0">
<frame src="AppleBobDylan.html" scrolling="auto" name="Think different.">
<frame src="DylanAlbumImages.html"  scrolling="auto" name="DylanAlbumImages">
</frameset>
<frameset rows="9%,*" border="0" framespacing="0" frameborder="0">
<frame src="DylanAlbumHeader.html" scrolling="auto" name="DylanAlbumHeader">
<frame src="DylanAlbumLinks.html" scrolling="auto" name="DylanAlbumLinks">
</frameset>
</frameset>
<noframes>
<body>
</body>
</noframes>


the code snippet that would have to be used with the link would be:


onmouseover="parent.DylanAlbumImages.document.albumcover.src='CURRENT_COVER.jpg'"
onmouseout="parent.DylanAlbumImages.document.albumcover.src='DEFAULT_IMAGE.jpg'"


CURRENT_COVER is here only sort of a variable for the image related to the current cover. those have been preloaded at the head of the script in the .html file that contains the links.

but what am i writing about? you thought this article would be about Amazon Web Services; well it is, we're slowly getting there.

before i get into that i should mention a few books that may be essential to the cause:


Programming PHP


Web Database Applications with PHP & MySQL


Learning Perl


Programming Perl


and of course my main guide: the AWS Book titled: The Web Developer's Guide To Amazon E-Commerce Service: Developing Web Applications Using Amazon Web Services And PHP

this last book not only helps you to learn php but also apply it already in reallife applications. example scripts can be seen as well as downloaded from www.awsbook.com.

i could go more into details about books, Ajax Hacks, Amazon Hacks (now somewhat outdated due to the termination of Amazon Web Services 3.0) and Google Hacks or any other from the Hacks series.

enough of this! now let me give an example of how i sometimes work. you can find already lots of usable code related to Amazon Web Services on the internet, you don't have to write your own. but you should at least have a fundamental knowledge of how Amazon Web Services works:

Step 1: you formulate your request url
Step 2: you send that request to Amazon's server (using your browser)
Step 3: Amazon returns a document with a XML structure related to your request, if neccessary with an error message which tells you what parameter was wrong.
Step 4: you write some kind of script that can turn the XML document into something more sensible to the visitors of your website.

the start of your url will always look like this:
http://ecs.amazonaws.com/onca/xml?Service=AWSECommerceService&AWSAccessKeyId=[YOUR ID]
http://ecs.amazonaws.co.uk/onca/xml?Service=AWSECommerceService&AWSAccessKeyId=[YOUR ID]
http://ecs.amazonaws.ca/onca/xml?Service=AWSECommerceService&AWSAccessKeyId=[YOUR ID]
http://ecs.amazonaws.de/onca/xml?Service=AWSECommerceService&AWSAccessKeyId=[YOUR ID]
http://ecs.amazonaws.fr/onca/xml?Service=AWSECommerceService&AWSAccessKeyId=[YOUR ID]
http://ecs.amazonaws.jp/onca/xml?Service=AWSECommerceService&AWSAccessKeyId=[YOUR ID]

you obtain the AWSAccessKeyId from Amazon and it's the same for all these locales.

next you need an Operation (no no, don't panik, not at the hospital! you should remember that these terms are case-sensitive!) for instance Operation=ItemSearch. you find those in the documentation from Amazon. i don't want to get into those details too much here.

certain Operations (like ItemSearch) require certain parameters that are a must. in this case for instance a SearchIndex is required. a SearchIndex is something like Books, DVD or VHS. the SearchIndex values vary from country to country (locale to locale); for instance, MusicalInstruments you get only under the US locale whereas Hobbies you will only find under the JP locale (for Japan). apropos Japan: i did not make a mistake with the url above, it is .jp and not .co.jp in this case.

now what are we searching for? one can search for a particular Author under Books, or Artist under Music, Actor or Director among DVD and VHS. the simplest would be the Keywords search (one can also use a BrowseNode, but who knows those offhand?).

we're almost there. we could add a Sort parameter or even which Version of Amazon Web Services we'd prefer to use in our request, but those will be returned as default parameters and we don't have to worry about that for now.

i almost forgot about the ResponseGroup: the information you're about to get depends on the ResponseGroup, Small, Medium or Large are the basic ones.

we got everything? let's give it a try, shall we?

http://ecs.amazonaws.com/onca/xml?Service=AWSECommerceService&AWSAccessKeyId=[where's your id?]&Operation=ItemSearch&SearchIndex=Books&Keywords=Bob%20Dylan&ResponseGroup=Large

O.K. that work's after a number of false starts (i hate links that don't work!)

now that we've had the basics i will show an example i found on the internet and changed it to suit my own purposes. nothing spectacular!

i found this code snippet in the Ajax Community:


<?php
class aws {
    function 
aws($aki$asin) {
        
$fs=fopen("http://ecs.amazonaws.de/onca/xml?Service=AWSECommerceService&AWSAccessKeyId="$aki ."&AssociateTag=22&Version=2006-09-11&Operation=ItemLookup&ItemId="$asin ."&ResponseGroup=Medium,Offers","r");                
        
$this->responseXML=simplexml_load_string(fgets($fs));
    }
    
    function 
getValue($pValue) {    
        
$myValue '';
        eval (  
'$myValue = $this->responseXML->'.$pValue.';' );
        if(empty(
$myValue)) $myValue='n.V.' ;                            
        return 
$myValue;
    }
}

$produkt = new aws('AccessKeyId''Produkt ASIN');
$preis =  $produkt->getValue('Items->Item->Offers->Offer->OfferListing->Price->FormattedPrice');
$bild  =  $produkt->getValue('Items->Item->LargeImage->URL');

echo 
'<img src="'.$bild.'" />';
echo 
'Preis: '$preis;
?>


and this is what i made of it:

<?php
class aws {
function 
aws($aki$affid$asin) {
        
$aki '1BZ9VRA5AKNBPYJM6YR2';
        
$affid 'downinthefl04-21';
        
$asin '3100744314';
        
$fs=fopen("http://ecs.amazonaws.de/onca/xml?Service=AWSECommerceService&AWSAccessKeyId="$aki ."&AssociateTag="$affid ."&Version=2006-09-11&Operation=ItemLookup&ItemId="$asin ."&ResponseGroup=Medium,Offers","r");                
        
$this->responseXML=simplexml_load_string(fgets($fs));
    }
    
    function 
getValue($pValue) {    
        
$myValue '';
        eval (  
'$myValue = $this->responseXML->'.$pValue.';' );
        if(empty(
$myValue)) $myValue='n.V.' ;                            
        return 
$myValue;
    }
}

$produkt = new aws('AccessKeyId''AffiliateId''Produkt ASIN');
$preis =  $produkt->getValue('Items->Item->Offers->Offer->OfferListing->Price->FormattedPrice');
$bild  =  $produkt->getValue('Items->Item->LargeImage->URL');
$link  =  $produkt->getValue('Items->Item->DetailPageURL');
$titel =  $produkt->getValue('Items->Item->ItemAttributes->Title');
echo 
'<img src="'.$bild.'" /><br />'."\n";
echo 
'<a href="'.$link.'" target="new">'.$titel.'</a><br />'."\n";
echo 
'<a href="http://ecs.amazonaws.de/onca/xml?Service=AWSECommerceService&AWSAccessKeyId=1BZ9VRA5AKNBPYJM6YR2&AssociateTag=downinthefl04-21&Version=2006-09-11&Operation=ItemLookup&ItemId=3100744314&ResponseGroup=Medium,Offers" target="new">XML Dokument</a><br />'."\n";
echo 
'Preis: 'str_replace('EUR','&#128;',$preis);
?>


i added my affiliate id and i display a link below the large image, as well as a link to the request i made. i always do this as an easy reference in case nothing shows up. the script is written in php5 which you can easily recognize by the use of the simplexml_load_string function.

writing this all up has now taken me a considerable amount of time; so i'm gonna knock off with a last link to the PHP: Documentation where the reader will find the simplexml_load_string as well as the simplexml_load_file functions explained in greater detail together with examples from other users. for some resource links on Amazon Web Services you can also visit my documentary.

Cheers for now!

tom.paine