Recent Changes - Search:

Home Pages Pidgin   Azarennya (S|N) Mac Textanium Reference ToDo Food Local Edit

Local: Hide

Language: Hide

Fantasy: Hide

SciFi: Hide

Film: Hide

Music: Hide

REALbasic: Hide

ResourcesGarageUniversityWebRingForums:REALElfDataPlugins and Code:BKeeneyDeclareSubEinhugurJoeRestrepoTempelmannZAZ

Coding: Hide

Forums:PowWebPHPWebmasterCodingWalkersPerlIntroMonksPHPJavaScriptToolboxUnobtrusiveJavaScriptJavaScriptCompressorRegularExpressions (test)JSLintSQLCocoaCocoaBuilderCocoaDevCocoaLabAppleScriptBBSUserlandFaqintoshFileMakerFileMakerTipsFileMakerWorldFileMakerPlugins

Science: Hide

History: Hide

1421

News/Politics: Hide

Cults/Crime: Hide

ClambakeInfidels

Miscellaneous: Hide

WebProgramming

PHP Hints

Strings

  • explode($delimiter, $string [, $limit])
  • implode($glue, $array_of_pieces)
  • number_format($number, $decimals = 0, $decimal_point = '.', $thousand_separator = ',')
  • soundex($string) returns soundex string (one letter, three digits) so that words with similar sounds can be compared.
  • sprintf($format [, $arg [, $arg [, ...]]])
    • Use format '%04d' to output a number padded with leading zeroes to at least four digits.
  • strpos($haystack, $needle, $offset = 0) = $position (starting from zero) or FALSE
  • trim($string [, $charlist = " \t\n\r\0\x0B"])

