Since I spent a good deal of time on this (…), I am posting it here, hopefully it will be useful to someone. Anyway, take my advice and forget about all the XMLHttpRequest objects, ActiveXObjects (which work only in IE) or other frameworks built specifically for this, for example, I came across XHConn.
All you need is jQuery. I used version 1.4.1, which you already have in the template if you use VS 2010. In the end I picked 2 methods that work 100% in all 4 most widely used browsers (and it works on localhost too; I read somewhere that Chrome cannot do this on localhost, so I copied it to the hosting, but now I see that I was naive and foolish to believe it). I tested it in these browsers: Google Chrome 17.0.963.56 m, Opera 11.61, Mozilla Firefox 10.0.1 and IE 8 (as I wrote earlier, I do not like IE9 because in my opinion it is an even bigger piece of cr*p than IE8).
Now to the code itself. I did not try XML, but JSON works perfectly in all of them:
The simpler variant without parameters – the post method:
function send7() {
$.post('SayHello.ashx', {
'tab': 'opera',
'rat': '7'
}, function () {
//any code you want to run if the operation succeeds
});
} And the more complex variant with parameters – the ajax method:
function send9()
{
$.ajax ({
type: "GET",
url: 'SayHello.ashx',
data: { 'tab': 'opera', 'rat': '9' }, //"rat=9&tab=L" - as data you can pass either a QueryString or JSON while keeping everything else the same - both work
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false, //This is probably important for Chrome, which cannot handle asynchronous operations; I read about it too but did not try it
success: function (response)
{ //Any code to run on success
}
//error: branchAjaxFailed //-You can also output any code to run in case of an error
});
}You can pass null as the success method; you probably cannot do anything with the data anyway – apparently a bug in the parameter/method success. To get data, you have to call the get method (see below).
So the method cannot be used when you want to get data from the handler. Otherwise, the branchAjaxFailed method could look something like this if you wanted it:
function branchAjaxFailed(result)
{
alert("FAILED : " + result.status + ' ' + result.statusText);
}(the number after “send” is the sequence number of the method – I called them all at once and tested them. #justsayin).
And now the code of the ASHX handler:
<%@ WebHandler Language="C#" Class="SayHello" %>
using System; using System.Web; public class SayHello: IHttpHandler { public void ProcessRequest(HttpContext context) { string ratParam = context.Request.Params["rat"]; //-It is very useful that it returns strings directly rather than objects you would have to check for null and then convert with ToString() string tabParam = context.Request.Params["tab"]; //-If a parameter is not found, the website or the code will of course not crash, the variable will just be null string tab2Param = context.Request.Params["tab2"]; if (ratParam != null && tabParam != null) { string filePath = System.Web.Hosting.HostingEnvironment.MapPath("~/a.txt"); System.IO.File.AppendAllText(filePath, ratParam + " " + tabParam + Environment.NewLine); } } public bool IsReusable { get { return false; } } }As you can see, the handler wrote the contents of the parameters rat and tab to disk. The result (I changed the tab parameter in the JS before each browser) is as follows:
- 7 ie
- 9 ie
- 7 chrome
- 9 chrome
- 7 firefox
- 9 firefox
- 7 opera
- 9 opera
I also tried to get data from the handler with the .ajax method, but whether I called prompt or alert, nothing was displayed. So if you want to get data, you have to call the .get method and pass the parameters in the query string:
function get1()
{
$.get('SayHello.ashx?id=1', function (data)
{
$('#result').html(data);
});
}If you need to get multiple parameters, you simply have to parse them out of the parameter data.
When you call the get method, you have to write output in the handler, for example with the context.Response.Write method (here I return the query string parameter I passed to it – it works):
context.Response.Write(context.Request.QueryString["id"]);I also found examples of calling web services online, but I split things up – I will use web services (asmx) for communication between the website and desktop applications.
Handlers (ashx), on the other hand, for when a page needs something from the server without a reload/postback.