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 21-30 of 37 total

HTTPRequest //JavaScript Class


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

[UPDATED CODE AND HELP CAN BE FOUND HERE]



   1  
   2  //+ Jonas Raoni Soares Silva
   3  //@ http://jsfromhell.com/classes/http-request [v1.0]
   4  
   5  HTTPRequest = function(){};
   6  with({$: HTTPRequest.prototype}){
   7  	$.isSupported = function(){
   8  		return !!this.getConnection();
   9  	};
  10  	$.events = ["start", "open", "send", "load", "end"];
  11  	$.filter = encodeURIComponent;
  12  	$.getConnection = function(){
  13  		var i, o = [function(){return new ActiveXObject("Msxml2.XMLHTTP");},
  14  		function(){return new ActiveXObject("Microsoft.XMLHTTP");},
  15  		function(){return new XMLHttpRequest;}];
  16  		for(i = o.length; i--;) try{return o[i]();} catch(e){}
  17  		return null;
  18  	};
  19  	$.formatParams = function(params){
  20  		var i, r = [];
  21  		for(i in params) r[r.length] = i + "=" + (this.filter ? this.filter(params[i]) : params[i]);
  22  		return r.join("&");
  23  	};
  24  	$.get = function(url, params, handler, waitResponse){
  25  		return this.request("GET", url + (url.indexOf("?") + 1 ? "&" : "?") + this.formatParams(params), null, handler, null, waitResponse);
  26  	};
  27  	$.post = function(url, params, handler, waitResponse){
  28  		return this.request("POST", url, params = this.formatParams(params), handler, {
  29  			"Connection": "close",
  30  			"Content-Length": params.length,
  31  			"Method": "POST " + url + " HTTP/1.1",
  32  			"Content-Type": "application/x-www-form-urlencoded; charset=utf-8"
  33  		}, waitResponse);
  34  	};
  35  	$.request = function(method, url, params, handler, headers, waitResponse){
  36  		var i, o = this.getConnection(), f = handler instanceof Function;
  37  		try{
  38  			o.open(method, url, !waitResponse);
  39  			waitResponse || (o.onreadystatechange = function(){
  40  				var s = $.events[o.readyState];
  41  				f ? handler(o) : s in handler && handler[s](o);
  42  			});
  43  			o.setRequestHeader("HTTP_USER_AGENT", "XMLHttpRequest");
  44  			for(i in headers)
  45  				o.setRequestHeader(i, headers[i]);
  46  			o.send(params);
  47  			waitResponse && (f ? handler(o) : handler["end"] && handler["end"](o));
  48  			return true;
  49  		}
  50  		catch(e){
  51  			return false;
  52  		}
  53  	};
  54  }


Example

   1  
   2  <fieldset>
   3  	<legend>HTTPRequest example</legend>
   4  	<input type="button" value="POST request with generic listener and params passage" onclick="genericHandler()" />
   5  	<br /><input type="button" value="GET request with specific listener (binded on load and end)" onclick="specificHandler()" />
   6  
   7  <script type="text/javascript">
   8  //<![CDATA[
   9  
  10  var r = new HTTPRequest;
  11  
  12  function myHandler(o){
  13  	alert("Current event = " + r.events[o.readyState] +
  14  	"\nAvailable \"responseText.length\" = " + o.responseText.length);
  15  }
  16  function genericHandler(){
  17  	r.post(location.href, {param: "abcde", name: "Jonas", site: "http://jsfromhell.com"}, myHandler);
  18  }
  19  function specificHandler(){
  20  	r.get(location.href, null, {"load": myHandler, "end": myHandler});
  21  }
  22  document.write(
  23  	"<br />Supports XMLHTTPRequest = ".bold() + r.isSupported(),
  24  	"<br />Encoded with the default filter (\"encodeURIComponent\") = ".bold() + r.formatParams({nameA: "aeiou", nameB: "áéíóú"})
  25  );
  26  
  27  r.filter = escape;
  28  document.write("<br />Encoded with \"escape\" filter = ".bold() + r.formatParams({nameA: "aeiou", nameB: "áéíóú"}));
  29  
  30  r.filter = null;
  31  document.write("<br />Encoded with no filtering = ".bold() + r.formatParams({nameA: "aeiou", nameB: "áéíóú"}));
  32  
  33  //]]>
  34  </script>
  35  </fieldset>

