Web Programming

Top1 Beispiele und Links zum Nachschlagen

Nachschlagen Beispiele

Top2 Tipps für das Erstellen / Aktualisieren dieser WebPage

Top2.1 Beispiel für eingebetteten Code-Abschnitt (<code>)

Das ist Text mit eingebettetem Quellcode (<code>). Ab hier wieder normaler Text;

Top2.2 Beispiel für mehrzeiligen Code-Abschnitt (<pre>)

Das ist normaler Text.
Das ist 
  vorformatierter Text
mit beliebigen Zeilenumbrüchen

Leerzeilen
  und Einschüben    und Lücken.
Der vorformatierte Text kann auch markierten Text enthalten.

Spitze Klammern können über selbstdefinierte Steuerzeichen
#lt# bzw #gt# definiert werden, also z.B. so:

<Inhalt der Klammer>
Hier geht wieder der normale Text weiter.

Top2.3 Beispiel für mehrzeiligen Output-Abschnitt (<pre class="Output">)

Das ist normaler Text.
Das ist generierter Output!
Hier kann auch markierter Text enthalten sein.
Hier geht wieder der normale Text weiter.

Top2.4 Beispiel für mehrzeilige Merkregel (<div class="Rule">)

Das ist normaler Text.
Hier steht eine wichtige Merkregel!
Hier kann auch markierter Text enthalten sein.
Hier geht wieder der normale Text weiter.

Top2.5 Selbstdefinierte Steuerzeichen

Motivationen zur Definition eigener Steuerzeichen:
  • Templateklammern im Beispielcode müssen speziell codiert werden, um sie von HTML-Tags unterscheiden zu können (das geht natürlich auch über &lt; und &gt;)
  • andererseits sollen kurze Anweisungen ausreichen, um andere Formate (z.B. farbliche Markierung) einfach zuordnen zu können (mit html müssten längere Konstrukte eingegeben werden)
  • Zusatzfunktionen, wie z.B. Stichwortdefinition und Generierung Stichwortverzeichnis muss über Auswertealgorithmus einfach realisierbar sein
  • Verwendung des Symbols # um die Steuerzeichen leichter vom regulären Text unterscheiden zu können
selbstdefinierte Steuerzeichen Beispiel/Anwendung
#lt# Text #gt# < Text in spitzen Klammern >
#-t# Text #t-# < Text in spitzen (Template-)Klammern >
#-m# Text #m-# markierter Text
#-todo# Text #todo-# markierter Text für TODO
#-b# Text #b-# fett (bold)
#-k#IrgendeinStichwort#k-#
#-k#Irgendein--Stichwort--mit--Blanks#k-#
Einträge im Stichwortverzeichnis:
IrgendeinStichwort
Irgenden Stichwort mit Blanks
Unterstützung für ergänzende Meta-Informationen (Zwischenüberschrift h6)
Am Anfang eines Textes können in speziellem Format Meta-Informationen für den HTML-Header definiert werden. Der an den Client gesendete HTML-Header enthält neben diesen spezifischen und optionalen Angaben noch weitere Einträge, die für alle Textseiten gleich sind.

Beispiel:

#-HeaderInfo#
#-PageTitle#Windows-Apps/Tools#PageTitle-#
#-Keywords#MS Windows, apps, applications, developper tools#Keywords-#
#-Description#Hinweise zu Konfiguration und Einsatz ausgewählter Windows-
  Applikationen: FreeCommander, Outlook, Enterprise Architect#Description-#
#HeaderInfo-#

Top2.6 Menus ausblenden

Menus können manuell ausgeblendet werden durch manuelle Erweiterung der http-Zeile um &menu=OFF

Top2.7 Drucken als PDF

  • Nicht mit FireFox, hat Propleme mit PDF-Generatoren
  • Menus manuell ausblenden mit Erweiterung der http-Zeile um: &menu=OFF
  • zusätzlich noch Hintergrundfarbe deaktivieren: &bgcolor=OFF
  • Drucken der Hintergrundfarben und -bilder abschalten (in Internet-Explorer unter Extras /Internetoptionen /Erweitert, dann letzter Punkt in Liste + zusätzlich in Menu Datei/ "Seite einrichten...")
  • Wenn doch benötigt (z.B. für Kalenderdruck), dann an beiden Stellen wieder aktivieren
  • Um relativ schmale PDF-Dokumente zu erhalten (z.B. zur Anzeige auf eBook-Readern) sollte der rechte Rand entsprechend vergrößert werden, z.B. auf 600mm (Menu Datei/"Seite einrichten")

