Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-10 of 31 total  RSS 

A simple XHTML submit form for ProjectX

Preparing ProjectX API requests through the browser's address bar can get quite messy, however inputting the request through a simple form makes it much easier to read.

<!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>ProjectX API</title>
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
  </head>
  <body>
    <h1>ProjectX API form</h1>
    <p>Enter the Project API XML to send a request to the server.</p>
    <form action="http://rorbuilder.info/api/projectx.cgi" method="post" id="projectx_form">
    <fieldset><legend>xml_project</legend><textarea id="xml_project" name="xml_project" cols="104" rows="20"></textarea></fieldset>
    <div><button type="submit">Submit</button></div>
    </form>
  <p>
    <a href="http://validator.w3.org/check?uri=referer"><img
        src="http://www.w3.org/Icons/valid-xhtml10"
        alt="Valid XHTML 1.0 Strict" height="31" width="88" style="float:right;  border:0 "/></a>
  </p>
  <p style="clear:float">last updated: 13th April 2008</p>
  
  </body>
</html>


The web page can be seen at http://rorbuilder.info/r/projectx-api/index.html
The following XML request value when submitted should return an XML result containing the results and the method executed.
<project name='whiteboardqueue'>
  <methods>
    <method name='get_user_id'>
      <params/>
    </method>
  </methods>
</project>

eg.
<result method="rtn_get_user_id">
  <get_user_id>36539</get_user_id>
</result>

Upload a file using Ajax

This code is categorised as Ajax because it "fits within my definition of Ajax" as explained from the Ajax File Upload [openjs.com] article.

<!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>File upload</title>
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
    <script type="text/javascript">
    //<![CDATA[
      function init() {
	document.getElementById('file_upload_form').onsubmit=function() {
                                  //'upload_target' is the name of the iframe
	  document.getElementById('file_upload_form').target = 'upload_target'; 
	  }
  }
  window.onload=init;
    //]]>
    </script>
  </head>
  <body>
    <form id="file_upload_form" method="post" enctype="multipart/form-data" action="/p/file_upload.cgi">
    <input name="myfile" id="myfile" size="27" type="file" /><br />
    <input type="submit" name="action" value="Upload" /><br />
    <iframe id="upload_target" name="upload_target" src="" style="width:0;height:0;border:0px solid #fff;"></iframe>
    </form>
  </body>
</html>

Upload a file using Ruby

The following code was used to upload an image file to the web server. Source code origin: Ruby Language Stuff | mod_ruby File upload scripts [zytrax.com]

file: file_upload.cgi
#!/usr/bin/ruby

# ruby script fragment
require 'cgi'
require 'stringio'

cgi = CGI.new()  # New CGI object
puts "Content-Type: text/plain"
puts
print '<result>'

# get uri of tx'd file (in tmp normally)
tmpfile = cgi.params['myfile'].first.path

# OR (functionally the same)
tmpfile = cgi.params['myfile'][0].path

# create a Tempfile reference
fromfile = cgi.params['myfile'].first

#displays the original file name as supplied in the form
puts fromfile.original_filename

# displays the content (mime) type e.g. text/html
puts fromfile.content_type

# create output file reference as original filename in our chosen directory
tofile = '/var/www/yourdomain.com/htdocs/r/'+fromfile.original_filename

# copy the file
# note the untaint prevents a security error
# cgi sets up an StringIO object if file < 10240
# or a Tempfile object following works for both
File.open(tofile.untaint, 'w') { |file| file << fromfile.read}
# when the page finishes the Tempfile/StringIO!) thing is deleted automatically

print '</result>'

file: file_upload.html
<!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>File upload</title>
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
  </head>
  <body>
    <form name='fileupload' enctype="multipart/form-data" 
    action='/p/file_upload.cgi' method='post'>
    <input type='file' name='myfile' size="40" />
    <input type='submit' value"Send it"/>
    </form>
  </body>
</html>
  

Submit Form programmatically from PHP using JavaScript

It´s something quite easy but may help a newby (as I´m now) in the future.
This is a simple function in PHP to insert a JavaScript sentence which will do the same action as if the user would be pressing the Submit Button.
It can be used to use any control as a Submit Button or in case you make a form you need to send without interaction from the user.
the $FormName must be the name specified in the Form tag (i.e.: <form action="MyActionURL" method="post" enctype="application/x-www-form-urlencoded" name="MyFormName">), if you didn´t specified any, you must now :)
Lastly, just a tip regarding a trouble I had and may be you case too... if you have a form with all hidden fields, it won´t work, you have to have at least something echoed inside the form, just a letter can help, anyway, as it will redirect to the action URL, it should not be a problem as the form will disappear.

