Monday, September 21, 2009

Automaticly Expanding Textarea

As many of you Social Networking Site users have seen, they have neat text areas that add rows as you need them which allows them to start you off with a small textarea (1-5 rows normally) and have it dynamically grow as you need it to. This really isn't difficult to do and you will notice your form feeling more interactive with this simple addition to your code.
JS Function

function textareaResize(elem){
if(elem.scrollTop > 0){
elem.rows = elem.rows + 1;
}
}

Textarea HTML

<textarea id="text" name="text" cols="30" rows="2" onKeyUp="textareaResize(this);"></textarea>

Tuesday, August 11, 2009

Lunar Lander in Javascript

http://halorelic.com/lunar/lander.php

This is not an original idea... but it was fun. I can't find any one else providing a JS lunar lander game, probably because you could just do it in flash more stabilized and with more features. I wrote in in JS simply because I wanted to test the capability of a JS physics engine.
To use, just keep the credits in place please. Have fun.

Thursday, July 23, 2009

AJAX Form Submission

The difference between this script and others is (sarcastically) this one works. Just kidding, it does work but so do other versions.

NOTES


  • Credit is due to Mark at http://www.captain.at/howto-ajax-form-post-get.php for the core script I worked off of.
  • If your using PHP to handle the results, you'll use urldecode($_POST['field_name']) because the variables are encoded by the Javascript.
  • The way I use it is like this:

    <form action="javascript:get('this_form','Page/url.php');" id="this_form" >

    Code


    var http_request = false;
    function makePOSTRequest(url, parameters) {
    http_request = false;
    if (window.XMLHttpRequest) { // Mozilla, Safari,...
    http_request = new XMLHttpRequest();
    if (http_request.overrideMimeType) {
    // set type accordingly to anticipated content type
    //http_request.overrideMimeType('text/xml');
    http_request.overrideMimeType('text/html');
    }
    } else if (window.ActiveXObject) { // IE
    try {
    http_request = new ActiveXObject(&quot;Msxml2.XMLHTTP&quot;);
    } catch (e) {
    try {
    http_request = new ActiveXObject(&quot;Microsoft.XMLHTTP&quot;);
    } catch (e) {}
    }
    }
    if (!http_request) {
    alert('Cannot create XMLHTTP instance');
    return false;
    }

    http_request.onreadystatechange = alertContents;
    http_request.open('POST', url, true);
    http_request.setRequestHeader(&quot;Content-type&quot;, &quot;application/x-www-form-urlencoded&quot;);
    http_request.setRequestHeader(&quot;Content-length&quot;, parameters.length);
    http_request.setRequestHeader(&quot;Connection&quot;, &quot;close&quot;);
    http_request.send(parameters);
    }

    function alertContents() {
    if (http_request.readyState == 4) {
    if (http_request.status == 200) {
    //alert(http_request.responseText);
    result = http_request.responseText;
    //success code
    alert('Form submitted, good job!');
    } else if(http_request.status == 404){
    alert('Error finding page');
    } else {
    alert('There was a problem with the request.\n' + http_request.status);
    }
    }
    }

    function get(form, url) {
    var obj = document.getElementById(form);
    read_form(obj);
    makePOSTRequest(url, getstr);
    getstr = &quot;&quot;;
    }
    var getstr = &quot;&quot;;
    function read_form(obj){
    if(obj.elements.length &lt;= 0){ return false; }
    for (i=0; i&lt;obj.elements.length; i++) {
    if (obj.elements[i].tagName == &quot;INPUT&quot;) {
    if (obj.elements[i].type == &quot;text&quot; || obj.elements[i].type == &quot;hidden&quot;) {
    getstr += obj.elements[i].name + &quot;=&quot; + obj.elements[i].value + &quot;&amp;&quot;;
    }
    if (obj.elements[i].type == &quot;checkbox&quot;) {
    if (obj.elements[i].checked) {
    getstr += obj.elements[i].name + &quot;=&quot; + obj.elements[i].value + &quot;&amp;&quot;;
    } else {
    getstr += obj.elements[i].name + &quot;=&amp;&quot;;
    }
    }
    if (obj.elements[i].type == &quot;radio&quot;) {
    if (obj.elements[i].checked) {
    getstr += obj.elements[i].name + &quot;=&quot; + obj.elements[i].value + &quot;&amp;&quot;;
    }
    }
    } else
    if (obj.elements[i].tagName == &quot;SELECT&quot;) {
    var sel = obj.elements[i];
    getstr += sel.name + &quot;=&quot; + sel.options[sel.selectedIndex].value + &quot;&amp;&quot;;
    } else
    if (obj.elements[i].tagName == &quot;TEXTAREA&quot;) {
    getstr += obj.elements[i].name + &quot;=&quot; + escape( encodeURI(obj.elements[i].value) ) + &quot;&amp;&quot;;
    } else {
    alert(obj.elements[i].tagName);
    }
    }
    return getstr;
    }

  • Monday, May 18, 2009

    Shared Notepad

    I wrote this for keeping notes on a game I'm working on. I and a few other people share it and leave notes for each other and update outdated content. Helpful to you in a development situation like mine hopefully, but I won't claim it is the cleanest code and in no way OOP.
    <?php
    /*CONFIG
    */
    $directory = "txt"; //Name of directory to store files
    $showlink = TRUE; //TRUE will have a link below the text box to the actual file
    $passprotect = TRUE; //FALSE will disable the password
    $password = "fakepass"; //Use this to set password.
    $allow_view = TRUE; //TRUE will allow HTML view of txt files
    $title = "Web Notepad 1.0"; //Must be in quotes. This is what apears in the tab and when you add this page to your favorites
    $time_zone = "America/Phoenix";


    //*END CONFIG
    $version = "1.0";
    date_default_timezone_set($time_zone);
    if($_GET['onload'] > ''){
    $onload = "alert('".$_GET['onload']."');";
    }
    session_start();
    if($passprotect && $_POST['pass'] > ''){
    if($_POST['pass'] == $password){ $_SESSION['okay'] = "1"; }
    else { header('location: notepad.php?onload=Wrong password'); die(); }
    }
    if(isset($_GET['signout'])){ unset($_SESSION['okay']); }
    if(($passprotect && $_SESSION['okay'] == "1") || $passprotect == FALSE){

    if($_GET['Create'] > ""){
    $_GET['Create'] = str_replace(".txt", "", strtolower($_GET['Create']));
    $filename = $_GET['Create'].".txt";
    if(is_file($directory."/".$filename)){
    $onload = "alert('The filename -".$_GET['Create'].".txt- is already in use');";
    } else {
    $handle = fopen($directory."/".$filename, "w+");
    fclose($handle);
    header('location: notepad.php?file='.$_GET['Create']."&onload=File Created");
    die();
    }
    }
    if($_POST['text'] > ''){
    $text = $_POST['text'];
    $filename = $directory."/".$_GET['file'].".txt";
    if(is_file($filename)){
    $handle = fopen($filename, "w");
    fwrite($handle, $text, 100000);
    fclose($handle);
    header("location: notepad.php?file=".$_POST['file']."&onload=Saved");
    die();
    }
    }
    if($_GET['delete'] > ""){
    unlink($directory."/".$_GET['delete'].".txt");
    header("location: notepad.php?onload=File Deleted");
    die();
    }
    ?>

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title><?php echo $title; ?></title>
    <script type="text/javascript" language="javascript">
    var isCtrl = false;
    document.onkeyup=function(e){
    if(window.event){ //IE
    if(window.event.keyCode == 17){ isCtrl=false; }
    } else {
    if(e.which == 17){ isCtrl=false; }
    }
    }
    <?php if($_GET['file'] > ''){ ?>//ONLY IF FILE IS LOADED FOR EDIT
    document.onkeydown=function(e){
    if(window.event){ //IE
    if(window.event.keyCode == 17){ isCtrl=true; }
    if(window.event.keyCode == 83 && isCtrl == true) {
    document.notepad.submit();
    return false;
    }
    if(window.event.keyCode == 9){
    sel = document.selection.createRange().text = ' ';
    return false;
    }
    } else { //IS FF
    var element = e.target;
    if(e.which == 17){ isCtrl=true; }
    if(e.which == 83 && isCtrl == true) {
    document.notepad.submit();
    return false;
    }
    if(e.which == 9){
    //var myField = document.getElementById('pad');
    var startPos = element.selectionStart;
    var endPos = element.selectionEnd;
    element.value = element.value.substring(0, startPos)
    + " "

    + element.value.substring(endPos, element.value.length);
    element.focus();
    return false;
    }
    }
    }
    <?php } ?>
    </script>
    <style>
    body {
    font-family:Helvetica, Arial, sans-serif;
    font-weight:normal;
    font-size:16px;
    }
    input {
    border:1px solid black;
    font-size:16px;
    }
    td {
    vertical-align:top;
    }
    li {
    list-style:inside;
    }
    ul {
    margin:3px;
    padding-left:20px;
    }
    hr {
    padding:0px;
    margin:0px;
    color:#003399;
    }
    </style>
    </head>

    <body onload="if(document.getElementById('pad') != null){ document.getElementById('pad').focus(); }<?php echo $onload; ?>">

    <table width="100%" cellpadding="0" cellspacing="0">
    <tr>
    <form action="notepad.php" method="get" onsubmit="if(document.getElementById('Cname').value == ''){ alert('Must have a name'); return false; }">

    <td width="380px">New: <input type="text" name="Create" id="Cname"/><input type="submit" value="Create" />

    <br /><br />
    <div>
    <span style="font-size:18px; font-weight:bold;"> Existing Files</span>
    <ul>
    <?php
    if(!is_dir($directory)){ mkdir($directory); }
    $handle = opendir($directory);
    $i=0;
    $stuff = "\n";
    while (false !== ($file = readdir($handle))) {
    if(stripos($file, ".txt") > 0){
    $stuff .= "<li><b>$file</b> - ";
    $stuff .= "<a href=\"notepad.php?file=".str_replace(".txt", "", $file)."\">[edit]</a> ";
    if($allow_view){
    $stuff .= "<a href=\"notepad.php?view=".str_replace(".txt", "", $file)."\">[view]</a> ";
    }
    $stuff .= "&nbsp;&nbsp;<span style='font-size:12px;'><i>(".filesize($directory."/".$file)." bytes | ".date("Y-m-d g:i a", filemtime($directory."/".$file)).")</i><span>";
    $stuff .= "</l\i>\n";
    $i++;
    }
    }
    if($i == 0){ echo "No files found"; } else {
    echo "<li>File name (size | last updated)</li>\n";
    echo $stuff;
    }
    ?>

    </ul>
    </div>
    <div style="padding-top:30px;">
    <span style="font-size:10px;">
    <?php echo "Server Time: ".date('m/d/y g:i a')."<br>
    Time Zone: $time_zone<br>

    Application Version: $version"; ?></span>
    </div>
    </td>
    </form>
    <form action="notepad.php" method="post" id="notepad" name="notepad">

    <td width="" style="border:1px solid black;">
    <?php if($_GET['file'] > ""){
    $filename = $directory."/".$_GET['file'].".txt";
    if(is_file($filename)){
    $handle = fopen($filename, "r");
    $content = fread($handle, 100000);
    fclose($handle);
    } else {
    $content = "FILE DOES NOT EXIST";
    }
    echo "<span style='font-size:24px;'>&nbsp;&nbsp;".$_GET['file'].".txt</span><hr>\n";
    ?>

    <div><input type="submit" value="Save" /><input type="Button" value="Delete"
    onclick="if(confirm('Are you sure?')){ window.location='notepad.php?delete=<?php echo $_GET['file']; ?>'; }"/>

    <span style="font-size:12px;">ctrl-s to save</span></div>
    <div align="center">
    <textarea name="text" cols="80" rows="25" style="width:99%;" id="pad"><?php echo $content; ?></textarea></div>

    <input type="hidden" name="file" value="<?php echo $_GET['file']; ?>" />
    </form>
    <?php if($showlink){ echo "<a href=\"".$directory."/".$_GET['file'].".txt\">Go to \"".$_GET['file'].".txt\"</a>"; }

    } else if($_GET['view'] > '' && $allow_view == TRUE) {
    @$content = file_get_contents($directory."/".$_GET['view'].".txt");
    $content = strip_tags($content, "<b><a><u><li><ul><i>");
    echo "<span style='font-size:24px;'>&nbsp;&nbsp;".$_GET['view'].".txt</span><hr>\n";
    echo "<div style='padding:5px;'>";
    echo $content;
    echo "</div>";
    }
    ?></td>

    <td width="75px" align="right"><?php if($passprotect){ ?><a href="notepad.php?signout">Sign Out</a><?php } ?></td>
    </tr>
    </table>

    <?php } else { //Need to sign in
    ?>
    <body onload="<?php echo $onload; ?>">
    <form action="notepad.php" method="post">
    Password: <input type="text" name="pass"/><input type="submit" value="Sign In"/>

    </form>
    <?php } ?>
    </body>
    </html>
    <!--
    PHP script by Brian Wendt
    This script is free to use under the GNU License for private and commercial use
    -->

    Pure JS alternating row colors

    This Javascript will allow you to turn a plain, dull table into an interactive table like the ones in phpMyAdmin with mouseover highlighting and alternating colors. At the moment, the script is a little narrow on functionality, but simple to use.
    /* This Java Script is intended to be very lightweight and fast using DOM methods to
    style a table. Using CSS and JS together, this will allow you to have very flashy
    tables with alternating row colors and row highlighting.
    To use, include this script on the page using the <script> tags and
    give the desired table an ID attribute (example: id="table_id")
    and add the onload event "grid('table_id');".
    See bottom for License agreement...
    * * Configuration * */
    var color_one = '#CCCCCC'; //the first row color below the header
    var color_two = ''; //the second color
    var highlighted = '#999999'; //color of the row when mouse over
    var header = true; //change to false if there is no header row

    /* * End Configuration * */
    var last = '';

    function grid(table){
    var table = document.getElementById(table);
    if(table == null){ return false; }
    var trs = table.getElementsByTagName('tr');
    var tr=0;
    if(header){ tr++; }
    var trc = trs.length;
    var c=1;
    while(tr < trc){
    var tds = trs[tr++].getElementsByTagName('td');
    var td = 0;
    var tdc = tds.length;
    c++;
    if(c%2){
    while(td < tdc){
    tds[td].style.backgroundColor = color_two;
    tds[td].onmouseout= function() { highlight(this, 1); }
    tds[td++].onmouseover= function() { highlight(this, 2); }
    }
    } else {
    while(td < tdc){
    tds[td].style.backgroundColor=color_one;
    tds[td].onmouseout= function() { highlight(this, 1); }
    tds[td++].onmouseover= function() { highlight(this, 2); }
    }
    }
    }
    }
    function highlight(obj, mode){
    var tr = obj.parentNode;
    var tds = tr.getElementsByTagName('td');
    var i = 0;
    var td = 0;
    var count = tds.length;
    if(mode == 1){
    var w = last;
    } else
    if(mode == 2){
    var w = highlighted;
    last = tds[0].style.backgroundColor;
    }
    while(i < count){
    tds[i].style.backgroundColor = w;
    i++;
    }
    }
    /*
    Version 1.0 2009-04-06
    Script author: Brian Wendt <brian.m.wendt (at) gmail (dot) com>

    Script available through the Lesser GNU Public License.
    Free for private and commercial use.
    Please leave the above intact and email improvments to author
    ISSUES & NEEDS
    *grid() may preform slowly if the table is too large.
    *What other features could this use / what do you need?
    VERSION HISTORY
    1.0 (2009-04-06)
    Released with alternating color and row-highlight functionality.
    */

    CAPTCHA


    I've played with several other people's CAPTCHAs out there but decided to develop my own and share with you all. Using the PHP GD Library and True Type fonts (sorry Unix users, I'll work on a compatible version if need be) to create this distinct CAPTCHA, I hope to have reached a un-botable image.
    <?php
    session_start();
    /*
    CAPTCHA by: Brian Wendt <brian (dot) m (dot) wendt (at) gmail (dot) com>
    Please leave this credit intact when using this code (even though only developers will see it).
    About this CAPTCHA:
    This is a simple to use CAPTCHA. Features include strait and curved lines, random colors, and angled characters.
    You can tweak a few configuration values that won’t screw things up too badly and several more if you are comfortable with php.
    The curves and thick lines are behind the text, but 1/3 of the lines are thin and in front of the text.
    */
    // CONFIG
    $characters = 6; //How many characters should be in the captcha
    $text_padding = 15; //How much space between the letters
    $random_lines = 30; //How many random lines should be made
    $session = "captcha"; //Name of session variable to use ( $_SESSION[$session] )
    $case_sensitive = FALSE; //If FALSE, $_SESSION[$session] will be all lowercase


    //Characters to include in CAPTCHA
    $letters = "A B C D E F G H I J K L M N P Q R S T U V W X Y Z a b c d e f g h j k m n p q r s t u v w x y z";
    $other = "2 3 4 5 6 7 8 9 @";
    // Some letters and numbers look to much alike so they were non included
    //Color seeds
    $line_dark = 250; //0-255, higher is lighter
    $text_dark = 70; //0-255, higher is lighter

    /*
    Don't change the below unless you know what you are doing.
    If you know PHP, below is some pretty simple stuff that you should be able to figure out.
    */
    //FONTS
    //Must be TTF that the server has
    $ttf_font[0] = "Times.ttf"; $font_size[0] = 28;
    $ttf_font[1] = "Arial.ttf"; $font_size[1] = 28;
    $ttf_font[2] = "cour.ttf"; $font_size[2] = 34;
    $ttf_font[3] = "upcii.ttf"; $font_size[3] = 46;
    $fonts = count($ttf_font);
    $font_width = 16;
    $font_height = 30;


    //CHARACTERS
    $Chars = explode(" ", $letters." ".$other);
    //Clean Chars
    function removeempty($var){ if($var > ''){ return $var; } }
    $Chars = array_filter($Chars, "removeempty");
    $Char_Count = count($Chars);
    $width = (($font_width*$characters) + ($text_padding*$characters)+$text_padding);
    $height = $font_height + ($text_padding*2);

    //CREATE IMAGE
    $img = imagecreatetruecolor($width, $height);
    imagefilledrectangle($img, 0, 0, $width, $height, imagecolorallocate($img, 255, 255, 255));

    //FUNCTIONS
    function drawlines($image, $lines, $thick = 1){
    global $text_dark, $line_dark, $height, $width;
    imagesetthickness($image, $thick);
    $i=0;
    do{
    srand();
    $color = imagecolorexact($image, rand($text_dark, $line_dark), rand($text_dark, $line_dark), rand($text_dark, $line_dark));
    $x1 = rand(0, $width); $y1 = rand(0, $height); $x2 = $x1+rand(-50, 50); $y2 = $y1+rand(-150, 150);
    imageline($image, $x1, $y1, $x2, $y2, $color);
    $i++;
    }while($i < $lines);
    }
    function drawcurves($image, $lines, $thick = 1){
    global $text_dark, $line_dark, $height, $width;
    imagesetthickness($image, $thick);
    $i=0;
    do{
    srand();
    $color = imagecolorexact($image, rand($text_dark, $line_dark), rand($text_dark, $line_dark), rand($text_dark, $line_dark));
    $x = rand(0, $width); $y = rand(0, $height);
    $w = rand(10, $width/2); $h = rand(10, $height);
    $s = rand(0, 359); $e = rand($s, 359);
    imagearc($image, $x, $y, $w, $h, $s, $e, $color);
    $i++;
    }while($i < $lines);
    }

    //Draw LINES
    drawlines($img, $random_lines/3, 2);
    drawcurves($img, $random_lines/3, 2);

    //WRITE CHARACTES
    $i=0; $x=$text_padding; $Captcha = '';
    do{
    srand();
    $font = rand(0,$fonts-1);
    $angle = rand(-15, 15);
    $color = imagecolorexact($img, rand(0, $text_dark), rand(0, $text_dark), rand(0, $text_dark));
    $Char = $Chars[rand(0, $Char_Count-1)]; $Captcha .= $Char;
    $y = ($height-$text_padding)-rand(0, 10);
    imagettftext($img, $font_size[$font], $angle, $x, $y, $color, $ttf_font[$font], $Char);
    $x = $x+$font_width+$text_padding;
    $i++;
    }while($i < $characters);

    //Draw LINES
    drawlines($img, $random_lines/3);

    //OUTPUT
    if($case_sensitive){
    $_SESSION[$session] = $Captcha;
    } else {
    $_SESSION[$session] = strtolower($Captcha);
    }
    header("ETag: ".date("U"));
    header('Content-type: image/jpeg');
    imagejpeg($img);
    ?>