Top3 Das CSS Boxmodell

Außenabstand (margin)
Einbettung in das Elternelement
Rahmen (border)
Innenabstand (padding)
Elementinhalt

Das CSS Boxmodell betrachtet jedes Element als rechteckige Einheit mit einem bestimmten Anordnungsverhalten

Sichtbare Elementbreite = angegebene Elementbreite (width) + Innenabstand (padding) auf beiden Seiten + Rahmenbreite (border) auf beiden Seiten.

  • html-Box
    Das html-Element hat kein übergeordnetes Elternelement. Es füllt das ganze Browserfenster bis zum Rand. Der untere Rahmen ist jedoch abhängig vom Inhalt.
  • body-Box
    Das body-Element ist ein Kind-Element des html-Elementes. Es erhält jedoch einen Default-Abstand zum html-Element.
  • Allgemeine Grundregeln
    Block-Elemente sind so breit wie möglich, so hoch wie nötig.
    Inline-Elemente sind so breit wie nötig, so hoch wie nötig.
    Die meisten Elemente erhalten vom Browser Defaultwerte für Aussenabstand, Rahmen und Innenabstand. Elemente vom Typ div erhalten als Standard 0-Werte!
  • Kollabierungsprinzip
    Für Blockelemente im Fließtext wird das Maximum der vertikalen Abstände gebildet (nicht die Summe)

Top4 Schraffierter Hintergrund

Um einen farbigen Hintergrund mit einer Schraffur zu versehen, kann man ihn mit einem teilweise transparenten Bild überlagern, in dem beliebige Schraffurlinien enthalten sind. Da Hintergrundbilder in der Anzeige wiederholt werden können, ist es dabei in der Regel ausreichend ein entsprechendes Bild von wenigen Pixel Größe zu erstellen, das dann auf HTML-Objekte beliebiger Größe angewendet werden kann:

Top4.1 CSS-Formatierung:

background-image:url(site/layout/shading_v.png); background-repeat:repeat;

Top4.2 Beispiele:

Schwarze Linien
(shading_v.png)
Weisse Linien
(shading_v_w.png)
Schwarz-Weisse Linien
(shading_v_bw.png)

Top4.3 Erstellung einer transparenten Pixel-Grafik:

Bedienablauf unter GIMP (GNU Image Manipulation Programm (free SW))
  • Neues Bild erstellen
    • (Menu Datei / Neu)
    • Abmessungen eingeben, z.B. für vertikale Schraffur Breite 5 Pixel, Höhe 1 Pixel
    • Erweiterte Einstellungen: Füllung "Transparenz"
  • Sichtbare Pixel setzen
    • Vergrößerungsfaktor auf 800% setzen
    • Pinsel mit Größe "Circle (01)" setzen
    • ggf. Farbe setzen über Farbefeld im "Werkzeugkasten"
    • Anwenden des Pinsels, z.B. auf letzen Pixel rechts
  • Bild als PNG abspeichern
    • Datei / Speichern unter
    • "Dateityp nach Endung": Auswahl PNG
    • OK
    • Defaultwerte belassen: "Hintergrundfarbe speichern", "Farbwerte aus Transparenz speichern"
    • Speichern

Top5 Javascript

Top5.1 Your own data struct (object)

A data struct can be defined with use of a creator function. The function's name represents the name of the data struct. The following code defines a data struct of type "Item":
// Constructor with optional params
function Item (desc, optCategory, optCount, optDone)
{
    // Verify existence of mandatory params
    if (typeof desc === "undefined") {alert("Item: desc is missing");}

    // Support for default params
    if (typeof optCategory === "undefined") {optCategory = 'default';}
    if (typeof optCount    === "undefined") {optCount    = '0';}
    if (typeof optDone     === "undefined") {optDone     = 'false';}

    // Define and set attributes
    this.desc     = desc;
    this.category = optCategory;
    this.count    = optCount;
    this.done     = optDone;
}
Using your new object type requires instantiation with "new":
myItem = new Item ("Homepage Design", "programming book");