function SubmitForm($FormName)
//JavaScript function to submit a form programmatically
//$FormName must be form´s name (as specified in the opening form tag)
{
	echo '<script language="javascript">document.'.$FormName.'.submit()</script>';
}

'Delete a Twitter entry' dissected

The following code was copied from my Twitter home page, it shows how to delete a twitter entry on the server.

raw HTML code with embedded JavaScript code.

<a href="/status/destroy/719423092" onclick="if (confirm('Sure you want to delete this update? There is NO undo!')) 
{var f = document.createElement('form'); f.style.display = 'none'; this.parentNode.appendChild(f); f.method = 
'POST'; f.action = this.href;var m = document.createElement('input'); m.setAttribute('type', 'hidden'); 
m.setAttribute('name', '_method'); m.setAttribute('value', 'delete'); f.appendChild(m);var s = 
document.createElement('input'); s.setAttribute('type', 'hidden'); s.setAttribute('name', 'authenticity_token'); 
s.setAttribute('value', 'd0057265c3784d2a6dc6cdb2c26083f638152151'); f.appendChild(s);f.submit(); };return false;" 
title="Delete this update?">


same code as above but with comments.
<a href="/status/destroy/719423092" onclick="

                     // if the user clicks the 'OK' button the confirm function will return true
if (confirm('Sure you want to delete this update? There is NO undo!')) { 

  // -- dhtml: creating html elements on-the-fly -------------------------------
  var f = document.createElement('form'); // create the dhtml 'form' (<form/>) element
  f.style.display = 'none';               // hide the form
  this.parentNode.appendChild(f);         // append the form element to the parent of the current node (<a/>)
  f.method = 'POST';                      // add the method to the form
  f.action = this.href;                   // add the action using the href of the current node (<a/>)
    
  var m = document.createElement('input');   // create the input (<input/>) 'element' 
  m.setAttribute('type', 'hidden');          // set the input type to 'hidden'
  m.setAttribute('name', '_method');         // set the input name to '_method'
  m.setAttribute('value', 'delete');         // set the input value to 'delete'
  f.appendChild(m);                          // append the input element to the form element
  
  var s = document.createElement('input');   // create another input element
  s.setAttribute('type', 'hidden');          // set the type to 'hidden'
  s.setAttribute('name', 'authenticity_token'); // set the name to 'authenticity_token'
  
                                     // set the input element's value using a unique id.
  s.setAttribute('value', 'd0057265c3784d2a6dc6cdb2c26083f638152151'); 
  
  f.appendChild(s);                  // apend the input element to the form element
  // -- end of dhtml: creating html elements on-the-fly -------------------------------
  
  f.submit(); // post the form data back to the server to delete the record, 
              // just as if the user had pressed the submit button.
};

  return false; // returning false cancels the default <a href="..."> request. 
                 // However if JavaScript had been disabled for some reason the 
                 // <a href="..."> would have acted normally, meaning the record 
                 // would have been deleted from following the URL request directly.
 "

Note: Twitter needs JavaScript for the web page to work properly, I've tried and it is not possible to delete a record without JavaScript. The authenticity_token has been altered by me to prevent any malicious activity on my Twitter account.

Blueprint CSS forms extension

Changes the widths of form elements so they fit into smaller columns created using the Blueprint CSS framework.

div.span-1 input.text, div.span-1 input.title { width:  30px; }
div.span-2 input.text, div.span-2 input.title { width:  50px; }
div.span-3 input.text, div.span-3 input.title { width:  90px; }
div.span-4 input.text, div.span-4 input.title { width: 130px; }
div.span-5 input.text, div.span-5 input.title { width: 170px; }
div.span-6 input.text, div.span-6 input.title { width: 210px; }
div.span-7 input.text, div.span-7 input.title { width: 250px; }
div.span-8 input.text, div.span-8 input.title { width: 290px; }

div.span-1 select { width:  30px; }
div.span-2 select { width:  50px; }
div.span-3 select { width:  90px; }
div.span-4 select { width: 130px; }
div.span-5 select { width: 170px; }

