ASP.NET 1.1 Web Services & jQuery - asp.net

I've been looking for an example of a 1.1 web service getting called using jQuery. I'd like to call a web service and pass a few parameters to it.
Can someone point me in the right direction?
Thanks!

Without more details on the web service, the generic answer is "use an AJAX call". The example below sends data in a JSON format, and retrieves JSON data back.
$.ajax({
type: "POST",
url: "theWebServiceURL",
data: {'key1':'value1','key2':'value2'},
dataType: /* depends on the return of the web service */,
success: function(data) { /* do stuff here */ };
});
There are some peculiarities sometimes on sending the data, if you need to send data.
UPDATE: Given John Saunder's post, I thought I'd expand on the last sentence. ASP.NET v1.1 accepts (by default) HTTP GET, HTTP POST or HTTP SOAP. What one particular web service is set to accept basically dictates how the whole AJAX request must be sent to the web service. Using jQuery, you are mainly going to go to HTTP GET or HTTP POST. (Unless you get fancy and set processData: false. You then create and send your SOAP-formatted (XML) data and set content-type to text/xml, but I've never done this, so I am unsure of the details.)

Just following up on this in case anyone else needs it in the future. I was able to call the 1.1 web service by using the ajax method and a POST:
$.ajax({
type: "POST",
url: 'PathToYourService.asmx/FunctionName',
data: 'foo1=value1&foo2=value&foo3=value',
dataType: "xml",
success: function(xml) {
//do something with your data
}
});

I don't believe that .NET 1.1 Web Services suppoted JSON. That's stuff from back around 2002 or 2003. You'll have to use SOAP, or else upgrade, preferably to .NET 3.5 SP1 (the current release).

Here's a solid set to get you started:
For specific ASP examples, see Using jQuery to directly call ASP.NET AJAX page methods
For details on various ways you can make calls, check out the jQuery AJAX documentation.
To monitor your calls and responses, consider using something like Firebug for Firefox
You also want to review 3 mistakes to avoid when using jQuery with ASP.NET AJAX
Good luck! M

Related

Why a browser only supports GET and POST HTTP methods?

I read the following text from Apress Apache Tomcat 7
The HttpServlet.service() method implementation is a convenient way to
control access to your servlets in the code. For example, servlets
that delete data from the database should always be accessed using the
DELETE method, but because browsers only support GET and POST
operations, the POST method should be used instead.
It seems most browsers only supports 2 HTTP methods, GET and POST.
If so, why?
In a form the only possible methods are GET and POST. When you make an AJAX call, other methods are supported.
<form>:
method = get|post [CI]
This attribute specifies which HTTP method will be used to submit the form data set. Possible (case-insensitive) values are "get" (the
default) and "post".
XMLHttpRequest:
method
The HTTP method to use, such as "GET", "POST", "PUT", "DELETE", etc. Ignored for non-HTTP(S) URLs.
There are modern browsers which allow GET, POST, PUT and DELETE using the XMLHttpRequest. You can go through this bug 10671
Executing PUT and DELETE to modify resources on the origin server is
straight-forward for modern Web browsers using the XmlHttpRequest
object. For unscripted browser interactions this not so simple.
Typically, devs and frameworks end up creating work-arounds that mimic
the HTTP PUT/DELETE + Etag interaction using a "POST FORM" coupled
with specialized server-side code to sort out the special case and act
as if the proper HTTP Method was used in the request
Other considerations:
Using POST as a tunnel instead of using PUT/DELETE can lead to
caching mis-matches (e.g. POST responses are cachable5, PUT responses
are not[6], DELETE responses are not[7])
Using a non-idempotent method (POST) to perform an idempotent
operation (PUT/DELETE) complicates recovery due to network failures
(e.g. "Is is safe to repeat this action?").
You can also refer this thread: Are the PUT, DELETE, HEAD, etc methods available in most web browsers?

SignalR - Persistent Connection - Cross Domain - Null Data Received

I am using SignalR Persistent Connections with Cross-Domain support and I am able to successfully start a connection, however when I send data from client to server, the server OnReceived method gets invoked, however the data field is always null.
I have traced into SignalR client script and there is valid data at client send time.
Has anyone experienced this ?
I resolved the issue. The resolution has nothing to do with the environment being cross-domain. It seems that SignalR assumes that the jQuery $.ajaxSetup defaults are consistent with what SignalR needs, which is a bad assumption....so I had to reset the Ajax defaults prior to using SignalR....
$.ajaxSetup({
processData: true,
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
dataType: "text"
});

ASP.NET MVC3 Ajax error response vs HTTP 4XX

I have an asp.net MVC3 application that makes Ajax calls to the server on various occassion. We have a debate in our team on how to handle error response:
Option 1: Use HTTP status code to return back an error response, and have the ajax failure handler bind to the function that needs to be called on error.
Option 2: Use a header/payload concept using JSON, with a structure similar to
response:
success: true
text: <status text>
....
payload: <actual response>
The argument for first is - why not reuse the mechanism provided by HTTP and Ajax.
The argument for second is - Let alone the onFailure ajax handler to deal with 'genuine' http errors (e.g caused by network failure etc..) and have a uniform contract between the client and server for application's success and error response. Parse the response to get failure/success and status text.
Thoughts on both approaches are welcome. Thanks.
I would go with the first approach. The HTTP protocol already provides all the mechanisms, so why does each developer should reinvent error handling everytime? If you return 200 status code intermediaries such as proxy servers has no way of knowing that this response should not be cached.

Sending Zip file to Client via Response - incorrect type being sent

OK, I've been pulling my hair out about this for ages. I have a WebService which sends a zip file to the browser. This works; when I test the WebService and 'invoke' the method through it directly, the zip file is downloaded to the browser correctly.
The problem arises when I use jQuery to send an AJAX request to the WebService - the zip file is downloaded to the response, but it stays in the response and doesn't download as a file.
Here is my code:
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.ContentType = "application/zip";
HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=pleasework.zip");
using (ZipFile zip = new ZipFile())
{
zip.AddDirectory("c:\\inetpub\\mediaserver\\music\\mixes");
zip.AddFile("c:\\test.txt");
zip.AddFile("c:\\test2.txt");
zip.Save("c:\\filename.zip");
}
HttpContext.Current.Response.TransmitFile("c:\\iloveshrooms.zip");
return "done";
}
Now this works since the file downloads when I use the 'invoke' function when navigating directly to the service.
Here is my jQuery AJAX request...
function getFile() {
alert("sending POST request...");
$.ajax({
type: 'POST',
url: 'ZipService.asmx/GetZipFile HTTP 1.1',
contentType: "application/x-www-form-urlencoded",
data: '{ "path":"c:\\inetpub\\mediaserver\\music\\mixes" }',
dataType: '',
beforeSend: function(xhr) {xhr.setRequestHeader("Accept","application/zip");},
success: function() {alert(":-)");},
failure: function() {alert(":-(");}
});
}
I added the code in 'beforeSend' so that the request states explicitly what type of response the browser should expect.
I've been using Firebug to monitor the request/response headers and can't see anything wrong with them (except when I look at the content of the response, it's full of binary data AND its the same size as the file I'm sending.
I just attempted to upload screen-dumps of the request/response headers and the content of the reponse but I don't have enough reputation points to do this yet :-(
The Response is the same size of the Zip file so I'm assuming its being sent back to the browser, but the browser doesn't know what to do with it.
Tested in IE, FF & Chrome and the results are consistent.
If anyone could shed any light on this I'd greatly appreciate it!
There are a couple of easy solutions.
Convert your server procedure to use a GET request, you can use window.open, to initialize the download.
window.open('your_procedure_url?parameter=xyz')
If you want stick with POST, you can create a hidden form, with inputs for each of the parameters. Set the form action to POST to your service url and use form.submit() to launch the download.
1st. Don't make it a webservice. If it always delivers a zip file, why is it not an aspx or a ashx? A resource that is requested by a script, need not be an ASMX.
2nd. it's not true that you cannot receive a binary file in AJAX or javascript. You can. For example, see Unzipping zip archives with Javascript.
But make sure you actually want to handle the zip file in script. In most cases you want to let the user save the zip file to the filesystem.

asmx WebMethod caching on POST request in asp.net

I am using jQuery to get back some JSON data from the server. I am using a POST verb, but even after setting the WebMethod CacheDuration attribute, the JSON doesn't get cached.
I checked the response headers with firebug and the Cache-Control is still set to no-cache.
How can i cache these request on the client and avoid the server to be hit every time.
UPDATE
After reading this post from scottGu I thought it would have been safe to go on to use a POST request. Does his post not apply to the kind of operation i would be trying to do ? (getting data from the server without modifying it). In fact after changing the verb to GET, i am not even getting to the web service ...
You should be using a get request. Post does not cache by default. You can try to get a post to cache by using .ajax() and setting cache to true and type to post. I cannot say that this will work as typically you would not expect a post to cache. I suggest using get.
E.g
$.ajax( { url: '/bla',
type : 'post',
data : dataObj,
cache : true } );
Use the GET keyword instead if you want to use caching. There is a similar question on SO.
I've noticed differences in the way ASP.NET caches responses depending upon whether the caching parameters are query string parameters or (in my case with ASP.NET MVC) route parameters.
I never completely figured out exactly what the conditions were, but this may help someone.

Resources