// Access data members
if (myItem.category == "programming book")
{
    ++myItem.count;
}

Top5.2 Array of objects

An empty array has to be instantiated via "new". Elements can be added at the end or inserted at specific positions:
// Define an array (of items)
var myItems = new Array();

// Add an item at the end of the array
myItems.push (new Item ("Windows"));

// Insert an item after a specific index position
myItems.splice (someIdx+1,0,new Item ("Linux"));

// Remark: second param "0" within splice says "delete 0 elements,
// do only a insert"
The array is zero based (0 .. length-1) and allows simple iteration:
for (var i = 0; i < myItems.length; ++i)
{
    // access attribute of ith element
    myItems[i].done = true;
}

Top5.3 Message boxes (alert, confirm)

To give the user a simple response, you can display a textual message:

javascript alert dialog

Source code:
... // some calculations
result = 42;

alert ("The final result to all your questions is: " + result");

... // proceed or terminate

Before executing an important and possibly irreversible action the user can be asked for confirmation:

javascript confirm dialog

Source code:
if (confirm("Do you really want to delete all your mp3 files?"))
{
    // delete the files, user has pushed 'ok'
}
else
{
    // do nothing, user has pushed 'cancel'
}

Top5.4 Controlling submit of html forms

On a typical web page there is often a form with data fields and possibly several submit buttons. By pushing one of the submit buttons both the type of the selected button and the data fields are sent to the web server. In some cases you may first want to make some checks on the client side or perhaps ask the user for confirmation before the data are really sent over the internet.

These checks can be performed with use of javascript:

First you have to define a check function within your form tag's attribute "onSubmit". The form will now ask the check function when any of the submit buttons is pushed. The form will be submitted only in the case where the check function returns true otherwise nothing is sent.

If you want to make specific decisions depending on the kind of the pushed submit button, you can store the name of the button in the moment of pushing within a global javascript variable which is available within your check function.

HTML code:
<form onSubmit='return IsSubmitAllowed()' action='SomeWebAddress.php'>

...// some edit fields or other form elements

<input type='submit' value='Save'
    onMouseUp='javascript: submitButtonPushed="save"'>
<input type='submit' value='Delete'
    onMouseUp='javascript: submitButtonPushed="delete"'>

</form>
Javascript code:
// global variable
var submitButtonPushed="";

function IsSubmitAllowed()
{
    if (submitButtonPushed == 'delete')
    {
        // Ask the user if remove action shall be
        // started on the remote server
        return confirm("Do you really want to remove all items?");
    }
    
    // all other buttons (e.g. save) execute without confirm
    return true;
}

Top5.5 Make arbitrary text clickable (<span> + onClick)

It is possible to program a specific reaction when the user clicks on an arbitrary text on your web page:

First you have to embed the text area which should become reactive within a specifc HTML tag, e.g. <span>. The advantage of using <span> is mainly that there will be no visible changes visible to the user.

Within this tag you have to define an event handler reacting on the click event. You can also provide arbitrary parameters to your click handler which you can use for identifying the type of clicked text.

HTML code
Here is some passive text, but <span onClick='OnClickedText(1)'>here it will
become reactive</span>.

From here on there will no reaction on mouse clicking. Here is another small <span onClick='OnClickedText(2)'>hot</span> spot.

Javascript code
function OnClickedText(id)
{
   if (id == 1)
   {
       // e.g. select a check box
   }
   else if (id == 2)
   {
       // e.g. open a message box
   }
}
Usage in real world:
When presenting several choices to the user with the use of check boxes, the user has to click the check box e.g. with the mouse. The label text near the text box is not reactive when clicking on it. On a desktop computer with a mouse device there is no problem to select the relatively small check box. But when using the page on a mobile device you must have tricky fingers to hit the right spot.

To rise the probability for simple and correct selection you could make the label text reactive. The event handler could programmatically select the checkbox. From the user's point of view he now can click both on the box and the text having the same reaction.

Top5.6 Viewing/debugging a generated web page

When a web page containing javascript is sent to the browser then there are two realities:
  • server generated page:
    The page contents as received from the server. The browser has not yet executed the javascript and you can read your javascript functions.
    <html>
      <head>
        <title>My Web Page</title>
        <script language="JavaScript" src="my_functions.js"
             type="text/javascript"t-#</script>
      </head>
      <body>
        <script language="JavaScript" type="text/javascript">
    <!--
    // Call javascript function to generate web page
    GenerateMyPageContents();
    // -->
        </script>
      </body>
    </html>
    
  • client generated page:
    The page as presented to the user. The browser has already executed the javascript code and you can view the html code which may be (partially) generated by your java scripts. The script code itself is invisible.
    <html>
      <head>
        <title>My Web Page</title>
        <script language="JavaScript" src="my_functions.js"
             type="text/javascript"t-#</script>
      </head>
      <body>
        <script language="JavaScript" type="text/javascript">
    <!--
    // Call javascript function to generate web page
    GenerateMyPageContents();
    // -->
        </script>
    
    
    This is the story of my life. I want to tell you about:
    <p>
    <ul>
      <li>The place where I was born
      <li>The schools I have visited
      ...
    </ul>
    ...
    
      </body>
    </html>
    
Depending on the kind of errors you are looking for you have to inspect one or both kinds of contents:
  • server generated page:
    most browsers offer the posibility to "view source code", e.g. within mouse context menu on the web page
  • client generated page:
    • Firefox:
      select Extra / Web Developer Extension / View Source / View Generated Source
    • Chrome:
      select Tools / Developer Tools. In the upcoming developer part of the web page window click on "Elements" and you can browse through the generated html tree of your web page
    • Internet Explorer:
      select Extras / Developer Tools, in the upcoming developer window select HTML tab and you can browse through the generated html tree of your web page

Top6 jQuery

Top6.1 Introduction

jQuery is a popular JavaScript library/framework which simplifies acessing and changing of HTML elements on a web page. Browser specific issues are considered within the library's implementation, thus jQuery runs on all major browsers.
Recommended way of usage
Include it from a CDN (content delivery network):
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery
    /1.11.1/jquery.min.js"></script>
</head>
Basic syntax
$(selector).action();
"selector" finds HTML elements, "action" is performed on those elements

Examples:

  • $(this).hide()
    hides the current element
  • $("p").hide()
    hides all <p> elements
  • $(".SomeClass").hide()
    hides all elements with class="SomeClass"
  • $("#SomeId").hide()
    hides all elements with id="SomeId"
  • $("[href]").hide()
    hides all elements with an href attribute
  • $("a[target='_blank']").hide()
    hides all <a> elements with a target attribute value equal to "_blank"
Before jQuery code can safely access the document structure the document should be fully loaded. This is signalled by a call to the ready function:
$(document).ready(function(){
   // access document elements...
});
Recommendation for learning
As a first learning step try to understand the source code and the reactions on the following html page. Basic jQuery sample - Main functionality in simple examples There you will find a demonstration of the most important jQuery features.

Top6.2 Selected topics

  • Method chaining
    It is possibls to run multiple jQuery commands on one html element:
    $("#someId").css("color","green").show().slideUp("fast").slideDown(3000);
    
  • Callback function
    When a jQuery effect function returns the belonging action may still be in progress. To be sure to execute the next step when the preceding step is finished, you can use a callback function as second param:
    $("#someId").hide("slow",function()
      {
        alert("The element is now hidden");
      });
    
  • Stop a running action
    stop() cancels a running animation, clearQueue() stops any queued functions.
  • Traversing HTML elements
    It is possible to navigate through the html hierarchy in any direction and with using nearly arbitrary filters.
    Examples:
    // immediate parent
    $("#someId").parent().doSomeAction();
    
    // all direct children with specific class attribute
    $("#someId").children(".SomeClass").doSomeAction();
    
    // all descendent elements of given type and having the given text
    $("#someId").find("p:contains('some text pattern')").doSomeAction();
    
    // all next sibling elements
    $("#someId").nextAll().doSomeAction();
    
    // first p element
    $("p").first();
    
    // third div element (zero based index)
    $("div").eq(2);
    
    // all div elements having the given class
    $("div").filter(".SomeClass");
    
    // all div elements NOT having the given class
    $("div").not(".SomeClass");
    
  • it is possible to use "foreach syntax" on a selection of elements:
    // do something for all paragraphs
    $("p").each(function(){
        $(this).doSomething();
    });
    

Top6.3 References

Basic jQuery sample - Main functionality in simple examples
How to address HTML elements - Selectors reference (w3schools)
Demo for adressing HTMLelements - Try selectors (w3schools)
How to iterate/navigate through an HTML tree - Traversing methods (w3schools)

Top7 PHP

Top7.1 Diverses

  • Umlenkung über ".htaccess"
    Über die Anweisungen "RewriteEngine on" und "RewriteRule" können z.B. nach aussen sichtbare Links auf Html oder Ics-Dateien auf interne dnymisch generierte Php-Seiten gelenkt werden.

Top8 Working with MySql Databases

Top8.1 phpMyAdmin

phpMyAdmin is an online tool which allows creation of new database tables and the changing of database contents of a MySql databases.

ATTENTION: Allow popups within your browser
If phpMyAdmin (runs in a popup window or new browser tab) does not show up, the reason may be that you have blocked browser popups. It is recommended to allow popups e.g. at least for the site of your web space provider.

Within Chrome perform the following steps:

  • Menu in upper right corner
  • "Settings" ("Einstellungen")
  • "Advanced settings" ("Erweiterte Einstellungen anzeigen")
  • "Datenschutz"/"Inhaltseinstellungen"
  • Pop-ups / "Ausnahmen verwalten..."
  • Insert: www.myprovider.de, "zulasssen"

Top8.2 Transfer contents and structure

Top8.2.1 Export as XML text for simple backup

  • Select table within DB WebAdmin
  • choose Export / XML format / OK
  • XML contents is displayed within browser and can be copied to some local editor
  • save editor contents in an arbitrary text/xml file

Top8.2.2 Export as SQL file for later import

You can export both structure and contents:
  • Select table within DB WebAdmin
  • choose Export / SQL format / GZIP / OK
  • GZIP file is downloaded to your download directory (typically named "myTableName.sql.gz")

Top8.2.3 Import external SQL file to your data base

You can import both structure and contents:
  • Select your database, view "new table" should be visible
  • choose Import / SQL format / browse to downloaded file ( "myTableName.sql.gz") / OK
  • imported contents should now be visible within your browser

Top8.3 Access database from within PHP

Open specific data base table
$db = mysql_connect("addressOfMyDatabaseServer",
                    "userNameOfMyDataBase",
                    "passwordOfMyDataBase")
   or
      die ("ERROR: Connection to data base failed" . mysql_error());

if ($db)
{
    mysql_select_db("nameOfMyDataBase",$db);

    // read/write fields using SQL queries
    ...
}

Top9 Strato Webspace: handling your contents

Basic setting have to be configured within php.ini

Top9.1 NEW: $_GET, $_POST, $_REQUEST exist only atprimary PHP file level

Safety reasons may have caused that the global variable arrays are no longer set within PHP includes and called PHP functions.

Workaround:
Set global variables according to submitted data (from $_REQUEST, $_GET, $_POST) directly at begin of called top level PHP file. At all other locations use the global variables. For correct working do not forget to declare them as "global $myVar;" at local scope where used.

Top9.2 Edit database contents with phpMyAdmin

  • login at Strato
  • select link "Domains"
  • select "Verwaltung" / "Datenbankverwaltung"
  • near by your desired database select "Zur Verwaltung"
  • phpMyAdmin will start in a separate window
  • select "Struktur" (or e.g. import)
  • select the table you want to change

Top9.3 Restrict access to file system directories

  • login at Strato
  • select link "Domains"
  • select "Verwaltung" / "Website-Configurator"
  • select "Verzeichnis Schutz Manager"
  • Benutzer anlegen + set password
  • "Schutz anlegen"
  • choose directory + "Verzeichnis schützen"
  • "Benutzer ändern" + "bearbeiten" + "Freigaben"
  • select from the list of protected directories those allowed for the user