Tag Archive for ajax

Only allow AJAX for a HTTP Request

// If the request did not come from AJAX, exit:
if($_SERVER['HTTP_X_REQUESTED_WITH'] !='XMLHttpRequest'){
	exit;
}

source

Detect Ajax

/* AJAX check  */
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
	/* special ajax here */
	die($content);
}

source

HTML5 Beginers Layout With Google Ajax Load

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <title>HTML5 Beginers Layout</title>
<script type="text/javascript" src="<a href="http://www.google.com/jsapi"></script>" >http://www.google.com/jsapi"></script></a>
<script type="text/javascript">
google.load("jquery", "1.4.2");
google.load("jqueryui", "1.8.2");
</script>
<!--[if lt IE 9]>
<script type="text/javascript" src="<a href="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>" >http://html5shiv.googlecode.com/svn/trunk/html5.js"></script></a>
<![endif]-->
</head>
<body>
    <header>
        <hgroup>
            <h1>Page Header</h1>
            <h2>Description May Go Here</h2>
        </hgroup>
    </header>

    <nav>
        <ul>
            <li><a href="#">Home</a></li>
            <li><a href="#">Contact</a></li>
        </ul>
    </nav>

    <article>
        <header>
            <h1>Article Header</h1>
            <time datetime="2010-05-05" pubdate>June 25th 2010</time>
        </header>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
        <section>
            <header>
                <h1>Section Header</h1>
            </header>
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
            <footer>
                <p>Section Footer</p>
            </footer>
        </section>
        <footer>
            Article Footer
        </footer>
    </article>

    <aside>
        <header>
            <h1>Siderbar Header</h1>
        </header>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
    </aside>

    <footer>
        Page Footer
    </footer>

</body>
</html>

source

Sharepoint Ajax List Data populater Example