PrototypeHelper :with helper

This method is for use in conjuction with the Ruby on Rails Module ActionView::Helpers::PrototypeHelper.

The options hash takes any number of key/value pairs the key becomes the name of the parameter passed in the with value and the value becomes a javascript expression

key — name of the parameter
value — a fragment of javascript that will be the value of the parameter

Example
>> params_for_with(:clean_range => 'clean_range', :raw_range => 'raw_range', :total_count => 'total_count')
=> 'total_count=' + total_count + '&' + 'clean_range=' + clean_range + '&' + 'raw_range=' + raw_range


Don‘t forget you won’t necessarily get the parameters out in the same order you put them in, such is the nature of hashes

   1  
   2  def params_for_with(options = {})
   3      options.collect { |param_name, js_fragment| "'#{param_name}='+#{js_fragment}" }.join("+'&'+")
   4      # or this one
   5      #options.stringify_keys.collect { |param_name, js_fragment| '"' << param_name << '="+' << js_fragment }.join('+"&"+')
   6  end

link_to_remote_unless_current

// Full discussion about this available at:
// http://6brand.com/articles/2006/06/07/link_to_remote_unless_current

   1  
   2  # throw this in one of your controller helpers.
   3  # it works just like a combination of link_to_unless_current and link_to_remote
   4  def link_to_remote_unless_current(name, options = {}, html_options = {}, *parameters_for_method_reference, &block)
   5    if current_page?(options[:url])
   6      if block_given?
   7        block.arity <= 1 ? yield(name) : yield(name, remote_function(options), html_options, *parameters_for_method_reference)
   8      else
   9        name
  10      end
  11    else
  12      link_to_function(name, remote_function(options), html_options)
  13    end
  14  end

Mini AJAX

A handy, lightweight set of AJAX functions.

   1  
   2  function $(e){if(typeof e=='string')e=document.getElementById(e);return e};
   3  function collect(a,f){var n=[];for(var i=0;i<a.length;i++){var v=f(a[i]);if(v!=null)n.push(v)}return n};
   4  
   5  ajax={};
   6  ajax.x=function(){try{return new ActiveXObject('Msxml2.XMLHTTP')}catch(e){try{return new ActiveXObject('Microsoft.XMLHTTP')}catch(e){return new XMLHttpRequest()}}};
   7  ajax.serialize=function(f){var g=function(n){return f.getElementsByTagName(n)};var nv=function(e){if(e.name)return encodeURIComponent(e.name)+'='+encodeURIComponent(e.value);else return ''};var i=collect(g('input'),function(i){if((i.type!='radio'&&i.type!='checkbox')||i.checked)return nv(i)});var s=collect(g('select'),nv);var t=collect(g('textarea'),nv);return i.concat(s).concat(t).join('&');};
   8  ajax.send=function(u,f,m,a){var x=ajax.x();x.open(m,u,true);x.onreadystatechange=function(){if(x.readyState==4)f(x.responseText)};if(m=='POST')x.setRequestHeader('Content-type','application/x-www-form-urlencoded');x.send(a)};
   9  ajax.get=function(url,func){ajax.send(url,func,'GET')};
  10  ajax.gets=function(url){var x=ajax.x();x.open('GET',url,false);x.send(null);return x.responseText};
  11  ajax.post=function(url,func,args){ajax.send(url,func,'POST',args)};
  12  ajax.update=function(url,elm){var e=$(elm);var f=function(r){e.innerHTML=r};ajax.get(url,f)};
  13  ajax.submit=function(url,elm,frm){var e=$(elm);var f=function(r){e.innerHTML=r};ajax.post(url,f,ajax.serialize(frm))};


How to use:

ajax.x - The XMLHttpRequest object (or MS equivalent) used for communication

ajax.serialize(f)
f = the form element you wish to be serialized
This function serializes all the fields in a form so that they can be passed as a query string in the form "arg1=val1&arg2=val2".

ajax.get(url, func)
url = the url to query (can contain arguments after a '?')
func = the function to call once the response is returned
This function uses a GET request to query the specified url and return a response to the specified function.

ajax.gets(url)
url = the url to query (can contain arguments after a '?')
This function uses a GET request to query the specified url and return a response synchronously. Use this sparingly, as synchronous calls can lock up the browser.

