Quick submission form (HTML/AJAX)

Anything to do with games at all.
Fizheuer Zieheuer
Member ♥
Joined in 2008

PostQuick submission form (HTML/AJAX)
by Fizheuer Zieheuer » Mon Aug 25, 2008 5:53 am

Spurred on by a fellow developer's labour in testing a database handler script for a Flash game he's working on, I decided to create an AJAX-based form-controlled tester page.

Basically, you save a backup of this and then modify your active version of it so it points at a page that is intended to receive data via POST or GET, listing the appropriate variables to send.

Then, all you have to do is fill in the fields automatically generated for you and click 'send vars' and it displays feedback in the same page, without forcing you to refresh or navigate elsewhere.

  • AJAX supports POST and GET methods
  • AJAX can be disabled if you want the form to actually physically direct you to the target script
  • Supports strings, numbers, long text (textareas), booleans (checkboxes) and multiple-choice selections (radio buttons and dropdowns). Doesn't currently support file upload testing, and I didn't build in a password input option, but it's probably as flexible as you need a testing form to be in a development environment.

Screenshot of the unmodified page, matching the theme of my upcoming site update:

Image

Download it here
Distributed freely under no license whatsoever.

Just download that link, change the extension to .php, and then give it a look-see. It isn't necessarily the best or cleanest coding around, but I made a point of keeping the script completely self-contained, referencing nothing external besides the target script, for maximum portability.

The entire source follows, if you would prefer to just copy-paste it into a text file. Feel free to modify this as much or as little as you like depending on your needs. If you have any feedback, please do say so!

Code: Select all

<?php

# Quick submission form by Studio Aneurin.
# Requires a PHP server and, optionally, Javascript/AJAX support.
# Distributed freely under no license whatsoever, so feel free to modify/expand this as you wish.

########################
#### Begin editing #####
########################

# Base URL to send vars to. By default the following line should work fine on localhost setups, when
# submitting your form back to this page for testing purposes, but for external access you will need
# to set it quite specifically.
$url_base   = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['SCRIPT_NAME'];

$url_method = 'post';             # Send method (get/post). Case insensitive as it is corrected where necessary.
$url_return = 'AJAX';             # Whether to display form output within the page or simply direct to $url_base. (AJAX/DIRECT)
$vars       = array ();           # Vars to use. This is the one line you don't edit btw!

# Begin adding your form elements.

$vars['one'] = array ('Example string',  'string');
$vars['two']   = array ( true,  'bool');
$vars['three']   = array ( false, 'text');
$vars['four']  = array (array('first' => 'First option', 'second' => 'Second option'), 'radio', 'second');
$vars['five']  = array (array('first' => 'First option', 'second' => 'Second option'), 'drop', 'first');

# Types can be 'string', 'bool', 'text', 'radio' or 'drop', as outlined below:

# $vars['string_example'] = array (value:String,  'string');
# $vars['bool_example]    = array (value:Boolean, 'bool);
# $vars['text_example']   = array (value:String,  'text');
# $vars['radio_example']  = array (value:Array (key => label, key => label), 'radio'[, selected-key:String]);
# $vars['drop_example']   = array (value:Array (key => label, key => label), 'drop'[, selected-key:String]);

ksort ($vars);      # Sort vars A-Z. You can change this if it matters.
$use_subbed = true; # This must be true if you are sending input back to this script.
                    # Otherwise, you may (and probably should) set it false.
                    # Setting this to false removes the 'subbed' hidden field so it doesn't affect external requests.

###############################
##### Stop editing. Stop! ##### Unless you want to mess with the source that is, but it isn't advised for newbies.
###############################

# Now, before anything else, check if POST or GET values have been sent back to this script.
# If so, simply return sent values in a semi-array format. Note that checkboxes don't send in forms when they are unchecked,
# so the Javascript form combiner further down (if used) leaves out unchecked boxes. Same with radio forms if no options are selected.

$die = '';
$die_line = '<p>{n} = {v}</p>' . "\n    ";

if (isset ($_POST['subbed'])):
  foreach ($_POST as $n => $v):
    $die .= str_replace (array ('{n}', '{v}'), array ($n, $v), $die_line);
  endforeach;
  die ($die);
elseif (isset ($_GET['subbed'])):
  foreach ($_GET as $n => $v):
    $die .= str_replace (array ('{n}', '{v}'), array ($n, $v), $die_line);
  endforeach;
  die ($die);
endif;

# Outputting to HTML.

$html_output = '';

