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
Perl - send form POST
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
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
<% 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
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; } } });