ajax.post(url, func, args)
url = the url to query
func = the function to call once the response is returned
args = a string containing arguments to be passed to the url
This function uses a POST request to query the specified url and return a response to the specified function.

ajax.update(url, elm)
url = the url to query
elm = the (name of the) element to update
This function uses a GET request to query the specified url and insert the result into the specified element.

ajax.submit(url, elm, frm)
url = the url to query
elm = the (name of the) element to update
frm = the form element to submit
This function is typically used in the onsubmit handler of a function. The form is not submitted the usual way; the form is instead serialized using "ajax.serialize" and submitted using "ajax.post". The result is then inserted into the specified element.

dojo/window/slidshow

// description of your code here

   1  
   2  <?php
   3  /*
   4   * Created on 2006-4-7
   5   *
   6   * To change the template for this generated file go to
   7   * Window - Preferences - PHPeclipse - PHP - Code Templates
   8   */
   9  ?>
  10  
  11  <html>
  12  <head>
  13  <meta http-equiv="Content-Language" content="en" />
  14  <meta name="GENERATOR" content="PHPEclipse 1.0" />
  15  <meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
  16  </head>
  17  
  18  
  19  <link href="dojo/src/widget/templates/HtmlSlideShow.css" rel="stylesheet" type="text/css" />
  20  <script type="text/javascript" src="dojo/dojo.js"></script>
  21  
  22  	<script type="text/javascript" src="windows/javascripts/prototype.js"> </script> 
  23  	<script type="text/javascript" src="windows/javascripts/effects.js"> </script>
  24  	<script type="text/javascript" src="windows/javascripts/window.js"> </script>
  25  	<script type="text/javascript" src="windows/javascripts/debug.js"> </script>
  26  	<link href="windows/themes/default.css" rel="stylesheet" type="text/css" >	 </link>
  27  	<link href="windows/themes/theme1.css" rel="stylesheet" type="text/css" >	 </link>
  28  	<link href="winodws/themes/alert.css" rel="stylesheet" type="text/css" >	 </link>
  29  	<title>Sample Windows</title>
  30  <script type="text/javascript">
  31     //dojo.require("dojo.widget.Editor");
  32      //dojo.require("dojo.widget.SlideShow");
  33  	//doji.require("dojo.event.*");
  34       </script>
  35  
  36  <body bgcolor="#FFFFFF" text="#000000" link="#FF9966" vlink="#FF9966" alink="#FFCC99">
  37  
  38  	<a href="javascript:openModalDialog()">Click here to open a modal window</a>
  39  	<br/>
  40  	<script>
  41  	var index= 0;
  42      var contentWin = null;
  43  		function openContentWindow() {
  44  		if (contentWin != null) {
  45  			Dialog.alert("Close the window 'Test' before opening it again!"); 
  46  		}
  47  		else {
  48  			contentWin = new Window('content_win', {title: "Test ",top:100, left:100, resizable: false})
  49  			contentWin.setContent('test_content', true)
  50  			contentWin.toFront();
  51  			contentWin.setDestroyOnClose();
  52  			contentWin.show();	
  53  		}		
  54  	}
  55  
  56  		function openModalDialog() {
  57  		var win = new Window('modal' + index, {title: "易登网",top:100, left:100,  width:300, height:200, zIndex:150, opacity:50, resizable: true,hideEffect: Effect.Grow})
  58  		win.getContent().innerHTML = "&nbsp;&nbsp;<a href='http://www.edeng.cn'>edeng</a><br /><input type='submit' value='æ??交'>"
  59  		win.show(true);	
  60  		index++;
  61  	}
  62  
  63  
  64  
  65  	win = new Window('dialog1', {className: "dialog",  width:300, height:400, zIndex: 100, resizable: true, title: "Title", hideEffect: Effect.SwitchOff})
  66  	win.getContent().innerHTML= "<div style='padding:10px'> Lorem ipsum dolor sit amet, consectetur adipiscing elit, set eiusmod tempor incidunt et labore et dolore magna aliquam. Ut enim ad minim veniam, quis nostrud exerc. Irure dolor in reprehend incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse molestaie cillum. Tia non ob ea soluad incom dereud facilis est er expedit distinct. Nam liber te conscient to factor tum poen legum odioque civiuda et tam. \
  67  	At vver eos et accusam dignissum qui blandit est praesent. Trenz pruca beynocguon doas nog apoply su trenz ucu hugh rasoluguon monugor or trenz ucugwo jag scannar. Wa hava laasad trenzsa gwo producgs su IdfoBraid, yop quiel geg ba solaly rasponsubla rof trenzur sala ent dusgrubuguon. Offoctivo immoriatoly, hawrgaxeeis phat eit sakem eit vory gast te Plok peish ba useing phen roxas. Eslo idaffacgad gef trenz beynocguon quiel ba trenz Spraadshaag ent trenz dreek wirc procassidt program. Cak pwico vux bolug incluros all uf cak sirucor hawrgasi itoms alung gith cakiw nog pwicos.\
  68  	Lor sum amet, commy nulputat. Duipit lum ipisl eros dolortionsed tin hent aliquis illam volor in ea feum in ut adipsustrud elent ulluptat. Duisl ullan ex et am vulputem augiam doloreet amet enibh eui te dipit acillutat acilis amet, suscil er iuscilla con utat, quisis eu feugait ad dolore commy nullam iuscilisl iureril ilisl del ut pratuer iliquis acipissit accum quis nulluptat. Dui bla faccumsan velis auguero con henis duismolor sumsandrem quat vulluptat alit er iniamcore exeriure vero core te dit ut nulla feummolore commod dipis augiamcommod tem ese dolestrud do odo odiamco eetummy nis aliquamcommy nonse eu feugue del eugiamconsed ming estrud magnis exero eumsandio enisim del dio od tat.sumsan et pratum velit ing etue te consequis alis nullan et, quis am iusci bla feummy.</div>"
  69  	win.showCenter();
  70  	</script>
  71  <div dojoType="Editor" items="textGroup;|;listGroup;|;colorGroup;|;blockGroup;|;commandGroup;">
  72      some contentfsdfsdfsdfsdfsdfsdfsd  dddd
  73  </div>
  74  <img dojoType="SlideShow" 
  75      imgUrlBase="dojo/src/pic/"
  76      imgUrls="2.jpg;3.jpg" 
  77      transitionInterval="700"
  78      delay="1000"
  79      imgWidth="400"
  80      imgHeight="300"
  81      width="400"
  82      height="300"
  83      src="http://dojotoolkit.org/path/to/dojo/tests/widget/images/1.jpg" /><p>
  84      <?php echo "ddd" ?>
  85  
  86  
  87  
  88  
  89  
  90  </body>
  91  </html>
  92    
  93  