Arrays

  • array_diff($array1, $array2 [, $array3 [, ...]]) returns all values in $array1 that are not also values in any of the other arrays passed.
    • To keep only those elements of array $a that appear in array $b (without introducing any elements of $b that do not appear in $a), use array_diff($a, array_diff($a, $b)).
  • array_filter($array [, $callback]) passes each value in array to callback function. Value is added to array returned only if $callback(value) returns TRUE. (If no callback is supplied, function returns array stripped of any FALSE (0, null, "") values.)
  • array_flip($array1) returns a new array whose keys are the values of $array1 and vice versa. (The keys must all be either integers or strings or this function won't work.)
  • array_intersect($array1, $array2 [, $array3 [, ...]]) returns all values in $array1 that are also values in all of the other arrays passed.
  • array_keys($array [, $search_value]) returns the keys of $array as a new array. Returns only the keys whose value == $search_value if that is provided.
  • array_search($needle, $haystack [, $strict]) searches array for $needle, returns key if found, FALSE if not.
  • array_slice($array, $offset [, $length [, $preserve_keys]])
  • in_array($needle, $haystack [, $strict = FALSE]) returns whether $needle exists as a value in the array $haystack. Set $strict = TRUE to return TRUE only if an item in the array has both the same value and the same type as $needle.

Files

  • fgets($handle [, $maxlength]) reads a line (including final newline) from the file.
  • file($filename) reads entire file into an array of lines.

Predefined variables

  • $_SERVER['DOCUMENT_ROOT'] e.g., /home/users/web/b198/pow.aitch748/htdocs
  • $_SERVER['SERVER_NAME'] e.g., karig.net
  • $_SERVER['HTTP_HOST'] e.g., karig.net
  • $_SERVER['SCRIPT_FILENAME'] e.g., /home/users/web/b198/pow.aitch748/htdocs/foo/bar.php
  • $_SERVER['SCRIPT_URI'] e.g., http://karig.net/foo/bar.php
  • $_SERVER['PHP_SELF'] e.g., /foo/bar.php

JavaScript Hints

"For" loops: Use continue to abort the current cycle and start the next; use break to abort the loop completely.

For each property in an object:

    var record = "Wine 1<br><br>"
    for (var prop in wine1) {
        record += prop + " = " + wine1[prop] + "<BR>"
    }

Creating an object with custom properties on the fly:

    myPetDog=new Object();
    myPetDog.name="Barney"; 
    myPetDog.breed="beagle";
    myPetDog.year=1981;
    // Adding function "woof()" to object as a method:
    myPetDog.sound=woof;

Creating a prototype object:

    function petDog(name, breed, year) {
        this.name = name;
        this.breed = breed;
        this.year = year;
    }

Creating an object from a prototype:

    myPetDog = new petDog("barney","beagle",1981);
    yourPetDog=new petDog("max","terrier",1990);

jQuery Hints

Shortcut to do something as soon as the DOM is ready:

    $(function(){ /* do something when DOM is ready */ });

Append HTML to the content of every DIV of class "foo":

    $("div.foo").append("<b>Hello!</b>");

Change the CSS property "color" for all paragraphs:

    $("p").css("color","red");

Have every link show an alert when clicked:

    $(document).ready(function() {
        $("a").click(function() {
            alert("Hello world!");
        });
    });

Have a button's "click" event download and display a quote:

    $(document).ready(function(){
        $("#generate").click(function(){
            $("#quote p").load("get_quote.php");
        });
    });

    <!-- HTML -->
    <div id="quote"><p><!-- QUOTE GOES HERE --></p></div>
    <input type="submit" id="generate" value="Generate!">

Equivalent to "onSubmit":

    $("form#chatform").submit(function(){ /* Code */ });

Clicking on a given link shows or hides a given DIV:

    $('a#slick-toggle').click(function() {
            $('#slickbox').toggle(400);
                // Show or hide DIV in 400 ms.
                // Or use 'slow', 'normal', or 'fast'.
                // Or call .slideToggle(400) instead.
            return false;
        });

Submit form to server and handle response:

    $("form#chatform").submit(function(){
        $.post(
            "backend.php",                  // PHP script
            {
                message: $("#msg").val(),   // Script parameters
                name: $("#author").val(),
                action: "postmsg",
                time: timestamp
            },
            function(xml) {                 // Response handler
                doSomethingWith(xml);
            }
        );
        return false; // Ensures we don't leave the page!
    });

DOM selection examples:

    $('div.panel')
        // All divs with class=“panel”
    $('p#intro')
        // The paragraph with id=“intro”
    $('div#content a:visible')
        // All visible links inside the div with id=“content”
    $('input[@name=email]')
        // All input fields with name=“email”
    $('table.orders tr:odd')
        // “odd” numbered rows in a table with class “orders”
    $('a[@href^="http://"]')
        // All external links (links that start with http://)
    $('p[a]')
        // All paragraphs that contain one or more links

    $('li:eq(0)')
        // gets the first list item.
    $('li:even')
        // gets items [0], [2], [4], [6], etc.
    $('li:lt(3)')
        // gets items "less than" [3] -- i.e., [0], [1], [2].
    $('li:not(.foo)')
        // gets all list items that aren't of class "foo".
    $('p a[@href*=#]')
        // gets any links that contain "#". (Space between "p"
        // and "a" means that "a" is a descendant of "p".)
    $('code, li.foo')
        // gets all code elements AND any list item of class "foo".
    $('ol .foo > strong')
        // gets all strong elements that are children of any "foo"-
        // class element, if that element is anywhere inside an
        // ordered list (it does not specifically have to be a CHILD
        // of the ordered list).
    $('li + li > a[@href$=pdf]')
        // gets all links ending in "pdf" that are children of any list
        // item that has another list item as its previous sibling.
    $('span:hidden')
        // gets any span element that is hidden.

    $('a[@href^=http]').not('[@href*=mysite.com]')
        // gets all links containing "http" but not containing "mysite.com"
        // (intention: to get all links to other websites, perhaps so you
        // could append an "external link" graphic)

DOM alteration examples:

    $('div#primary').width(300);
        // Set the width of div id=“primary” to 300 px.
    $('p').css('line-height', '1.8em');
        // Apply a line-height of 1.8em to all paragraphs.
    $('li:odd').css({color: 'white', backgroundColor: 'black'});
        // Apply two CSS rules to every other list item; note that the css()
        // function can take an object instead of two strings.
    $('a[@href^="http://"]').addClass('external').attr('target', '_blank');
        // Add a class of “external” to all external links (those beginning
        // with http://), then add target=“_blank” for good measure.
    $('blockquote').each(function(el) { alert(jQuery(this).text()) });
        // Iterate over every blockquote on the page, and alert its textual
        // content (excluding HTML tags).
    $('a').html('Click here!');
        // Replace all link text on the page with the insidious “Click here!”. 

DOM inspection examples:

    var width = $('div').width();
        // How wide is the first div on the page?
    var src = $('img').attr('src');
        // What’s the src attribute of the first image on the page?
    var color = $('h1').css('color');
        // What color is the first h1?

DOM traversal examples:

    $('div').not('[@id]')
        // Returns divs that do not have an id attribute.
    $('h2').parent()
        // Returns all elements that are direct parents of an h2.
    $('blockquote').children()
        // Returns all elements that are children of a blockquote.
    $('p').eq(4).next()
        // Find the fifth paragraph on the page, then find the next element
        // (its direct sibling to the right).
    $('input:text:first').parents('form')
        // Find the form parent of the first input type=“text” field on the
        // page. The optional argument to parents() is another selector. 

Element "stack" examples (using .end()):

    $('form#login')
            // hide all the labels inside the form with the 'optional' class
        .find('label.optional').hide().end()
            // add a red border to any password fields in the form
        .find('input:password').css('border', '1px solid red').end()
            // add a submit handler to the form
        .submit(function(){
            return confirm('Are you sure you want to submit?');
        });

Create a DIV, set its attributes, and prepend to another DIV:

    var div = $('<div>Text</div>').addClass('inserted').attr('id', 'foo');
    div.prependTo('div#primary');

Trigger an event:

    $('p:first').click();
        // Send a fake “click” to the first paragraph on the page.

Have links be highlighted in orange when the mouse hovers over them:

    $('a').hover(function() {
            $(this).css('background-color', 'orange');
        }, function() {
            $(this).css('background-color', 'white');
        });

Set up a one-time-only event handler:

    $('p').one('click', function() {
            alert(jQuery(this).html());
        });
        // The paragraph contents appear in an alert only on the FIRST
        // time you click on the paragraph, not thereafter.

Change the first letter in the first paragraph to a drop cap:

    var first_paragraph = $('#main-content p')[0];
    if (!first_paragraph) return false;
    var node = first_paragraph;
    while (node.childNodes.length) {
        node = node.firstChild;
    }

    var text = node.nodeValue;
    var first_letter = text.substr(0,1);
    var match = /[a-zA-Z]/.test(first_letter);
    if ( match ) {
        node.nodeValue = text.slice(1);
        $('<img />')
            .attr('src','/images/caps/' + first_letter.toLowerCase() + '.gif')
            .attr('alt',first_letter)
            .addClass('fancy-letter')
            .prependTo( first_paragraph );
        }
    }

