Recently I ran across a need to log some information about a user performing a certain action but I did not want to wait for a success or failure response from the server. I just wanted to fire off the request and forget about it. I will outline some basics on how you can achieve this. The code provided is using jQuery, C# and .NET. First lets write the code for the logging on our server side.
Now for the above to work there are a few conditions that must be met.
- We have to decorate the function with a [WebMethod(true)] attribute.
- We have to make it a static function.
- This function MUST be written within a .aspx file. (cannot be in a .ascx control or a master page and it cannot be within a standalone class.)
- Here I have added the code to my Default.aspx page code behind.
Now that we have the code behind we need a way to trigger it. So lets write some jQuery that will call into this method and then forget about the response.
In jquery we will create the path to where the web method resides. This is the full path with protocol host and page path all included. If you notice we are doing a short form if statement that allows his script to work even if we are debugging the application locally (So you will need to replace AppName with the name of your website). The script fires each time the users clicks on an html element with id="someElem".
And that's all it takes!