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 11-20 of 36 total

Test if called from XMLHttpRequest

if($_SERVER["HTTP_X_REQUESTED_WITH"] == 'XMLHttpRequest')
{
  // Called from XMLHttpRequest
}

AJAX file upload

Ever wanted to upload files using AJAX like in GMAIL, without reloading the page? Now you can. Cross browser method to upload files using AJAX in only 1Kb of code.
How to use AJAX file upload you can find on this script homepage - free code and tutorials website.

/**
*
*  AJAX IFRAME METHOD (AIM)
*  http://www.webtoolkit.info/
*
**/

AIM = {

	frame : function(c) {

		var n = 'f' + Math.floor(Math.random() * 99999);
		var d = document.createElement('DIV');
		d.innerHTML = '<iframe style="display:none" src="about:blank" id="'+n+'" name="'+n+'" onload="AIM.loaded(\''+n+'\')"></iframe>';
		document.body.appendChild(d);

		var i = document.getElementById(n);
		if (c && typeof(c.onComplete) == 'function') {
			i.onComplete = c.onComplete;
		}

		return n;
	},

	form : function(f, name) {
		f.setAttribute('target', name);
	},

	submit : function(f, c) {
		AIM.form(f, AIM.frame(c));
		if (c && typeof(c.onStart) == 'function') {
			return c.onStart();
		} else {
			return true;
		}
	},

	loaded : function(id) {
		var i = document.getElementById(id);
		if (i.contentDocument) {
			var d = i.contentDocument;
		} else if (i.contentWindow) {
			var d = i.contentWindow.document;
		} else {
			var d = window.frames[id].document;
		}
		if (d.location.href == "about:blank") {
			return;
		}

		if (typeof(i.onComplete) == 'function') {
			i.onComplete(d.body.innerHTML);
		}
	}

}

Ajax style radio buttons

Ajax radio buttons. update the page div when a radio button is pressed.

<div id="join">
        <p class="title">
      Sign-up
        </p>
   <% form_for :radio_join, :html => { :id => 'radio_join' } do %>
      <%= radio_button_tag :join_page, :member %> Member
      <%= radio_button_tag :join_page, :model %> Model
      <%= radio_button_tag :join_page, :photographer %> Photographer
    <% end -%>
<% form_for :user, @user, :url => {:action => 'save_free'} do |user_form| -%>
        <div class="info">
    <%= render :partial => 'common/user_form', :object => user_form %>
                <p class="alignright">
        <%= submit_tag 'JOIN', :class => 'inputSubmit' %>
                </p>
      <br />
      <br />
        </div>
  <% end -%>

     </div>
<%= observe_form :radio_join, :url => { :action => 'choose_page' }, :update => "join", :complete => "Element.show('join')", :frequency => "0.25" %>

Synchronous AJAX

// Snippet showing how to use synchronous AJAX

function getFile(url) {
  if (window.XMLHttpRequest) {              
    AJAX=new XMLHttpRequest();              
  } else {                                  
    AJAX=new ActiveXObject("Microsoft.XMLHTTP");
  }
  if (AJAX) {
     AJAX.open("GET", url, false);                             
     AJAX.send(null);
     return AJAX.responseText;                                         
  } else {
     return false;
  }                                             
}

var fileFromServer = getFile('http://somedomain.com/somefile.txt');

Dependant Dropdowns Using Ajax

This code demonstrates using ajax for dependant combos.The sample application
below has 2 combo boxes 1.country 2.city.
OnChange event on the country should populate the corresponding cities in the
city dropdown.

--------------------------------------------------------------------------------
ajaxscripting.js
--------------------------------------------------------------------------------

<script type="text/javascript">
var xmlHttp;
function createXMLHttpRequest() {
    if (window.ActiveXObject) {
        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
    } 
    else if (window.XMLHttpRequest) {
        xmlHttp = new XMLHttpRequest();
    }
}