div.span-1  textarea { width:  30px; height:  25px; }
div.span-2  textarea { width:  50px; height:  50px; }
div.span-3  textarea { width:  90px; height:  75px; }
div.span-4  textarea { width: 130px; height: 100px; }
div.span-5  textarea { width: 170px; height: 125px; }
div.span-6  textarea { width: 210px; height: 150px; }
div.span-7  textarea { width: 250px; height: 175px; }
div.span-8  textarea { width: 290px; height: 200px; }
div.span-9  textarea { width: 330px; height: 225px; }
div.span-10 textarea { width: 370px; height: 250px; }

Use rails date_select without activerecord model

// In your view:
<%= date_select('range', 'start_date', :order => [:month, :day, :year])%>


// In your controller:
@start_date = Date.civil(params[:range][:"start_date(1i)"].to_i,params[:range][:"start_date(2i)"].to_i,params[:range][:"start_date(3i)"].to_i)


Credit: http://www.jonsthoughtsoneverything.com/2006/05/21/how-to-access-date_select-without-an-active-record-model/

text input /w background image

// self-explanatory. see title.

<style type="text/css">
.searchBox{
  background-image:url('http://www.dhtmlgoodies.com/tips-and-tricks/input-with-background/images/magnifying-glass.gif');
  background-repeat:no-repeat;
  padding-left:20px;
}
</style>

<input type="text" name="search" style="border:2px inset gray;color:black;background-color:lightyellow;font-family:arial narrow;font-weight:bold;font-size:9pt;" class="searchBox">

Using a mutiple collection select form helper with habtm or has many associations in Rails

// where user has and belongs to many roles

# in your view
<%= collection_select :user, :role_ids, Role.find(:all, :order => 'name ASC'), :id, :name, { :selected => @user.role_ids }, { :multiple => true, :name => 'user[role_ids][]' } -%>

Fix for camping multipart parsing issue.

// description of your code here
I wrote a nice description of this issue, but snippets ate it.

In short, this parses complicated form names into nice hashes, i.e. name[asd][asd] for multipart forms.

module Camping
module Base
 def initialize(r, e, m) #:nodoc:
      e = H[e.to_hash]
      @status, @method, @env, @headers, @root = 200, m.downcase, e,
          {'Content-Type'=>'text/html'}, e.SCRIPT_NAME.sub(/\/$/,'')
      @k = C.kp(e.HTTP_COOKIE)
      qs = C.qs_parse(e.QUERY_STRING)
      @in = r
      todo = []
      if %r|\Amultipart/form-data.*boundary=\"?([^\";,]+)|n.match(e.CONTENT_TYPE)
        b = /(?:\r?\n|\A)#{Regexp::quote("--#$1")}(?:--)?\r$/
        until @in.eof?
          fh=H[]
          for l in @in
            case l
            when Z: break
            when /^Content-Disposition: form-data;/
              fh.u H[*$'.scan(/(?:\s(\w+)="([^"]+)")/).flatten]
            when /^Content-Type: (.+?)(\r$|\Z)/m
              puts "=> fh[type] = #$1"
              fh[:type] = $1
            end
          end
          fn=fh[:name]
          o=if fh[:filename]
            o=fh[:tempfile]=Tempfile.new(:C)
            o.binmode
          else
            fh=""
          end
          while l=@in.read(16384)
            if l=~b
              o<<$`.chomp
              @in.seek(-$'.size,IO::SEEK_CUR)
              break
            end
            o<< l
          end
          if(fn)
            qs.merge!(C.qs_parse(fn + "=1"))
            parts = fn.split(/\[/)
            line = ""
            parts.each do |pp|
              pp = pp.gsub(/\]/,"")
              line += "['#{pp}']"
            end
            #p "line is:"
            #p line
            #p fh
            todo << ["qs#{line}", fh]
            #eval("qs#{line} = fh")
            #p qs
          end
          fh[:tempfile].rewind if fh.is_a?H
        end
      elsif @method == "post"
        qs.merge!(C.qs_parse(@in.read))
      end
      #post process vars
      todo.each do |n|
        eval("#{n.first} = n.last")
      end
      #p "END QUERY"
      #p qs
      #exit
      @cookies, @input = @k.dup, qs.dup
    end


end 
end
// insert code here..
« Newer Snippets
Older Snippets »
Showing 1-10 of 31 total  RSS