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-7 of 7 total  RSS 

request params

Request: #<ActionController::CgiRequest:0x452205c @path_parameters={"action"=>"dispatch", "controller"=>"mephisto", "path"=>["2006", "12", "23", "just-wanna-see"]}, @request_parameters={"action"=>"dispatch", "controller"=>"mephisto", "path"=>["2006", "12", "23", "just-wanna-see"]}, @session_options=false, @session={}, @env={"SERVER_NAME"=>"localhost", "PATH_INFO"=>"/2006/12/23/just-wanna-see", "HTTP_ACCEPT_ENCODING"=>"gzip,deflate", "HTTP_USER_AGENT"=>"Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1", "SCRIPT_NAME"=>"/", "SERVER_PROTOCOL"=>"HTTP/1.1", "HTTP_ACCEPT_LANGUAGE"=>"en-us,en;q=0.5", "HTTP_HOST"=>"localhost:3000", "REMOTE_ADDR"=>"127.0.0.1", "SERVER_SOFTWARE"=>"Mongrel 0.3.13.3", "HTTP_KEEP_ALIVE"=>"300", "HTTP_REFERER"=>"http://localhost:3000/", "HTTP_ACCEPT_CHARSET"=>"ISO-8859-1,utf-8;q=0.7,*;q=0.7", "HTTP_VERSION"=>"HTTP/1.1", "REQUEST_URI"=>"/2006/12/23/just-wanna-see", "SERVER_PORT"=>"3000", "GATEWAY_INTERFACE"=>"CGI/1.2", "HTTP_ACCEPT"=>"text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5", "HTTP_CONNECTION"=>"keep-alive", "REQUEST_METHOD"=>"GET"}, @content_type=nil, @cgi=#<Mongrel::CGIWrapper:0x452269c @out_called=false, @input=#<StringIO:0x45228f4>, @request=#<Mongrel::HttpRequest:0x452291c @body=#<StringIO:0x45228f4>, @params={"SERVER_NAME"=>"localhost", "PATH_INFO"=>"/2006/12/23/just-wanna-see", "HTTP_ACCEPT_ENCODING"=>"gzip,deflate", "HTTP_USER_AGENT"=>"Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1", "SCRIPT_NAME"=>"/", "SERVER_PROTOCOL"=>"HTTP/1.1", "HTTP_ACCEPT_LANGUAGE"=>"en-us,en;q=0.5", "HTTP_HOST"=>"localhost:3000", "REMOTE_ADDR"=>"127.0.0.1", "SERVER_SOFTWARE"=>"Mongrel 0.3.13.3", "HTTP_KEEP_ALIVE"=>"300", "HTTP_REFERER"=>"http://localhost:3000/", "HTTP_ACCEPT_CHARSET"=>"ISO-8859-1,utf-8;q=0.7,*;q=0.7", "HTTP_VERSION"=>"HTTP/1.1", "REQUEST_URI"=>"/2006/12/23/just-wanna-see", "SERVER_PORT"=>"3000", "GATEWAY_INTERFACE"=>"CGI/1.2", "HTTP_ACCEPT"=>"text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5", "HTTP_CONNECTION"=>"keep-alive", "REQUEST_METHOD"=>"GET"}, @socket=#<TCPSocket:0x45232a4>>, @params={}, @multipart=false, @output_hidden=nil, @head={}, @handler=#<Mongrel::Rails::RailsHandler:0x463f1c4 @listener=#<Mongrel::HttpServer:0x2e55b1c @workers=#<ThreadGroup:0x2e559dc>, @host="0.0.0.0", @death_time=60, @classifier={"/"=>[#<RequestLog::Access:0x2dfae60 @listener=#<Mongrel::HttpServer:0x2e55b1c ...>, @header_only=false, @options={:includes=>["mongrel"], :timeout=>0, :pid_file=>"log/mongrel.pid", :config_script=>nil, :environment=>"development", :host=>"0.0.0.0", :num_processors=>1024, :group=>nil, :docroot=>"public", :port=>3000, :user=>nil, :mime_map=>nil, :cwd=>"C:/Projects/blog.transphorm.com", :daemon=>false, :debug=>false, :log_file=>"log/mongrel.log"}>, #<Mongrel::Rails::RailsHandler:0x463f1c4 ...>]}, @port=3000, @acceptor=#<Thread:0x44fda2c sleep>, @num_processors=1024, @timeout=0, @socket=#<TCPServer:0x2e55acc>>, @guard=#<Mutex:0x463f138 @locked=true, @waiting=[]>, @files=#<Mongrel::DirHandler:0x463f14c @default_content_type="text/plain; charset=ISO-8859-1", @path="C:/Projects/blog.transphorm.com/public", @index_html="index.html", @listing_allowed=false>>, @args=nil, @output_cookies=nil, @response=#<Mongrel::HttpResponse:0x4522908 @header=#<Mongrel::HeaderOut:0x4522840 @out=#<StringIO:0x4522868>>, @body=#<StringIO:0x45228a4>, @status_sent=false, @status=404, @header_sent=false, @body_sent=false, @socket=#<TCPSocket:0x45232a4>>, @cookies={}>, @symbolized_path_parameters=nil, @request_method=:get, @query_parameters={}, @parameters={"action"=>"dispatch", "controller"=>"mephisto", "path"=>["2006", "12", "23", "just-wanna-see"]}>

