AJAX is a hot topic right now and I didn't see any FAQ's on it in this forum so I thought I would show you how I'm implementing AJAX functionality on one of my sites.
So let's begin...
First create a simple web page with a few labels, a textbox and a button on it.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head id="head1" runat="server"> <title>Untitled Page</title>
var Command = "1:" + document.getElementById('txtInput').value; var context = new Object(); context.CommandName = "GetDetails"; window.status="Getting Details. Please wait...";
//This is where the "magic happens" //In the page load event we are going to register this script <%=callbackString %> }
//Splitting the string returned by the server SplitResults = result.split("| |");
Imports System Imports System.Web Imports System.Data
Partial Class Test Inherits System.Web.UI.Page Implements ICallbackEventHandler
#Region "AJAX Variables"
'Since the ICallBackEventHandler uses two functions we need a page-level variable so that we can return the string Dim results As String
'We need this so that we can register the string in the .aspx page from the page_load event Public callbackString As String
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load If Not Page.IsPostBack Then 'Adding the script for AJAX callbackString = Page.ClientScript.GetCallbackEventReference(Me, "Command", _ "CallBackHandler", "context", "onError", False)
End If End Sub
#Region "AJAX Events"
Public Sub RaiseCallbackEvent(ByVal eventArgument As String) Implements System.Web.UI.ICallbackEventHandler.RaiseCallbackEvent
Dim myString As New StringBuilder
With myString 'Let's get what we passed over first and return it .Append(eventArgument.Substring(eventArgument.IndexOf(":") + 1))
'setting the result page-level variable results = myString.ToString Else 'If we had another calling JS function we could put it here results = "New Function that we haven't created yet..." End If
#End Region End Class
And finally a few things to keep in mind.
4) The page_load will always get fired (even when using AJAX), so be aware of what you are doing there.
EDIT: I has come to my attention that I am slightly mistaken when I say that you can only return strings. You can also access XML files, but that is beyond the scope of this FAQ.