Button Click Event via Ajax With jQuery
In this post you will see how easy you can simulate button click event via ajax and this way call some ASP.NET server side method. There are number of scenarios in which this trick can be useful but for me the most appealing one are asynchronous autosaves. You have seen it in number of places for sure – basically whenever you give user an option to enter long piece of content, it’s a good practice to implement autosave, just in case, to prevent user’s content from disappearing because of browser crash or session timeout.
Okey, so here is an example how to get asynchronous autosaves working.
Step 1 – Get HTML ready
HTML is very straightforward, all you need is a textarea and a button. Of course you don’t need any button to have autosaves working, button will be used to save final version.
<h3>This is AutoSave demo!</h3> <div> <textarea id="ContentTextarea" cols="50" rows="10"><%=HttpContext.Current.Session["UserContent"]%></textarea> <br /> <button id="SaveContentButton">Save</button> <span id="autosaveUpdates"></span> </div>
There are two additional elements:
- span autosaveUpdates – this is where I will show updates to a user, it’s nice to inform that everything went fine and autosave actually works
- server side call to HTTP Session – I’m going to keep autosaved content in HTTP session, this is definitely not a production viable option, but for this example it will work
Step 2 – ASP.NET method which saves data
There are two things which you need to do to make your ASP.NET method available for jQuery and Ajax calls:
- method has to be public and static,
- and you need to add [WebMethod] attribute
Here is an example with very basic code which stores content in HTTP Session:
[WebMethod]
public static void SaveContent(string content, bool autosave)
{
if (autosave) {
HttpContext.Current.Session["UserContent"] = content;
}
else {
// TODO save data to a database
HttpContext.Current.Session["UserContent"] = String.Empty;
}
}
Step 3 – Button Click Event via Ajax
Before going to autosave functionality, I will show you how to call button click even via ajax with jQuery. So firstly, this is the function which will call ASP.NET method (from step 2):
function SaveDataViaAjax(autosaveMode) {
$("#autosaveUpdates").html("Saving ... ");
methodURL = "/AutoSave.aspx/SaveContent";
parameters = "{'content':'" + $("#ContentTextarea").val() + "', 'autosave':'" + autosaveMode + "'}";
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: methodURL,
data: parameters,
dataType: "json",
async: true,
success: function (data) {
if (autosaveMode) {
$("#autosaveUpdates").html("Autosave at " + Date().toLocaleString());
}
else {
$("#autosaveUpdates").html("Data have been saved at " + Date().toLocaleString());
}
},
error: function (result) {
alert("Due to unexpected errors we were unable to load data");
}
});
};
This function will be used to save data after manually clicking on the button and also to autosave content. A few words of explanation:
- URL to the ASPX page and method is: ‘/AutoSave.aspx/SaveContent’
- I need to pass two parameters as this is exactly what is expected by SaveContent() method – content and autosave
- $(“ContentTextarea”).val() returns value of textarea.
- $.ajax() method is responsible for all the ajax calls mechanics.
- please note that ajax() function is configured to make a asynchronous call, hence user interface won’t be blocked even in case when server will need a few seconds to respond.
- success function will be invoked when entire ajax call went fine and error in other case.
- I use simple jQuery selectors to find relevant tags.
I hope that the rest is self-explanatory. If not – let me know!
Now, we need to set this function to be called after clicking on the button, this code will do it:
$(document).ready(function () {
$("#SaveContentButton").click(function (event) {
SaveDataViaAjax(false)
event.preventDefault();
});
});
Step 4 – Autosaves with jQuery
And final step where I just need to do 2 things
- Define AutoSave function
- Tell Java Script to call the AutoSave function every 5 seconds
And here is code which will do all of that:
$(document).ready(function () {
window.setInterval(Autosave, 5000)
});
function Autosave() {
SaveDataViaAjax(true);
}
And this is it, it all together should work like a charm
Essential here is usage of setInterval() function which takes as a parameter name of the function which should be invoked and interval of time how often give function should be invoked. If you like ajax updates then I recommend you reading about about modules and ajax updates every X seconds, you will find more details there.
Conclusions
After reading this post you should know how to:
- simulate button click event via ajax and jQuery
- call ASP.NET method via Ajax after clicking on a button – ajax() jQuery function
- call server-side method periodically with setInterval() function
- create methods in ASP.NET pages which can be invoked by jQuery
And here is the final effect:

Can you explain the usage of the single quotations in this string?
“{‘content’:'” + $(“#ContentTextarea”).val() + “‘, ‘autosave’:'” + autosaveMode + “‘}”
Jacob
4 Nov 11 at 4:13 pm