So I’m trying to load some returned html from an .aspx page but a click event needs to fire before it doing some stuff that the AJAX request depends upon. More specifically, I’m doing this. When a user types in a text field this function is run…
function KeyPress() { $('#' + HiddenButtonId).click(); $('#test').load('TempJumpToAJAX.aspx'); }
then $(‘#’ + HiddenButtonId).click(); does sets some session data in a code behind file. Specifically…
Session['SearchText'] = Search.Text;
then, $(‘#test’).load(‘TempJumpToAJAX.aspx’); calls that .aspx page that returns a newly built select box…
Response.Expires = -1; StringBuilder builder = new StringBuilder(); builder.Append('<select id=\'testListId\' name=\'testList\' size=\'4\' style=\'width:200px;\'>'); builder.Append('<option>'); builder.Append(Session['SearchText']); builder.Append('</option>'); builder.Append('</select>'); Response.ContentType = 'text/HTML'; Response.Write(builder.ToString()); Response.End();
The problem is, the order seems to be screwed up it tries to append the Session[‘SearchText’] first, then runs the code that the click event runs. So it functions more like this…
function KeyPress() { $('#test').load('TempJumpToAJAX.aspx'); $('#' + HiddenButtonId).click(); }
Where the commands are reversed. So what in effect happens is the session variable has an empty string as opposed to what the user typed in the text box. What’s odd to me is that it doesn’t seem like it should have an empty string, it seems like it should have nothing since the session variable has not been initialized to anything at this point. I really have no idea what’s happening. Chalk it up to inexperience I guess. Any ideas?
You are mixing technologies here. The hiddenButtonID click event is trying to do a full postback for the page, whereas the AJAX call will not do a postback. There is no reason to do a post back and then follow it up with an AJAX call. The point of AJAX is to eliminate the need to postback the page and instead just reload a small amount of the HTML on the page using a small callback to the server. Instead of accessing the Search Textbox text in the HiddenButtonID click event handler you should be passing that data to the Server in the AJAX call parameters.
The following client side script should do this.
In this code you are getting the ID of the search textbox and then using jQuery to retrieve the value of that text box. This will get passed to the TempJumpToAJAX.aspx page as POST variable called ‘searchText’. You should be able access this data by accessing the Request[‘searchText’] variable in the ‘TempJumpToAJAX.aspx’ page.