How to make an AJAX Postback with JavaScript

Recently, we were working on a project that required us to make an AJAX postback with a table cell (TD) onclick event. We were "forced" to do this because the webpage designer wanted the search results displayed in a table and the TD's had onmouseover, onmouseout and onmouseclick events. The way he designed it was very nice and we didn't want to change it because AJAX for .NET didn't natively support the TD click event.

We quickly searched the web for an answer and couldn't find anything. Over the past few months many others asked how to do it too, but nobody could provide an answer. It's really not that just need to be a little creative and think how AJAX works in ASP.NET.

In our project, we were binding location search results to a Repeater. In the onclick event, we added code to make a call to JavaScript function "makeAJAXPostback" and passed the ID. Originally, we tried to make a call to __doPostBack, but that forces a full page postback:

1<asp:Repeater ID="rptSearchResults" runat="server">
2    <ItemTemplate>
3        <table width="100%" border="0" cellpadding="0" cellspacing="4">
4            <tbody>
5                <tr>
6                    <td class="agentbox" onmouseover="style.backgroundColor='#e0e8f3';"
7 onclick="makeAJAXPostback('<%# DataBinder.Eval(Container.DataItem, "ID")%>')"> 8 <%# DataBinder.Eval(Container.DataItem, "DisplayName")%> 9 <br /> 10 <%# DataBinder.Eval(Container.DataItem, "Address1")%> 11 <br /> 12 <%# DataBinder.Eval(Container.DataItem, "City")%> 13 <br /> 14 <%# DataBinder.Eval(Container.DataItem, "StateIDCode")%> 15 <%# DataBinder.Eval(Container.DataItem, "Zip")%> 16 <br /> 17 <%# DataBinder.Eval(Container.DataItem, "Phone")%> 18 </td> 19 </tr> 20 </table> 21 </ItemTemplate> 22</asp:Repeater> 23
At the bottom of the page, we added a the "makeAJAXPostback" function.
We also added a hidden field and a hidden HTML submit button:

1            <input type="submit" id="btnTDClicked" name="btnTDClicked" style="display: none" />
2            <input type="hidden" id="hidTDClickID" name="hidTDClickID" />
3        </ContentTemplate>
4    </asp:UpdatePanel>
5    <script type="text/javascript">
6        function makeAJAXPostback(TDClickID)
7        {
8            document.forms[0].hidTDClickID.value = TDClickID;
9            document.forms[0];
10        }
11    </script>
When the TD cell is clicked, the "makeAJAXPostback" function is called, the ID is put in the hidden field and the hidden button is clicked. Because the AJAX Toolkit handles all form postbacks, the button click is automatically made via AJAX.

All that's left is to handle the postback on the server. In Page_Load, we simply check if the hidden field is populated and process accordingly:

1//Handle TD Clicked Event when user clicks search results2if (Request.Form["hidTDClickID"] != null &&
3    Request.Form["hidTDClickID"].ToString() != "")
4    TDClicked(int.Parse(Request.Form["hidTDClickID"].ToString()));