good website

// description of your code here

   1  
   2  http://blogus.xilinus.com/pages/javawin
   3  http://bennolan.com/behaviour/
   4  http://prototype.conio.net/
   5  http://ajaxpatterns.org/PHP_Ajax_Frameworks
   6  http://www.ajaxload.info/
   7  http://www.dragon-labs.com/articles/utm/
   8  http://www.snook.ca/archives/000531.php
   9  http://www.netlobo.com/div_hiding.html
  10  http://www.roundcube.net/
  11  http://24ways.org/
  12  http://www.designologue.com/v3/
  13  http://www.musicstrands.com/
  14  http://www.soundclick.com/
  15  http://www.drweb.de/programmierung/ajax.shtml
  16  http://www.modernmethod.com/sajax/
  17  
  18   http://css.maxdesign.com.au/
  19  http://www.iconbuffet.com/
  20  http://www.mainada.net/comics/edit_strip/new
  21  
  22  http://bennolan.com/behaviour/
  23  
  24  http://lab.rails2u.com/bgmaker/
  25  易登网www.edeng.cn ï¼Œæ±‚èæ‹›è〈¿å±‹å‡ºç§Ÿã€‰¾æœ‹å?‹ä¸€ç½‘打尽ï¼?

Ultra simple Prototype.js AJAX example

Taken from the great Amy Hoy.

   1  <h2>ajax replacing link</h2>
   2  <a href="backend.php?return=time" 
   3     onclick="new Ajax.Updater('testdiv', 'backend.php?return=time',
   4     {asynchronous:true, evalScripts:true }); return false;">
   5  This link updates a line</a>
   6  <div id="testdiv"></div>


With no JavaScript turned on, it'll go to the normal URL. Without, it'll do an XMLHTTPRequest and put the result in #testdiv.