function doRequestUsingGETCountry(url) {
   
    createXMLHttpRequest();
    queryString =   url ;
    queryString = queryString + "&selcountry="+document.forms[0].country.options[document.forms[0].country.selectedIndex].value;
    xmlHttp.onreadystatechange = handleStateChange;
    xmlHttp.open("GET", queryString, true);
    xmlHttp.send(null);
}

function handleStateChange() {
    if(xmlHttp.readyState == 4) {
        if(xmlHttp.status == 200) {
          parseResults();
        }
    }
}
function parseResults() {
            var responseText = document.createTextNode(xmlHttp.responseText);
            var returnElements=xmlHttp.responseText.split("||");
          //Process each of the elements 	
          for ( var i=0; i<returnElements.length; i++ ){
             
             if(returnElements[i]!="")
            {
             valueLabelPair = returnElements[i].split(";")
             document.getElementById('state').options.length= returnElements.length;     
             document.getElementById('state').options[i] = new Option(valueLabelPair[0], valueLabelPair[1]);
            } 
        }
}
function inc(filename)
{
var body = document.getElementsByTagName('body').item(0);
script = document.createElement('script');
script.src = filename;
script.type = 'text/javascript';
body.appendChild(script)
}

--------------------------------------------------------------------------------
dependantComboExample.jsp
--------------------------------------------------------------------------------
<%@page import="ajaxsample.SampleForm,java.util.*"%>
<%@include file="taglibs.jsp"%>
<%@include file="ajaxscripting.js"%>

<head>
</head>

<body onLoad="doRequestUsingGETCountry('/struts-ajax/DependantComboExample.do?');">

<html:form action="DependantComboExample.do" >

  <h1></h1>
  <table>
    <tbody>
        <tr>
            <td>Country</td>
              <td>
                <html:select property="country" name="inputForm" onchange="doRequestUsingGETCountry('/struts-ajax/DependantComboExample.do?');">
                    <html:options collection="countries" property="value" labelProperty="label"/>
                </html:select>
               </td>
               <td>
               <html:select property="state" name="inputForm" >
                    <html:options collection="states" property="value" labelProperty="label" />
                </html:select>                  
               </td>
        </tr>
    </tbody>
  </table>
  
</html:form>
</body>
</script>

------------------------------------------------------------------
GetAndPostExample
------------------------------------------------------------------


package ajaxsample;

import java.io.*;
import java.net.*;
import javax.servlet.*;
import javax.servlet.http.*;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import java.util.ArrayList;
import org.apache.struts.action.ActionServlet;
import org.apache.struts.util.LabelValueBean;

public class GetAndPostExample extends Action {
    
    ServletContext context = null;
    
    public void setServlet(ActionServlet servlet)
    {
        context =  servlet.getServletContext();
    }
   public ActionForward execute(ActionMapping mapping, ActionForm inForm, 
           HttpServletRequest request, HttpServletResponse response) throws Exception {
           response.setContentType("text/xml");

          String optionSelected = request.getParameter("selcountry");        
         //Build the response text
         
         SampleForm sform = (SampleForm)inForm;
         ArrayList countries = (ArrayList)context.getAttribute("countries");
         ArrayList states = (ArrayList)context.getAttribute("states");
         ArrayList newStates = new ArrayList();
         String responseText = "";
         //sending response text in the format label:value||label;value
         for(int i=0;i<states.size();i++)
         {
            LabelValueBean temp = (LabelValueBean)states.get(i);
            if(temp.getValue().startsWith(optionSelected))
            {
                    newStates.add(temp); 
                    responseText = temp.getLabel()+";"+temp.getValue()+"||"+responseText; 
            }
         }
         if(responseText.endsWith("||"))   //chop off the ending ||
         {
             responseText = responseText.substring(0, responseText.lastIndexOf("||"));
         }
         PrintWriter out = response.getWriter();
         out.println(responseText);
        //Close the writer
        out.close();
        return(mapping.findForward("content1"));
   }
  }
------------------------------------------------------------------
CacheServlet.java
------------------------------------------------------------------

