Never been to CodeSnippets 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 (or not, you can keep them private!)

javascript :: create an xml request object

javascript :: create an xml request object

/* create an xml request object */
function createRequest() 
{
   try
   {
      /* Firefox */
      req = new XMLHttpRequest();
   } 
   catch(err1) 
   {
      try 
      {
         /* some versions IE */
         req = new ActiveXObject("Msxml2.XMLHTTP");
      } 
      catch (err2)
      {
         try 
         {
            /* other versions IE */
            req = new ActiveXObject("Microsoft.XMLHTTP");
         }
         catch (err3)
         {
            req = false;
         }
      }
   }
   return req;
}

xmlhttp with testing for various ie versions

var xmlHTTP = getXMLHTTP();

if (xmlHTTP) {
    xmlHTTP.async = false;
    xmlHTTP.open('get', 'http://google.com/');
    xmlHTTP.send(null);

    if (xmlHTTP.status == 200) {
        var data = xmlHTTP.responseText;
    }
}

function getXMLHTTP()
{
    if ((typeof XMLHttpRequest) != "undefined") {
        /* XMLHTTPRequest present, use that */
        return new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        /*  there are several versions of IE's Active X control, use the most recent one available */
        var xmlVersions = ["MSXML2.XMLHttp.5.0",
                           "MSXML2.XMLHttp.4.0",
                           "MSXML2.XMLHttp.3.0",
                           "MSXML2.XMLHttp",
                           "Microsoft.XMLHTTP"];

        for (var x = 0; x < xmlVersions.length; x++) {
            try {
                var xmlHTTP = new ActiveXObject(xmlVersions[x]);
                return xmlHTTP;     
            } catch (e) {
                //continue looping
            }
        }
    }

    /* if none of that worked, return false, to indicate failure */
    return false;
}

Load file into Div via Ajax

// SCRIPT

$j(document).ready(function() {
	$j('a#ajaxLink').click(function(){
		$j("#ajaxBox").load("public/js/testAjax.html");
	});
});


// HTML
<a id="ajaxLink" href="javascript:;">Load Ajax</a>
<div id="ajaxBox"></div>

Crea Objeto XMLHTTPRequest

function ajaxFunction()
{
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("Explorador no soporta--------AJAX!");  
	     xmlhttp= false;  
	    }
       }	// fin si no es Internet Explorer
     }   // fin si no es Firefox
return xmlhttp;
} // fin de crear objeto XMLHTTPRequest

Ajax-creaObjeto-XMLHttpRequest

// description of your code here

Código JavaScript:
/*
*Esta libreria es una libreria AJAX creada por Javier Mellado con la inestimable
*colaboracion de Beatriz Gonzalez.
*y descargada del portal AJAX Hispano http://www.ajaxhispano.com
*contacto javiermellado@gmail.com
*
*Puede ser utilizada, pasada, modificada pero no olvides mantener
*el espiritu del software libre y respeta GNU-GPL
*/ 
function creaAjax(){
         var objetoAjax=false;
         try {
          /*Para navegadores distintos a internet explorer*/
          // jajajajaja ... IE tambien entra aqui ...
          objetoAjax = new ActiveXObject("Msxml2.XMLHTTP");
         } catch (e) {
          try {
                   /*Para explorer*/
                   objetoAjax = new ActiveXObject("Microsoft.XMLHTTP");
                   }
                   catch (E) {
                   objetoAjax = false;
          }
         }

         if (!objetoAjax && typeof XMLHttpRequest!='undefined') {
          objetoAjax = new XMLHttpRequest();
         }
         return objetoAjax;
}
                                     


jQuery namespaced event binding/unbinding

// from a comment by Steven Bristol on errtheblog.com

I just wanted to share a really killer event handling tidbit:

Generally you do something like:

jQuery(’.class’).click(function(){//whatever});


Everyone knows this can be rewritten as:

jQuery(’.class’).bind(‘click’, function(){//whatever});


But sometimes you need to unbind something:

jQuery(’.class’).unbind(‘click’, function(){//});


The problem with this is that it will unbind all the click events, not just yours. So if multiple bits of javascript have a click event handler for ’.class’, unbinding removes them all. (This is because there is no way to identify an anonymous function.)

But jQuery is so good that there is a way to handle this: Namespacing your events:

jQuery(’.class’).bind(‘click.namespace’, function(){//}); 
jQuery(’.class’).unbind(‘click.namespace’);


or for reinitializing an element added via ajax:

jQuery(’.class’)unbind(‘click.namespace’).bind(‘click.namespace’, function(){//});

jQuery and Rails' respond_to

// Just throw this at the bottom of your application.js and you’re good to go: all jQuery ajax requests will trigger the wants.js block of your respond_to declaration, exactly like you’d expect. Enjoy.
// via: http://ozmm.org/posts/jquery_and_respond_to.html

jQuery.ajaxSetup({beforeSend’: function(xhr) {xhr.setRequestHeader(“Accept”,text/javascript”)} })

Ajax / Effects-only link

To create a link that is used purely for some Scriptaculous effects or for an Ajax call, use # as the href target and return false from the javascript onlick call.

<a href="#" onclick="Effect.toggle('widget_preview', 'blind');return false;">Blog this ...</a>

Never render the full layout in a Rails view when called via AJAX

Essential for degradable javascript, when one never knows if a view or partial is being called via XmlHttpRequest or not. Throw the below code in your ApplicationController (application.rb)

More info in this blog post

def render(*args)
  	args.first[:layout] = false if request.xhr? and args.first[:layout].nil?
	super
end

AJAX multiple updates to calling page without using RJS template

When a controller action is called via XHR (XmlHttpRequest), the action will look for a .rjs template first, then a .rhtml template if not available.

To skip using the .rjs template, include a render(:update) {|page| <block code> } call to perform updates.

  def toggle_showall
    render(:update) do |page|
      page[:fb_content].replace_html "just text? ripoff!"
      page[:flash_box].visual_effect :blind_down, :duration => 0.25
    end
  end


We use page as a hash to reference elements by id from the originating page.

page[:fb_content]


Then perform the updates to the element. Here we're replacing the contents of the element with id of "fb_content" with the string of text.
page[:fb_content].replace_html "just text? ripoff!"


You can render anything you could normally using a render call, example, some partial.
page[:fb_content].replace_html :partial => "shared/some_partial"


If the partial you're calling has instance vars you need to fill before, just include them before the render(:update) block and they'll be available to the partial during rendering.


Here we execute scriptaculous' Effect.BlindDown on element 'flash_box' with option of duration of .25 seconds.
page[:flash_box].visual_effect :blind_down, :duration => 0.25


There are plenty of other methods you can call on a page element. Refer to the Agile WebDev PDF for more details.