Display images in separate div on mouseover of list entry

Exerpt of prog to handle images from 35mm film. Main admin page displays a table of films. On mouseover of each row thumbnails of the pictures in that film are displayed in a separate div.

Exerpt of list.rhtml
   1  
   2  <tr id="tablerow<%= roll.id %> " onMouseover="<%= remote_function(:update => "preview",  :url => { :action => :preview ,  :id => roll.id})%>;">


Exerpt of controller.rb
   1  
   2    def preview
   3      @pictures = Picture.find(:all, :conditions => ["roll_id = #{params[:id]} "])
   4      render(:partial => "preview")
   5    end


_preview.rhtml
   1  
   2  <% for picture in @pictures%>
   3  <img src= <%= picture.thumb_url %> alt= <%= picture.thumb_url %> height=60 >
   4  <% end %>

how to escape from AJAX URL

From Dylan Stamat's post on the Ruby on Rails list


Within my "login.rjs" template that get's invoked after my login process, it returns to the same page with an error message on error, or... if the login was successful, it needs to "redirect" to another controller... which is pretty much impossible to do otherwise. so, my " login.rjs" looks like:

   1  
   2  if @logged_in_client
   3    page.replace_html "message", :partial => 'shared/bad_login'
   4  else
   5    page.redirect_to "whatever you want here"
   6  end

------ End Message--------
Here is my two cents:
Technically, you can do this without a RJS template at all, because it is such a simple example. Use this in your controller

   1  
   2  render :update do |page|
   3    if @logged_in_client
   4      page.replace_html "message", :partial => 'shared/bad_login'
   5    else
   6      page.redirect_to "whatever you want here"
   7    end
   8  end

Ruby on Rails: AJAX Live Search using MySQL and Rails

source: http://weknowsnow.com/blog/techside.php?itemid=64

The following code will create a live search in your Ruby on Rails project using AJAX. This Web 2.0 stuff is neaaaato. Yes, I'm sure there are better ways to do this, post a comment if you have them. This works for me right now so I'm going with it. You'll have to reformat the code because I dont have time to do that under this Nucleus blog software. Enjoy and please leave a comment if you find this code helpful! Ruby on Rails makes writing code fun....

Tags: Web 2.0, AJAX, Ruby, Rails, Ruby on Rails, Javascript, Live, Search, Live Search

VIEWS -> yourcontroller -> search.rhtml
   1  
   2  <%= start_form_tag({:action=> "search"}, { :onSubmit => "Element.show('spinner');" }) %>
   3  <table>
   4  <tr>
   5  <td><label for="searchtext"><font size="1"><b>Live TR Search:</b></font></label></td>
   6  <td><%= text_field_tag :searchtext %></td>
   7  <td><img alt="spinner" id="spinner" src="http://dev.backcountrymaps.com/images/spinner.gif" style="display:none;" /></td>
   8  </tr>
   9  </table>
  10  <%= end_form_tag%>
  11  
  12  <%= observe_field(:searchtext,
  13                   :frequency => 0.5,
  14                   :update => :search_hits,
  15                   :loading => "Element.show('spinner')",
  16                   :complete => "Element.hide('spinner')",
  17                   :url => { :action => :live_search }) %>
  18  
  19  <div id="search_hits"></div>

VIEWS -> yourcontroller -> live_search.rhtml
   1  
   2  <% if @results.empty? %>
   3    '<%=h @phrase %>' not found!
   4  <% else %>
   5    '<%=h @phrase %>' found <b><%= @number_match %></b> time(s)!
   6  <% end %>

CONTROLLERS -> yourcontroller.rb
   1  
   2  def live_search
   3  
   4      @phrase = request.raw_post || request.query_string
   5      a1 = "%"
   6      a2 = "%"
   7      @searchphrase = a1 + @phrase + a2
   8      @results = <b>YOURMODEL</b>.find(:all, :conditions => [ "<b>YOURTABLE</b> LIKE ?", @searchphrase])
   9     
  10      @number_match = @results.length
  11     
  12      render(:layout => false)
  13  end


HINT: It would be very easy to step through @results with a for each loop and display any column from the database record using foreach_loopvar.dbcolumn_name.....
« Newer Snippets
Older Snippets »
Showing 21-30 of 37 total