function btnSubmitEntry_OnClick() {
   $('#contentLoading').show(); 
   var ourProperty = EscapeHtmlString($('#selProperty :selected').text());
   var ourAffectedUrl = EscapeHtmlString($('#selUrl :selected').text());
   var ourStagingUrl;
   
  if (ourAffectedUrl.indexOf('/') == 0) {
   		if (ourProperty.indexOf('MS.com') > -1) ourStagingUrl = "<a href="http://wwwstaging"" >http://wwwstaging"</a> + ourAffectedUrl;
   		else if (ourProperty.indexOf('<a href="http://')" >http://')</a> > -1) ourStagingUrl = "<a href="http://standards"" >http://standards"</a> + ourAffectedUrl;
   		else ourStagingUrl ="n/a";
   		}
   else if ((ourAffectedUrl == "new page") || (ourProperty == "talkstandards.com")) ourStagingUrl ="to be determined" ;
   else ourStagingUrl ="n/a"  ;
   
   var updateString = "<Batch OnError="Continue">"; 
   updateString += "<Method ID="1" Cmd="New">"; 
   updateString += "<Field Name="ID">1</Field>"; 
   //updateString += "<Field Name="Title">" + EscapeHtmlString($("#txtTitle").val()) + "</Field>";
   updateString += "<Field Name="Title">Bug or Change Request </Field>"; 
   updateString += "<Field Name="Property">" + ourProperty + "</Field>"; 
   updateString += "<Field Name="Property_x0020_Owner">" + getPropertyOwner($('#selProperty :selected').text()) + "</Field>"; 
   updateString += "<Field Name="URL_x0020_Affected">" + ourAffectedUrl + "</Field>"; 
   updateString += "<Field Name="The_x0020_Requester">" + EscapeHtmlString($("#txtAuthor").val()) + "</Field>";
   updateString += "<Field Name="staging_x0020_url">" + ourStagingUrl + "</Field>";
   updateString += "<Field Name="Description">" + EscapeHtmlString($("#txtDescript").val()) + "</Field>";
   updateString += "<Field Name="Priority_x0020_Level">" + EscapeHtmlString($('#selPriority :selected').text()) + "</Field>";
   updateString += "<Field Name="Type_x0020_of_x0020_Request">" + EscapeHtmlString($('#selType :selected').text()) + "</Field>";
   updateString += "<Field Name="Go_x0020_Live_x0020_Date">" + EscapeHtmlString($("#txtGoLiveDate").val()) + "</Field>";
   updateString += "<Field Name="Go_x0020_Live_x0020_Time">" + EscapeHtmlString($("#txtGoLiveTime").val()) + "</Field>";
   updateString += "<Field Name="PageSection">" + EscapeHtmlString($("#txtSection").val()) + "</Field>"; 
   


    
 
   updateString += "</Method>"; 
   updateString += "</Batch>";
   try { 
   UpdateListItems("Change Requests", updateString, callback_Submit); }
   catch (err) {
   
   alert(err.message);
   
   }
   }	
   

function callback_Submit(respObj, status) {
   var soapError = SoapErrorCheck(respObj); 
   if (soapError.length == 0) {
      if (respObj.xml.length > 0) {
      var rows = $("z:row", respObj);
      requestID = trim($(rows[0]).attr("ows_ID"))
      
      var editUrl  = $("a#attachLink").attr("href") + "?ID=" + requestID;
      var attachmentUrl = $("a#custom-popup").attr("href") + "?ID=" + requestID; 
      
       $("a#attachLink").attr("href", editUrl );
      
      $("a#custom-popup").attr("href", attachmentUrl );
      
         $('#submittalConfirmation').show(); 
         $('#requestForm').hide(); 
         $('#contentLoading').hide(); 
         }
      else {
         alert("Error updating request list. Try again and if the error continues please contact your administrator."); 
         }
      }
   else {
      alert("Error submitting your request: 
" + soapError); 
      }
   }

source

Simple Ajax Class

// Request class
Request = function(){
	Request = window.XMLHttpRequest?new XMLHttpRequest():window.ActiveXObject?new ActiveXObject("Microsoft.XMLHTTP"):false;
	Request.fn = function(fn){
		if(typeof fn=='string')return new Function(fn);
		if(typeof fn=='function')return fn;
		if(typeof fn=='undefined')return new Function();
	};
	Request.config = {
		'xml' : false,
		'404' : 'File not found'
	};
	
	Request.success = false;
	Request.loading = false;
	Request.error = false;
	
	Request.submit = function(obj){		
		if(Request){
			Request.onreadystatechange = function(){
				if(Request.status==200){
					if(Request.readyState==4){
						Response = Request.config['xml']?Request.responseXml:Request.responseText;
						if(Request.success){
							Request.fn(Request.success).call(this, Response, Request);
						} else {
							Request.fn(obj.success).call(this, Response, Request);
						}
					} else {
						if(Request.success){
							Request.fn(Request.loading).call(this, Request);
						} else {
							Request.fn(obj.loading).call(this, Request);
						}
					}
				} else {
					if(Request.success){
						Request.fn(Request.error).call(this, Request.config['404']);
					} else {
						Request.fn(obj.error).call(this, Request.config['404']);
					}
				};
			}
		
			Request.open("GET", obj.url, true);
			Request.send(null);
		} else obj.error.call(this, Request);
	};
	
	return Request;
};

// Eval code
var req = new Request;
req.submit({
	url : 'plik.xml',
	xml : false,
	success : function(res, req){
		document.getElementById('p2').innerHTML = res;
	},
	loading : function(){ console.log('loading...'); },
	error : function(err){ console.log(err); }
});

source

Google AJAX Libraries API

<script src="<a href="http://www.google.com/jsapi"></script>" >http://www.google.com/jsapi"></script></a>
<script>
  // Load jQuery - simply call it here, and name the version after it  
      google.load("jquery", "1.3.2");
</script>

source

Google CDN hosted jQuery with local fallback

<!-- jQuery Google CDN hsoted with local fallback, weird doc.write slashes explained here <a href="http://www.codehouse.com/javascript/articles/external/" >http://www.codehouse.com/javascript/articles/external/</a> -->

<script type="text/javascript" src="<a href="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>" >http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script></a>
<script>
if (typeof jQuery == 'undefined') {
document.write('<script src="', 'js/jquery-1.4.1.min.js', '" type="text/JavaScript"></script>');
}
</script>

source

Asynchronous ASP.Net Pages, AJAX Helper, WebRequest Passthrough

Main Class (AsyncCall.cs), place in App_Code directory or compile as a dll and place in the bin dirctory of the site:
-------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Net;
using System.Threading;
using System.IO;
using System.Collections.Specialized;

namespace AsyncStuff
{
	public static class AsyncCall
	{
		public sealed class AsyncState
		{
			internal const string QVARNAME = "ASYNCSession";

			public readonly Page CallingPage;
			internal readonly Uri Url;
			private HttpWebRequest _request;
			private HttpWebResponse _response;
			internal readonly SpecificFunction SpecificFunction;
			public readonly object[] Parameters;
			private string _text;
			internal byte[] FormContent;

			//cascaded constructor only (private)
			private AsyncState(Page page)
			{
				this.CallingPage = page;
				this.Url = GetAsyncUrl(page.Request.Url);
			}

			//off-page url
			internal AsyncState(Uri url, Page page, SpecificFunction specificFunction)
			{
				this.CallingPage = page;
				this.Url = GetAsyncUrl(url);
				this.SpecificFunction = specificFunction;
			}

			internal AsyncState(Page page, SpecificFunction specificFunction)
				: this(page)
			{
				this.SpecificFunction = specificFunction;
			}

			internal AsyncState(Page page, SpecificFunction specificFunction, params object[] parameters)
				: this(page, specificFunction)
			{
				this.Parameters = parameters;
			}

			private Uri GetAsyncUrl(Uri uri)
			{
				string url = uri.OriginalString;
				int start = url.IndexOf("?");
				if (start < 0)
				{
					start = url.Length;
					url = url.Insert(start++, "?");
				}
				else
				{
					start++;
					url = url.Insert(start, "&");
				}

				//timestamped query variable inserted to indicate that a page is running asychronously
				url = url.Insert(start, QVARNAME + "=" + DateTime.Now.ToString("MMddyyyyHHmmssffff"));
				return new Uri(url);
			}

			public HttpWebRequest Request
			{
				get { return this._request; }
				internal set { this._request = value; }
			}

			public HttpWebResponse Response
			{
				get { return this._response; }
				internal set { this._response = value; }
			}

			public string GetResponseText()
			{
				if (this._text == null)
				{
					this._text = "";
					if (this._response != null)
						this._text = (new StreamReader(this._response.GetResponseStream())).ReadToEnd();
				}
				if (this._text == "")
					return null;

				return this._text;
			}
		}

		/// <summary>
		/// A delegate function used to create a callback for the RunPageAsynchronously() function
		/// </summary>
		/// <param name="state">The state object that will be returned from the results of the asychronous call</param>
		public delegate void SpecificFunction(AsyncState state);

		/// <summary>
		/// Run an off-page url request as an asychronous request. (Note: this is a seperate session, so don't expect session variables to persist)
		/// </summary>
		/// <param name="url">Off-page URL which contents will be retreived asychronously</param>
		/// <param name="callingPage">The current System.Web.UI.Page object which is making the asychronous call (must implement IHttpAsyncHandler or use the [%@ Page Async="true"] directive)</param>
		/// <returns>true, if the page was able to run asynchronously (a value of false may indicate the %@ Page directive is not using Async="true"</returns>
		public static bool RunAsynchronously(string url, Page callingPage)
		{
			if (callingPage is IHttpAsyncHandler)
			{
				Uri absUrl = new Uri(url, UriKind.RelativeOrAbsolute);
				if (!absUrl.IsAbsoluteUri || absUrl.OriginalString.StartsWith("file"))
				{
					string resolve = callingPage.ResolveUrl(url);
					Uri pageUrl = callingPage.Request.Url;
					string newPath = pageUrl.OriginalString.Replace(pageUrl.PathAndQuery, resolve);
					absUrl = new Uri(newPath, UriKind.Absolute);

					string filePath = callingPage.MapPath(absUrl.AbsolutePath);
					FileInfo fi = new FileInfo(filePath);
					if (!fi.Exists)
						throw new Exception("File Not Found, requestsed relative path does not exist. Check the filename for spelling errors.");
				}
				AsyncState state = new AsyncState(absUrl, callingPage, new SpecificFunction(AfterOffPage));
				callingPage.AddOnPreRenderCompleteAsync(new BeginEventHandler(BeginAsyncOperation), new EndEventHandler(EndAsyncOperation), state);
				return true;
			}
			return false;
		}

		private static void AfterOffPage(AsyncState state)
		{
			if (state==null || state.Response == null || state.CallingPage==null || state.CallingPage.Response==null)
				return;

			//content rewrite (make calling page same as the page called)
			//requires IIS content rewrite pipline mode, so if exception then ignore
			try
			{
				state.CallingPage.Response.Headers.Clear();
				state.CallingPage.Response.Headers.Add(state.Response.Headers);
			}
			catch { }
			state.CallingPage.Response.ContentType = state.Response.ContentType;
			BinaryReader br = new BinaryReader(state.Response.GetResponseStream());
			int len = (int)state.Response.ContentLength;
			byte[] data = br.ReadBytes(len);
			state.CallingPage.Response.OutputStream.Write(data, 0, len);			
		
			state.CallingPage.Response.End();
		}

		/// <summary>
		/// Run the current page request as an asychronous request. (Note: this is a seperate session, so don't expect session variables to persist)
		/// </summary>
		/// <param name="callingPage">The current System.Web.UI.Page object to be processed (must implement IHttpAsyncHandler or use the [%@ Page Async="true"] directive)</param>
		/// <param name="specificFunction">A parameterless function to call on the async request page</param>
		/// <returns>true, if the page was able to run asynchronously (a value of false may indicate the %@ Page directive is not using Async="true"</returns>
		public static bool RunAsynchronously(Page callingPage, SpecificFunction specificFunction)
		{
			if ((callingPage is IHttpAsyncHandler) && !IsRunningAsync(callingPage))
			{
				AsyncState state = new AsyncState(callingPage, specificFunction);
				callingPage.AddOnPreRenderCompleteAsync(new BeginEventHandler(BeginAsyncOperation), new EndEventHandler(EndAsyncOperation), state);
				return true;
			}
			return false;
		}

		/// <summary>
		/// Run the current page request as an asychronous request. (Note: this is a seperate session, so don't expect session variables to persist)
		/// </summary>
		/// <param name="callingPage">The current System.Web.UI.Page object to be processed (must implement IHttpAsyncHandler or use the [%@ Page Async="true"] directive)</param>
		/// <param name="specificFunction">A function to call on the async request page</param>
		/// <param name="parameters">The parameters to pass to the specific function</param>
		/// <returns>true, if the page was able to run asynchronously (a value of false may indicate the %@ Page directive is not using Async="true"</returns>
		public static bool RunAsynchronously(Page callingPage, SpecificFunction specificFunction, params object[] parameters)
		{
			if ((callingPage is IHttpAsyncHandler) && !IsRunningAsync(callingPage))
			{
				AsyncState state = new AsyncState(callingPage, specificFunction, parameters);
				callingPage.AddOnPreRenderCompleteAsync(new BeginEventHandler(BeginAsyncOperation), new EndEventHandler(EndAsyncOperation), state);
				return true;
			}
			return false;
		}

		/// <summary>
		/// Tests to see if the page is in is asynchronous cycle of an asynchronous request made from the RunPageAsynchronously function
		/// </summary>
		/// <param name="page">The page to check for sychronicity</param>
		/// <returns>true if in the asychronous cycle</returns>
		public static bool IsRunningAsync(Page page)
		{
			return (page.Request.QueryString[AsyncState.QVARNAME] != null);
		}

		private static IAsyncResult BeginAsyncOperation(object sender, EventArgs e, AsyncCallback cb, object stateObj)
		{
			if (stateObj is AsyncState)
			{
				AsyncState state = (AsyncState)stateObj;
				state.Request = (HttpWebRequest)HttpWebRequest.Create(state.Url);
				
				//copy relevant header information
				state.Request.Accept = GetTextList<string>(state.CallingPage.Request.AcceptTypes, ", ", true);
				state.Request.AllowAutoRedirect = true;
				state.Request.AllowWriteStreamBuffering = true;
				state.Request.ContentType = state.CallingPage.Request.ContentType + "; " + state.CallingPage.Request.ContentEncoding.WebName;
				state.Request.Method = state.CallingPage.Request.RequestType;
				state.Request.Referer = state.CallingPage.Request.UrlReferrer.OriginalString;
				
				//copy cookies
				if (state.CallingPage.Request.Cookies.Count > 0)
				{
					state.Request.CookieContainer = new CookieContainer();
					List<string> excludedCookies = new List<string> { "ASP.NET_SessionId" };
					foreach (string key in state.CallingPage.Request.Cookies.Keys)
					{
						if (!excludedCookies.Contains(key, StringComparer.CurrentCultureIgnoreCase))
						{
							HttpCookie cookie = state.CallingPage.Request.Cookies[key];
							Cookie copy = new Cookie(cookie.Name, cookie.Value, state.Url.AbsolutePath, state.Url.Host);
							state.Request.CookieContainer.Add(copy);
						}
					}
				}
				
				//copy form variables
				if (state.CallingPage.Request.Form.Count > 0 && state.Request.Method.Equals("POST", StringComparison.CurrentCultureIgnoreCase))
				{
					string pairs = GetTextDictionary(state.CallingPage.Request.Form, "=", "&", true);					
					state.FormContent = state.CallingPage.Request.ContentEncoding.GetBytes(pairs);
					state.Request.ContentLength = state.FormContent.Length;
					state.Request.BeginGetRequestStream(EndRequestStreamCallback, state);
				}

				return state.Request.BeginGetResponse(cb, stateObj);
			}
			return null;
		}

		private static void EndRequestStreamCallback(IAsyncResult ar)
		{
			if (ar.AsyncState is AsyncState)
			{
				AsyncState state = (AsyncState)ar.AsyncState;				
				BinaryWriter sw = new BinaryWriter(state.Request.EndGetRequestStream(ar));
				sw.Write(state.FormContent, 0, state.FormContent.Length);
				sw.Close();
			}
		}

		private static void EndAsyncOperation(IAsyncResult ar)
		{
			if (ar.AsyncState is AsyncState)
			{
				AsyncState state = (AsyncState)ar.AsyncState;
				if (state.Request != null)
				{
					try { state.Response = (HttpWebResponse)state.Request.EndGetResponse(ar); }
					catch (Exception ex) { throw new Exception("WebRequest Error. Remember that asynchronous calls are made from the server and not the client, so any routing done on the client (say...to a testing server) will not be in effect with this request.", ex); };

					if (state.SpecificFunction != null)
					{
						object target = state.SpecificFunction.Target;
						if (target == null)
							target = state.CallingPage;
						try { state.SpecificFunction.Method.Invoke(target, new object[] { state }); }
						catch (Exception ex) { throw new Exception("An error occured in the SpecificFunction supplied, the debug thread is not attached to the function invoked, therefore further debug information is unavailable.", ex); }
					}
				}
			}
		}

		private static string GetTextList<I>(IEnumerable<I> list, string separator, bool urlEncode)
		{			
			System.Text.StringBuilder sb = new System.Text.StringBuilder();
			int index = 0;
			foreach (I item in list)
			{
				if (index > 0)
					sb.Append(separator);				
				if (urlEncode)				
					sb.Append(HttpUtility.UrlPathEncode(item.ToString()));
				else
					sb.Append(item.ToString());
				index++;
			}
			string ret = sb.ToString();
			sb.Length = 0; //destroy memory
			return ret;
		}

		private static string GetTextDictionary<K, V>(IDictionary<K, V> dictionary, string equality, string separator, bool urlEncode)
		{
			System.Text.StringBuilder sb = new System.Text.StringBuilder();
			int index = 0;
			foreach (K key in dictionary.Keys)
			{
				V value = dictionary[key];
				if (index > 0)
					sb.Append(separator);
				if (urlEncode)
					sb.Append(HttpUtility.UrlPathEncode(key.ToString()));
				else
					sb.Append(key.ToString());
				sb.Append(equality);
				if (urlEncode)
					sb.Append(HttpUtility.UrlPathEncode(value.ToString()));
				else
					sb.Append(value.ToString());

				index++;
			}
			string ret = sb.ToString();
			sb.Length = 0; //destroy memory
			return ret;
		}

		private static string GetTextDictionary(NameValueCollection dictionary, string equality, string separator, bool urlEncode)
		{
			System.Text.StringBuilder sb = new System.Text.StringBuilder();
			int index = 0;
			foreach (string key in dictionary.Keys)
			{
				string value = dictionary[key];
				if (index > 0)
					sb.Append(separator);
				if (urlEncode)
					sb.Append(HttpUtility.UrlPathEncode(key.ToString()));
				else
					sb.Append(key.ToString());
				sb.Append(equality);
				if (urlEncode)
					sb.Append(HttpUtility.UrlPathEncode(value.ToString()));
				else
					sb.Append(value.ToString());
				index++;
			}
			string ret = sb.ToString();
			sb.Length = 0; //destroy memory
			return ret;
		}



	}
}

Page Example (AsyncPage.aspx):
-------------------------------------------------------------------------------
<%@ Page Async="true" Language="C#" AutoEventWireup="true" CodeFile="AsyncPage.aspx.cs" Inherits="AsyncPage" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "<a href="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">" >http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"></a>

<html xmlns="<a href="http://www.w3.org/1999/xhtml">" >http://www.w3.org/1999/xhtml"></a>
<head runat="server">
    <title></title>
    <script type="text/javascript">
    	function AJAXCall(url, callBack, postData) {
    		//setup the callback
    		var out = callBack;
    		if (!out) {
    			out = function(text) { return; }
    		}

    		//setup the request
    		var request = null;
    		if (window.XMLHttpRequest)
    			request = new XMLHttpRequest();
    		else if (window.ActiveXObject)
    			request = new ActiveXObject("Microsoft.XMLHTTP");
    		else
    			return false;

    		//true for async..
    		request.open("POST", url, true);

    		//setup the handle of the request when the status changes
    		request.onreadystatechange = function() {
    			if (request && request.readyState == 4) {
    				//if (request.status == 200)
    				out(request.responseText);

    			}
    		}
    		//setup the request headers
    		request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

    		//send the request
    		if (postData)
    			request.send(postData);
    		else
    			request.send("");
    	}

    	function callback(data) {
    		alert('got here: ' + data);
    	}

    	function button1() {
    		AJAXCall("AsyncPage.aspx?LongFunction=1", callback, "testing=1");
    	}   	

    	function button2() {
    		AJAXCall("AsyncPage.aspx?ShortFunction=1", callback, "testing=1");
    	}

    	function button3() {
    		AJAXCall("AsyncPage.aspx?UrlFunction=1", callback, "testing=1");
    	}

    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
		<asp:Label ID="lbl1" runat="server" />
		<input type="button" id="testbutton1" value="TestLong" onclick="javascript:button1();" style="width:100px;Height:25px;" />
		<input type="button" id="testbutton2" value="TestShort" onclick="javascript:button2();" style="width:100px;Height:25px;" />
		<input type="button" id="testbutton3" value="TestUrl" onclick="javascript:button3();" style="width:100px;Height:25px;" />
    </div>
    </form>
</body>
</html>

Code Behind (AsyncPage.aspx.cs):
-------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.IO;
using System.Threading;
using AsyncStuff;

public partial class AsyncPage : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {		
		if (AsyncCall.IsRunningAsync(Page))			
			CalledAsync(); //function is run when a page calls itself asychronously

		//a query variable triggers this page to run a different async function (use AJAX Call to this same url with this query variable)
		//these are single-run checked already, so you don't have to worry about running them more than once
		if (Request.QueryString["LongFunction"] != null)		
			AsyncCall.RunAsynchronously(Page, AfterLong, "Long call");

		if (Request.QueryString["ShortFunction"] != null)
			AsyncCall.RunAsynchronously(Page, AfterShort);

		if (Request.QueryString["UrlFunction"] != null)
			AsyncCall.RunAsynchronously("/AsyncTest.aspx?test=1", Page);
				
		//Normal Page load		
		lbl1.Text = "Just sitting here";
    }

	//this stuff called on the async thread
	protected void CalledAsync()
	{
		//stuff done during async
		
		if (Request.QueryString["LongFunction"]!=null)
		{
			//crunch some numbers to waste some time
			for(int i = 1; i<565535; i++)
			{
				decimal num = (decimal)DateTime.Now.Millisecond * (decimal)(new Random(DateTime.Now.Millisecond)).NextDouble();
				num += num;
			}
			Response.Write("Success");
		}
		else if (Request.QueryString["ShortFunction"] != null)
		{
			Response.Write("Short Call Was Run");
		}

		Response.End(); //do not show regular page contents
	}

	//this stuff called on the page thread after the async call returns
	protected void AfterLong(AsyncCall.AsyncState state)
	{
		//this is an example of using the response stream directly, you can use state.GetResponseText() to accomplish this same thing
		StreamReader sr = new StreamReader(state.Response.GetResponseStream());
		string pageContent = sr.ReadToEnd();
		if (pageContent.Contains("Success"))		
			Response.Write(state.Parameters[0].ToString());
		else		
			Response.Write("Failure");

		Response.End();
	}

	//this stuff called on the page thread after the async call returns
	protected void AfterShort(AsyncCall.AsyncState state)	
	{		
		string text = state.GetResponseText();
		if (text!=null)
			Response.Write(text);
		Response.End();
	}
}

source

Drupal Views AJAX Reset Button for Exposed Filters in

function CUSTOM_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'views_exposed_form') {
        $form['reset'] = array(
           '#type' => 'markup',
           '#value' => '<input '. drupal_attributes(array('type' => 'button', 'value' => t('Reset') )) .'onclick="javascript:$(this.form).clearForm();$(this.form).submit();" class="form-submit" />',
    );
    }
}