# HTML output templates.
$html_string   = '<p><label for="{var_name}" class="l">var <strong>{var_name}</strong></label> <input type="text" name="{var_name}" id="{var_name}" value="{var_value}" /></p>' . "\n    ";
$html_bool     = '<p><label for="{var_name}" class="l">var <strong>{var_name}</strong></label> <input type="checkbox" name="{var_name}" id="{var_name}" {checked}/></p>' . "\n    ";
$html_text     = '<p><label for="{var_name}" class="l">var <strong>{var_name}</strong></label> <textarea name="{var_name}" id="{var_name}" rows="auto" cols="auto">{var_value}</textarea></p>' . "\n    ";
$html_radio    = '<p><span class="label">{var_name2}</span><input type="radio" name="{var_name}" id="{var_name}{var_opt}" value="{var_opt}" {checked}/> <label for="{var_name}{var_opt}">{var_label}</label></p>' . "\n    ";
$html_drop     = '<p><label for="{var_name}" class="l">var <strong>{var_name}</strong></label> <select name="{var_name}" id="{var_name}">{opts}
    </select></p>' . "\n    ";
$html_drop_opt = "\n      " . '<option value="{var_key}"{selected}>{var_value}</option>';

foreach ($vars as $var_name => $var_vals):
  $temp_form = '';
  if ($var_vals[1] == 'string'):
    $temp_form .= str_replace ('{var_name}', $var_name, $html_string);
    $temp_form = str_replace ('{var_value}', $var_vals[0], $temp_form);
  elseif ($var_vals[1] == 'bool'):
    $temp_form .= str_replace ('{var_name}', $var_name, $html_bool);
    if ($var_vals[0]):
      $vr = 'checked="checked" ';
    else:
      $vr = '';
    endif;
    $temp_form = str_replace ('{checked}', $vr, $temp_form);
  elseif ($var_vals[1] == 'text'):
    $temp_form .= str_replace ('{var_name}', $var_name, $html_text);
    $temp_form = str_replace ('{var_value}', $var_vals[0], $temp_form);
  elseif ($var_vals[1] == 'radio'):
    $temp_form = '';
    $radiopen  = true;
    foreach ($var_vals[0] as $var_key => $var_label):
      $temp_opt = str_replace (array ('{var_opt}', '{var_name}', '{var_label}'), array ($var_key, $var_name, $var_label), $html_radio);
      if ($radiopen):
        $temp_opt = str_replace ('{var_name2}', 'var <strong>' . $var_name . '</strong>', $temp_opt);
        $radiopen = false;
      endif;
      if (isset ($var_vals[2])):
        if ($var_key == $var_vals[2]):
          $temp_opt = str_replace ('{checked}', 'checked="checked" ', $temp_opt);
        endif;
      endif;
      $temp_form .= $temp_opt;
    endforeach;
    $temp_form = str_replace ('{var_name2}', '', $temp_form);
    $temp_form = str_replace ('{checked}', '', $temp_form);
  elseif ($var_vals[1] == 'drop'):
    $temp_form = str_replace ('{var_name}', $var_name, $html_drop);
    $temp_opts = '';
    foreach ($var_vals[0] as $var_key => $var_label):
      $temp_opt = str_replace (array ('{var_key}', '{var_value}'), array ($var_key, $var_label), $html_drop_opt);
      if (isset ($var_vals[2])):
        if ($var_key == $var_vals[2]):
          $temp_opt = str_replace ('{selected}', ' selected="selected"', $temp_opt);
        endif;
      endif;
      $temp_opts .= $temp_opt;
    endforeach;
    $temp_form = str_replace ('{opts}', $temp_opts, $temp_form);
    $temp_form = str_replace ('{selected}', '', $temp_form);
  endif;
  $html_output .= $temp_form;
endforeach;