package ajaxsample;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import java.io.IOException;
import org.apache.struts.util.LabelValueBean;
import java.util.*;
/**
 *
 * @author rupali_l
 */
public class CacheServlet extends HttpServlet {
    
    
    /** Creates a new instance of CacheServlet */
    public void init() throws ServletException {
   
      
        System.out.println("In do get of CacheServlet");
        ArrayList countries = new ArrayList(); 
        countries.add(new  LabelValueBean("India", "1" ));
        countries.add(new  LabelValueBean("U.S","2"));
        countries.add(new  LabelValueBean( "Australia","3"));
        
        ArrayList states = new ArrayList(); 
        states.add(new  LabelValueBean("Maharashtra","11"));
        states.add(new  LabelValueBean( "Delhi","12"));
        states.add(new  LabelValueBean("Goa","13"));
        states.add(new  LabelValueBean( "Newjersey","21"));
        states.add(new  LabelValueBean("NewYork","22"));
        states.add(new  LabelValueBean( "California","23"));
        states.add(new  LabelValueBean("Sydney","31"));
        getServletContext().setAttribute("countries", countries);
        getServletContext().setAttribute("states", states);
        
       
    }
        
    
    public void doGet(HttpServletRequest request ,HttpServletResponse response) throws ServletException,
    IOException
    {
        // request.getRequestDispatcher
    }       
            
    
}
------------------------------------------------------------------
web.xml
------------------------------------------------------------------


<web-app>
  <display-name>Struts Blank Application</display-name>
  
  <!-- Standard Action Servlet Configuration (with debugging) -->
  <servlet>
    <servlet-name>CacheServlet</servlet-name>
    <servlet-class>ajaxsample.CacheServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
  </servlet>

  
  <servlet>
    <servlet-name>action</servlet-name>
    <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
    <init-param>
      <param-name>config</param-name>
      <param-value>/WEB-INF/struts-config.xml</param-value>
    </init-param>
    <init-param>
      <param-name>debug</param-name>
      <param-value>2</param-value>
    </init-param>
    <init-param>
      <param-name>detail</param-name>
      <param-value>2</param-value>
    </init-param>
    <load-on-startup>2</load-on-startup>
  </servlet>

  <!-- Standard Action Servlet Mapping -->
  <servlet-mapping>
    <servlet-name>action</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>


  <!-- The Usual Welcome File List -->
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>


  <!-- Struts Tag Library Descriptors -->
  <taglib>
    <taglib-uri>/WEB-INF/struts-bean.tld</taglib-uri>
    <taglib-location>/WEB-INF/struts-bean.tld</taglib-location>
  </taglib>

  <taglib>
    <taglib-uri>/WEB-INF/struts-html.tld</taglib-uri>
    <taglib-location>/WEB-INF/struts-html.tld</taglib-location>
  </taglib>

  <taglib>
    <taglib-uri>/WEB-INF/struts-logic.tld</taglib-uri>
    <taglib-location>/WEB-INF/struts-logic.tld</taglib-location>
  </taglib>

  <taglib>
    <taglib-uri>/WEB-INF/struts-nested.tld</taglib-uri>
    <taglib-location>/WEB-INF/struts-nested.tld</taglib-location>
  </taglib>

  <taglib>
    <taglib-uri>/WEB-INF/struts-tiles.tld</taglib-uri>
    <taglib-location>/WEB-INF/struts-tiles.tld</taglib-location>
  </taglib>

</web-app>

struts-config.xml


<!-- ================================================ 
<struts-config>
<!-- ================================================

    <form-beans>
    
	<!-- <form-bean name="sampleForm" type="ajaxsample.SampleForm"/>
    -->
    
    <!-- sample form bean descriptor for an ActionForm-->
        <form-bean
            name="inputForm"
            type="ajaxsample.SampleForm"/>
 </form-bean>
    
    </form-beans>
 <action-mappings>