Perl - send form POST

// Manda le informazioni per il login ad un determinato sito

use HTTP::Request::Common qw(POST);
use LWP::UserAgent;

my $user = "user";
my $pass = "pass";

my $browser = LWP::UserAgent->new();

my $responde = HTTP::Request->new(POST => "http://www.sito.com/index.php");
$responde->content_type("application/x-www-form-urlencoded");
$responde->content("user=" . $user . "&pass=" . $pass);

$browser->request($responde)->as_string

Code Snippets Feature Request

I wonder how I can search for snippets in Code Snippets.
Searching Code Snippets thru Google, is it the only way?

// insert code here..

HTTPRequest //JavaScript Class


Class to make remote requests, which can be used on the popular "AJAX".

[UPDATED CODE AND HELP CAN BE FOUND HERE]



//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/classes/http-request [v1.0]

HTTPRequest = function(){};
with({$: HTTPRequest.prototype}){
	$.isSupported = function(){
		return !!this.getConnection();
	};
	$.events = ["start", "open", "send", "load", "end"];
	$.filter = encodeURIComponent;
	$.getConnection = function(){
		var i, o = [function(){return new ActiveXObject("Msxml2.XMLHTTP");},
		function(){return new ActiveXObject("Microsoft.XMLHTTP");},
		function(){return new XMLHttpRequest;}];
		for(i = o.length; i--;) try{return o[i]();} catch(e){}
		return null;
	};
	$.formatParams = function(params){
		var i, r = [];
		for(i in params) r[r.length] = i + "=" + (this.filter ? this.filter(params[i]) : params[i]);
		return r.join("&");
	};
	$.get = function(url, params, handler, waitResponse){
		return this.request("GET", url + (url.indexOf("?") + 1 ? "&" : "?") + this.formatParams(params), null, handler, null, waitResponse);
	};
	$.post = function(url, params, handler, waitResponse){
		return this.request("POST", url, params = this.formatParams(params), handler, {
			"Connection": "close",
			"Content-Length": params.length,
			"Method": "POST " + url + " HTTP/1.1",
			"Content-Type": "application/x-www-form-urlencoded; charset=utf-8"
		}, waitResponse);
	};
	$.request = function(method, url, params, handler, headers, waitResponse){
		var i, o = this.getConnection(), f = handler instanceof Function;
		try{
			o.open(method, url, !waitResponse);
			waitResponse || (o.onreadystatechange = function(){
				var s = $.events[o.readyState];
				f ? handler(o) : s in handler && handler[s](o);
			});
			o.setRequestHeader("HTTP_USER_AGENT", "XMLHttpRequest");
			for(i in headers)
				o.setRequestHeader(i, headers[i]);
			o.send(params);
			waitResponse && (f ? handler(o) : handler["end"] && handler["end"](o));
			return true;
		}
		catch(e){
			return false;
		}
	};
}


Example

<fieldset>
	<legend>HTTPRequest example</legend>
	<input type="button" value="POST request with generic listener and params passage" onclick="genericHandler()" />
	<br /><input type="button" value="GET request with specific listener (binded on load and end)" onclick="specificHandler()" />

<script type="text/javascript">
//<![CDATA[

var r = new HTTPRequest;

function myHandler(o){
	alert("Current event = " + r.events[o.readyState] +
	"\nAvailable \"responseText.length\" = " + o.responseText.length);
}
function genericHandler(){
	r.post(location.href, {param: "abcde", name: "Jonas", site: "http://jsfromhell.com"}, myHandler);
}
function specificHandler(){
	r.get(location.href, null, {"load": myHandler, "end": myHandler});
}
document.write(
	"<br />Supports XMLHTTPRequest = ".bold() + r.isSupported(),
	"<br />Encoded with the default filter (\"encodeURIComponent\") = ".bold() + r.formatParams({nameA: "aeiou", nameB: "áéíóú"})
);