Ajax options

(http://docs.jquery.com/Ajax/jQuery.ajax#options)

Code like what I expect to use:

    $.ajax({
        type: "POST",
        url: "find.php",
        data: "q=abc&c=def",
        datatype: "json", // or "html" if your script returns that instead.
        success: function(data){
            // Do something with data returned from server.
            // If datatype was "json" then data should be an object.
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            // typically only one of textStatus or errorThrown  will have info
        }
    });

Load and execute a JavaScript file:

    $.ajax({
        type: "GET",
        url: "test.js",
        dataType: "script"
    });

Retrieve the latest version of an HTML page:

    $.ajax({
        url: "test.html",
        cache: false,
        success: function(html){
            $("#results").append(html);
        }
    });

Optimization

jQuery has a "speed hierarchy":

  • $('#some_id') (accessing items by ID) is fastest; jQuery calls getElementById() for this.
  • $('div') (accessing items by HTML element) is slower; jQuery calls getElementsByTagName() for this, to get a subset of the elements to search through.
  • $('.some_class') (accessing items by class) is slowest; jQuery has to examine every element in the document, because a class can be attached to anything.

To speed up class access, put all items of a given class inside an element with an ID, then use $('#some_id .some_class') to access the items.

Edit - History - Print - Recent Changes - Search
Page last modified on December 20, 2007, at 11:02 AM