<action path="/DependantComboExample" type="ajaxsample.GetAndPostExample" 
    	name="inputForm" scope="request" validate="false" >
    	
    	<!-- Partial Ajax Content-->
    <forward name="content1" path="/dependantComboExample.jsp" />

</action-mappings>

</struts-config>




Simple Ajax

http = getHTTPObject();

function getHTTPObject(){
var xmlhttp;

/*@cc_on

@if (@_jscript_version >= 5)
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}catch(e){
try{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}catch(E){
xmlhttp = false;
}
}
@else
xmlhttp = false;
@end @*/

if(!xmlhttp && typeof XMLHttpRequest != 'undefined'){
try {
xmlhttp = new XMLHttpRequest();
}catch(e){
xmlhttp = false;
}
}

return xmlhttp;
}

function doMath(){
var url = "backend.php?op=" + document.getElementById('op').value;
url += "&num1=" + document.getElementById('num1').value;
url += "&num2=" + document.getElementById('num2').value;

http.open("GET", url, true);
http.onreadystatechange = handleHttpResponse;

http.send(null);
}

function handleHttpResponse(){
if(http.readyState == 4){
document.getElementById('answer').innerHTML = http.responseText;
}
}

Javascript Ajax Object

// Just a stub function we'll tell ajaxObject to call when it's done
// callback functions get responseText, and responseStat respectively
// in their arguments.
function fin(responseTxt,responseStat) {
  alert(responseStat+' - '+responseTxt);
}

// create a new ajaxObject, give it a url it will be calling and
// tell it to call the function "fin" when its got data back from the server.
var test1 = new ajaxObject('http://someurl.com/server.cgi',fin);
    test1.update();
		
// create a new ajaxObject, give it a url and tell it to call fin when it
// gets data back from the server.  When we initiate the ajax call we'll
// be passing 'id=user4379' to the server.		
var test2 = new ajaxObject('http://someurl.com/program.php',fin);
    test2.update('id=user4379');
		
// create a new ajaxObject but we'll overwrite the callback function inside
// the object to more tightly bind the object with the response hanlder.
var test3 = new ajaxObject('http://someurl.com/prog.py', fin);
    test3.callback = function (responseTxt, responseStat) {
      // we'll do something to process the data here.
      document.getElementById('someDiv').innerHTML=responseTxt;
    }
    test3.update('coolData=47&userId=user49&log=true');	
		
// create a new ajaxObject and pass the data to the server (in update) as
// a POST method instead of a GET method.
var test4 = new ajaxObject('http://someurl.com/postit.cgi', fin);
    test4.update('coolData=47&userId=user49&log=true','POST');	


function ajaxObject(url, callbackFunction) {
  var that=this;      
  this.updating = false;
  this.abort = function() {
    if (that.updating) {
      that.updating=false;
      that.AJAX.abort();
      that.AJAX=null;
    }
  }
  this.update = function(passData,postMethod) { 
    if (that.updating) { return false; }
    that.AJAX = null;                          
    if (window.XMLHttpRequest) {              
      that.AJAX=new XMLHttpRequest();              
    } else {                                  
      that.AJAX=new ActiveXObject("Microsoft.XMLHTTP");
    }                                             
    if (that.AJAX==null) {                             
      return false;                               
    } else {
      that.AJAX.onreadystatechange = function() {  
        if (that.AJAX.readyState==4) {             
          that.updating=false;                
          that.callback(that.AJAX.responseText,that.AJAX.status,that.AJAX.responseXML);        
          that.AJAX=null;                                         
        }                                                      
      }                                                        
      that.updating = new Date();                              
      if (/post/i.test(postMethod)) {
        var uri=urlCall+'?'+that.updating.getTime();
        that.AJAX.open("POST", uri, true);
        that.AJAX.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        that.AJAX.send(passData);
      } else {
        var uri=urlCall+'?'+passData+'&timestamp='+(that.updating.getTime()); 
        that.AJAX.open("GET", uri, true);                             
        that.AJAX.send(null);                                         
      }              
      return true;                                             
    }                                                                           
  }
  var urlCall = url;        
  this.callback = callbackFunction || function () { };
}