source

1 Ajax Code

function loadBom(sort, order) {
	      if (typeof sort == 'undefined')
	        sort = "";
	        
	      if (typeof order == 'undefined')
	        order = "";
	
			new Ajax.Request(
			'./manuModel_Req.aspx',
			{ 
				method:'post', 
				onCreate: function(){
				}, 
				onComplete: function(){
				},
				onSuccess: function(transport){ 
					//Handle Successful Response 
					
					var obj = transport.responseText.evalJSON();
				    handleLoadBOM(obj);
					
				},
				parameters: {
				requestType:"loadBom",
				PageIndex:curPage['bom'],
				column:sort,
				direction:order,
				filter: "retain filter"
							
				},
				onException: function(transport,ex){
					//Turn Error Indicator On
					//Javascript Exception
					_sendErr("Unable to Load Inventory BOM on Manu/Model Page. (loadBom)", transport.status, "manuModel.js");
					$('BomResults').innerHTML = "<span style="color: red">Error:  " + transport.status + "</span>";
				},
				on406: function(transport){
					//Turn Error Indicator On
					//Server Error
					_sendErr("Manu/Model Page - Error 406. (loadBom)", transport.status, "manuModel.js");
					$('BomResults').innerHTML = "<span style="color: red">Error:  " + transport.status + "</span>";
				}
			}
		);	
	
}

source