r.filter = escape;
document.write("<br />Encoded with \"escape\" filter = ".bold() + r.formatParams({nameA: "aeiou", nameB: "áéíóú"}));

r.filter = null;
document.write("<br />Encoded with no filtering = ".bold() + r.formatParams({nameA: "aeiou", nameB: "áéíóú"}));

//]]>
</script>
</fieldset>

Auto-store all request variables

// Puts all request variables into local variables. Never type request.querystring again. Easily modified to work with option explicit.

<%
	For each item in Request.querystring
		If not len(item) <= 0 Then
			Execute("[" & item & "] = Request(""" & item & """)")
		End If
	Next

	For each item in Request.form
		If not len(item) <= 0 Then
			Execute("[" & item & "] = Request(""" & item & """)")
		End If
	Next
%>

Request Adapter //PHP Class

A simple class providing a cute adapter for get/post requests.

Usage
$r = &new Request(POST_METHOD | GET_METHOD);
#$r = &new Request(POST_METHOD); //just post
#$r = &new Request(GET_METHOD); //just get =b

if($r->has('name'))
  echo $r->get('name'), $r->name;

echo $r->get('year', '2006');

if($r->isPosted())
  echo 'This was a post =b';


if($r->isFile('file'))
  if($r->file->isUploaded()){
    echo 'The file was uploaded';
    if($r->file->hasError())
      echo 'And there was an error when uploading';
    else{
      echo 'Moving ' . $r->file->path;
      $r->file->save('uploads/' . $r->file->name)
    }
  }




<?php
//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com

define('GET_METHOD', 1);
define('POST_METHOD', 2);

class PostedFile{
	var $file, $name, $type, $size, $path, $error;

	function PostedFile(&$f){
		$this->file = &$f;
		$this->name = $f['name'];
		$this->type = $f['type'];
		$this->size = $f['size'];
		$this->path = $f['tmp_name'];
		$this->error = $f['error'];
	}

	function hasError(){
		return $this->isUploaded() && $this->error != UPLOAD_ERR_OK;
	}

	function isUploaded(){
		return $this->error != UPLOAD_ERR_NO_FILE;
	}

	function save($path){
		return @move_uploaded_file($this->path, $path);
	}
}

class Request{
	function &Request($method){
		if(GET_METHOD & $method)
			foreach($_GET as $n=>$v)
				$this->$n = $v;
		if(POST_METHOD & $method){
			foreach($_POST as $n=>$v)
				$this->$n = $v;
			foreach($_FILES as $n=>$v)
				$this->$n = &new PostedFile($v);
		}
		return $this;
	}

	function isFile($name){
		return is_a($this->get($name), 'PostedFile');
	}

	function has($name){
		if(is_array($name)){
			foreach($name as $n)
				if(!isset($this->$n))
					return false;
			return true;
		}
		else
			return isset($this->$name);
	}

	function get($name, $default = null){
		if($this->has($name))
			return $this->$name;
		else
			return $default;
	}

	function isPosted(){
		return $_SERVER['REQUEST_METHOD'] == 'POST' && isset($_SERVER['CONTENT_LENGTH']) && $_SERVER['CONTENT_LENGTH'];
	}
}
?>

OnlyOneOfClass: Extension to prototype library allowing AJAX calls to supercede / abort / cancel previous calls within a given class.

// Extension to Ajax allowing for classes of requests of which only one (the latest) is ever active at a time
// - stops queues of now-redundant requests building up / allows you to supercede one request with another easily.

// just pass in onlyLatestOfClass: 'classname' in the options of the request

Ajax.currentRequests = {};

Ajax.Responders.register({
	onCreate: function(request) {
		if (request.options.onlyLatestOfClass && Ajax.currentRequests[request.options.onlyLatestOfClass]) {
			// if a request of this class is already in progress, attempt to abort it before launching this new request
			try { Ajax.currentRequests[request.options.onlyLatestOfClass].transport.abort(); } catch(e) {}
		}
		// keep note of this request object so we can cancel it if superceded
		Ajax.currentRequests[request.options.onlyLatestOfClass] = request;
	},
	onComplete: function(request) {
		if (request.options.onlyLatestOfClass) {
			// remove the request from our cache once completed so it can be garbage collected
			Ajax.currentRequests[request.options.onlyLatestOfClass] = null;
		}
	}
});
« Newer Snippets
Older Snippets »
Showing 1-7 of 7 total  RSS