Making a simple XMLHTTP Request

// description of your code here
purpose : makes XMLHttpRequest
Requires : url



function makeRequest(url) {
        var http_request = false;
        url = url +  "?txt1=" + document.getElementById('first_no').value + '&' + "txt2=" + document.getElementById('second_no').value;
       
     if (window.XMLHttpRequest) { // Mozilla, Safari, ...
            http_request = new XMLHttpRequest();
            if (http_request.overrideMimeType) {
                http_request.overrideMimeType('text/xml');
                // See note below about this line
            }
        } else if (window.ActiveXObject) { // IE
            try {
                http_request = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {
                try {
                    http_request = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (e) {}
            }
        }

        if (!http_request) {
            alert('Giving up :( Cannot create an XMLHTTP instance');
            return false;
        }
        http_request.onreadystatechange = function() { alertContents(http_request); };
        http_request.open('GET', url, true );
        
        http_request.send(null);

    }

    function alertContents(http_request) {

        if (http_request.readyState == 4) {
            if (http_request.status == 200) {

              document.getElementById('spid').innerHTML = http_request.responseText ;

            } else {
                alert('There was a problem with the request.');

            }
        }

    }


FirstLast (real classes for Ajaxability)

I know CSS has the :first-child and :last-child pseudo classes. But :first-child is a part of CSS 2 and has poor browsers support and :last-child is a part of CSS 3 and that's not worth thinking about using yet. The idea is sound though, so I worked up this JavaScript method of getting the same effect.

One advantage of doing this in JavaScript rather than using CSS is that the classes will change if you reorder the child nodes with more JavaScript. In my case I'm using Scriptaculous sortables. Or to be more specific, I'm using a Ruby on Rails helper method to make something sortable through Scriptaculous:
<%= sortable_element 'image-list',
    :constraint => false,
    :url => { :action => 'sort', :issue_id => params[:issue_id] }
-%>


I've chosen to not make this script run unobtrusively. Most of it can go into a file and be included in the header or added to your own common JavaScript include file. To get it to run on a page you will need to include something like the below in each page.
<script type="text/javascript">
//<![CDATA[
    Event.onDOMReady(function(){FirstLast.go("image-list")});
    Ajax.Responders.register({
        onComplete: function(){FirstLast.go("image-list");}
   });
//]]>
</script>

I use the DOMReady extension for Prototype's Event object, but you can use any loader you want. The Ajax.Responders.register part reruns the script after a drag-and-drop operation (or any Ajax operation really).

Download Scriptaculous and Prototype.

var FirstLast = {
    go: function(el) {
        el = $(el);

        // Whitespace nodes need to be cleaned to get the intended effect
        var children = Element.cleanWhitespace(el).childNodes;

        // Return if there are not any children
        if (0 == children.length) return
        
        if (1 == children.length) {
            // Cheap shortcut if there is only 1 child node
            children[0].addClassName(this._firstChildClassName);
            children[0].addClassName(this._lastChildClassName);
        } else {
            for (var i = 0; i < children.length; i++) {
                switch (i) {
                    // First child
                    case 0:
                        children[i].addClassName(this._firstChildClassName);
                        children[i].removeClassName(this._lastChildClassName);
                        break;
                    // Last child
                    case children.length - 1:
                        children[i].removeClassName(this._firstChildClassName);
                        children[i].addClassName(this._lastChildClassName);
                        break;
                    // Every child other than the first or last
                    default:
                        children[i].removeClassName(this._firstChildClassName);
                        children[i].removeClassName(this._lastChildClassName);
                        break;  // I know it is unnecessary
                }
            }
        }
    },
    // Pseudo Private methods and attributes
    _firstChildClassName: "first",
    _lastChildClassName: "last"
};

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>
« Newer Snippets
Older Snippets »
Showing 11-20 of 36 total