code_junkie

AJAX - How to Pass value back to server

Nov 10th, 2011
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 7.76 KB | None | 0 0
  1. <html xmlns="http://www.w3.org/1999/xhtml" >
  2. <head runat="server">
  3. <title>Untitled Page</title>
  4. <script type="text/javascript" src="AjaxHelper.js"></script>
  5. </head>
  6. <body>
  7. <form id="form1" runat="server">
  8. <div>
  9. <asp:TextBox ID="txtSearchValue" runat="server"></asp:TextBox>
  10. <input id="btnSearch" type="button" value="Search by partial full name" onclick="doSearch()"/>
  11.  
  12. <igtbl:ultrawebgrid id="uwgUsers" runat="server"
  13. //infragistics grid crap
  14. </igtbl:ultrawebgrid>--%>
  15. </div>
  16. </form>
  17. </body>
  18. </html>
  19.  
  20. //this is tied to the button click. It takes care of input cleanup and calling the AJAX method
  21. function doSearch(){
  22. var eleVal;
  23. var eleBtn;
  24. eleVal = document.getElementById('txtSearchValue').value;
  25. eleBtn = document.getElementById('btnSearch');
  26. eleVal = trim(eleVal);
  27. if (eleVal.length > 0) {
  28. eleBtn.value = 'Searching...';
  29. eleBtn.disabled = true;
  30. refreshGridData(eleVal);
  31. }
  32. else {
  33. alert("Please enter a value to search with. Unabated searches are not permitted.");
  34. }
  35. }
  36.  
  37. //This is the function that will go out and get the data and call load the Grid on AJAX call
  38. //return.
  39. function refreshGridData(searchString){
  40.  
  41. if (searchString =='undefined'){
  42. searchString = "";
  43. }
  44.  
  45. var xhr;
  46. var gridData;
  47. var url;
  48.  
  49. url = "DefaultHandler.ashx?partialUserFullName=" + escape(searchString);
  50. xhr = GetXMLHttpRequestObject();
  51.  
  52. xhr.onreadystatechange = function() {
  53. if (xhr.readystate==4) {
  54. gridData = eval(xhr.responseText);
  55. if (gridData.length > 0) {
  56. //clear and fill the grid
  57. clearAndPopulateGrid(gridData);
  58. }
  59. else {
  60. //display appropriate message
  61. }
  62. } //if (xhr.readystate==4) {
  63. } //xhr.onreadystatechange = function() {
  64.  
  65. xhr.open("GET", url, true);
  66. xhr.send(null);
  67. }
  68.  
  69. //this does the grid clearing and population, and enables the search button when complete.
  70. function clearAndPopulateGrid(jsonObject) {
  71.  
  72. var grid = igtbl_getGridById('uwgUsers');
  73. var eleBtn;
  74. eleBtn = document.getElementById('btnSearch');
  75.  
  76. //clear the rows
  77. for (x = grid.Rows.length; x >= 0; x--) {
  78. grid.Rows.remove(x, false);
  79. }
  80.  
  81. //add the new ones
  82. for (x = 0; x < jsonObject.length; x++) {
  83. var newRow = igtbl_addNew(grid.Id, 0, false, false);
  84. //the cells should not be referenced by index value, so a name lookup should be implemented
  85. newRow.getCell(0).setValue(jsonObject[x][1]);
  86. newRow.getCell(1).setValue(jsonObject[x][2]);
  87. newRow.getCell(2).setValue(jsonObject[x][3]);
  88. }
  89.  
  90. grid = null;
  91.  
  92. eleBtn.disabled = false;
  93. eleBtn.value = "Search by partial full name";
  94. }
  95.  
  96.  
  97. // this function will return the XMLHttpRequest Object for the current browser
  98. function GetXMLHttpRequestObject() {
  99.  
  100. var XHR; //the object to return
  101. var ua = navigator.userAgent.toLowerCase(); //gets the useragent text
  102. try
  103. {
  104. //determine the browser type
  105. if (!window.ActiveXObject)
  106. { //Non IE Browsers
  107. XHR = new XMLHttpRequest();
  108. }
  109. else
  110. {
  111. if (ua.indexOf('msie 5') == -1)
  112. { //IE 5.x
  113. XHR = new ActiveXObject("Msxml2.XMLHTTP");
  114. }
  115. else
  116. { //IE 6.x and up
  117. XHR = new ActiveXObject("Microsoft.XMLHTTP");
  118. }
  119. } //end if (!window.ActiveXObject)
  120.  
  121. if (XHR == null)
  122. {
  123. throw "Unable to instantiate the XMLHTTPRequest object.";
  124. }
  125. }
  126. catch (e)
  127. {
  128. alert("This browser does not appear to support AJAX functionality. error: " + e.name
  129. + " description: " + e.message);
  130. }
  131. return XHR;
  132. } //end function GetXMLHttpRequestObject()
  133.  
  134. function trim(stringToTrim){
  135. return stringToTrim.replace(/^ss*/, '').replace(/ss*$/, '');
  136. }
  137.  
  138. Imports System.Web
  139. Imports System.Web.Services
  140. Imports System.Data
  141. Imports System.Data.SqlClient
  142.  
  143. Public Class DefaultHandler
  144. Implements System.Web.IHttpHandler
  145.  
  146. Private Const CONN_STRING As String = "Data Source=;Initial Catalog=;User ID=;Password=;"
  147.  
  148. Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
  149.  
  150. context.Response.ContentType = "text/plain"
  151. context.Response.Expires = -1
  152.  
  153. Dim strPartialUserName As String
  154. Dim strReturnValue As String = String.Empty
  155.  
  156. If context.Request.QueryString("partialUserFullName") Is Nothing = False Then
  157. strPartialUserName = context.Request.QueryString("partialUserFullName").ToString()
  158.  
  159. If String.IsNullOrEmpty(strPartialUserName) = False Then
  160. strReturnValue = SearchAndReturnJSResult(strPartialUserName)
  161. End If
  162. End If
  163.  
  164. context.Response.Write(strReturnValue)
  165.  
  166. End Sub
  167.  
  168.  
  169. Private Function SearchAndReturnJSResult(ByVal partialUserName As String) As String
  170.  
  171. Dim strReturnValue As New StringBuilder()
  172. Dim conn As SqlConnection
  173. Dim strSQL As New StringBuilder()
  174. Dim objParam As SqlParameter
  175. Dim da As SqlDataAdapter
  176. Dim ds As New DataSet()
  177. Dim dr As DataRow
  178.  
  179. 'define sql
  180. strSQL.Append(" SELECT ")
  181. strSQL.Append(" [id] ")
  182. strSQL.Append(" ,([first_name] + ' ' + [last_name]) ")
  183. strSQL.Append(" ,[email] ")
  184. strSQL.Append(" FROM [person] (NOLOCK) ")
  185. strSQL.Append(" WHERE [last_name] LIKE @lastName")
  186.  
  187. 'clean up the partial user name for use in a like search
  188. If partialUserName.EndsWith("%", StringComparison.InvariantCultureIgnoreCase) = False Then
  189. partialUserName = partialUserName & "%"
  190. End If
  191.  
  192. If partialUserName.StartsWith("%", StringComparison.InvariantCultureIgnoreCase) = False Then
  193. partialUserName = partialUserName.Insert(0, "%")
  194. End If
  195.  
  196. 'create the oledb parameter... parameterized queries perform far better on repeatable
  197. 'operations
  198. objParam = New SqlParameter("@lastName", SqlDbType.VarChar, 100)
  199. objParam.Value = partialUserName
  200.  
  201. conn = New SqlConnection(CONN_STRING)
  202. da = New SqlDataAdapter(strSQL.ToString(), conn)
  203. da.SelectCommand.Parameters.Add(objParam)
  204.  
  205. Try 'to get a dataset.
  206. da.Fill(ds)
  207. Catch sqlex As SqlException
  208. 'Throw an appropriate exception if you can add details that will help understand the problem.
  209. Throw New DataException("Unable to retrieve the results from the user search.", sqlex)
  210. Finally
  211. If conn.State = ConnectionState.Open Then
  212. conn.Close()
  213. End If
  214. conn.Dispose()
  215. da.Dispose()
  216. End Try
  217.  
  218. 'make sure we have a return value
  219. If ds Is Nothing OrElse ds.Tables(0) Is Nothing OrElse ds.Tables(0).Rows.Count <= 0 Then
  220. Return String.Empty
  221. End If
  222.  
  223. 'This converts the table into JS array.
  224. strReturnValue.Append("[")
  225.  
  226. For Each dr In ds.Tables(0).Rows
  227. strReturnValue.Append("['" & CStr(dr("username")) & "','" & CStr(dr("userfullname")) & "','" & CStr(dr("useremail")) & "'],")
  228. Next
  229.  
  230. strReturnValue.Remove(strReturnValue.Length - 1, 1)
  231. strReturnValue.Append("]")
  232.  
  233. 'de-allocate what can be deallocated. Setting to Nothing for smaller types may
  234. 'incur performance hit because of a forced allocation to nothing before they are deallocated
  235. 'by garbage collection.
  236. ds.Dispose()
  237. strSQL.Length = 0
  238.  
  239. Return strReturnValue.ToString()
  240.  
  241. End Function
  242.  
  243.  
  244. ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
  245. Get
  246. Return False
  247. End Get
  248. End Property
  249.  
  250. End Class
Add Comment
Please, Sign In to add comment