?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>
  <title>Quick submission form</title>
  <style type="text/css">
  * {
    margin:  0;
    padding: 0;
  }
  body, input, textarea {
    color:       #303030;
    font-family: Arial, Helvetica, sans-serif;
    font-size:   10pt;
  }
  form {
    margin:  20px auto;
    padding: 20px;
    width:   460px;
  }
  p {
    margin-bottom: 10px;
  }
  h1 {
    border-bottom:  2px solid #303030;
    font-weight:    normal;
    margin-bottom:  30px;
    padding-bottom: 5px;
    text-align:     center;
  }
  p label.l, p .label {
    display:      block;
    float:        left;
    padding-left: 10px;
    padding-top:  2px;
    width:        100px;
  }
  p.footer {
    border-top:  2px solid #303030;
    margin-top:  30px;
    padding-top: 8px;
    text-align:  center;
  }
  a {
    color: #de3232;
    text-decoration: none;
  }
  a:hover {
    text-decoration: underline;
  }
  ul {
    padding-left: 110px;
  }
  input, textarea {
    border:  1px solid #303030;
    padding: 2px 4px;
  }
  textarea {
    height: 100px;
    width:  330px;
  }
  div#ajaxcontent {
    border-top: 2px solid #303030;
    margin-top: 30px;
    padding:    8px 10px 0 10px;
  }
  </style><?php
  # If AJAX enabled, include the request source.
  if ($url_return == 'AJAX'): ?>
 
  <script type="text/javascript">
  //<![CDATA[
  function requestScript() {
    var ajContent = document.getElementById('ajaxcontent');
    ajContent.innerHTML = 'Awaiting returned content...';
    var xmlHttp;
    try {
      // Firefox, Opera 8.0+, Safari
      xmlHttp=new XMLHttpRequest();
    } catch (e) {
      // Internet Explorer
      try {
        xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
      } catch (e) {
        try {
          xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
        } catch (e) {
          alert("Your browser does not support AJAX!");
          return false;
        }
      }
    }
    xmlHttp.onreadystatechange=function() {
      if(xmlHttp.readyState==4) {
        if (document.getElementById('showurl').checked) {
          var requested = '<p><a href="' + url + '?' + queryString + '" title="URL of your request">' + url + '?' + queryString + '</a></p>';
          ajContent.innerHTML = requested + xmlHttp.responseText;
        } else {
          ajContent.innerHTML =  xmlHttp.responseText;
        }
      }
    }
    var method = <? echo '"' . strtoupper ($url_method) . '"'; ?>;
    var url    = <? echo '"' . $url_base . '"'; ?>;
    var queryString = '';
    var qrElements  = document.getElementById("qrForm").elements;
    var radiopened  = false;
    for (var i = 0; i < qrElements.length; i ++) {
      if (qrElements[i].name != '') {
        if (qrElements[i].type == 'checkbox') {
          if (qrElements[i].checked) {
            queryString += (qrElements[i].name + "=" + qrElements[i].value + '&');
          }
        } else if (qrElements[i].type == 'radio') {
          if (qrElements[i].checked) {
            queryString += (qrElements[i].name + "=" + qrElements[i].value + '&');
          }
        } else {
          queryString += (qrElements[i].name + "=" + qrElements[i].value + '&');
        }
      }
    }
    queryString = queryString.substring(0, queryString.length-1);
    if (method == 'POST') {
      xmlHttp.open('POST', url, true);
      xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
      xmlHttp.send(queryString);
    } else {
      var urlWithVars = url + '?' + queryString;
      xmlHttp.open('GET', urlWithVars, true);
      xmlHttp.send(null);
    }
  }
  //]]>
  </script>
  <?php
  endif;
  ?>
</head>

<body>
  <form action="<?php if ($url_return == 'DIRECT'): echo $url_base; endif; ?>" enctype="multipart/form-data" method="<?php echo strtolower ($url_method); ?>" id="qrForm"><?php if ($use_subbed): ?>
    <p style="display: none"><input type="hidden" name="subbed" value="true" /></p><?php endif; ?>
    <h1>Quick submission form</h1>
    <?php

# Echo HTML.
echo $html_output;

if ($url_return == 'AJAX'): ?>
<p><span class="label">&nbsp;</span><input type="checkbox" id="showurl" /> <label for="showurl">Show URL above returned values</label></p><?php endif; ?>

    <p><span class="label">&nbsp;</span><?php if ($url_return == 'DIRECT'): ?><input type="submit" value="Send vars" /><?php else: ?><input type="button" value="Send vars" onclick="requestScript()" /><?php endif; ?></p>
    <ul>
      <li>via <?php echo strtoupper($url_method); ?></li>
      <li>to <a href="<?php echo $url_base; ?>" title="Go to this address"><?php echo $url_base; ?></a></li>
    </ul><?php

# Spot for AJAX return if it is enabled.
if ($url_return == 'AJAX'): ?>

    <div id="ajaxcontent">AJAX return spot. Submit the form to start seeing returned data here. Please note that this spot is by default subject to the dominating stylesheet as it is intended for variable returning. For more elaborate returns, you may want to modify the CSS to exclude this area from existing style rules.</div>
  <?php
endif;

?>
  <p class="footer">Courtesy <a href="http://www.aneuri.net/" title="Studio Aneurin">Studio Aneurin</a>. Distributed freely under no license whatsoever.</p>
  </form>

<!-- W3C XHTML 1.0 Strict validated, but who really cares? -->

</body>

</html>

User avatar
Alpha eX
Member
Joined in 2008
Location: London
Contact:

PostRe: Quick submission form (HTML/AJAX)
by Alpha eX » Mon Aug 25, 2008 1:31 pm

Cheers, this is really handy, save me a lot of time, i've put the requests I need in a drop down, makes testing this game much less tedious.

User avatar
Tell Karl his brother is dead
Daiakuma
Daiakuma
Joined in 2008
Contact:

PostRe: Quick submission form (HTML/AJAX)
by Tell Karl his brother is dead » Mon Aug 25, 2008 5:55 pm

Geek!


Return to “Games”

Who is online

Users browsing this forum: Yahoo [Bot] and 23 guests