Reputation: 3402
I want to do a fire-and-forget jQuery call to a web service.
Basically, I want to send a JSON object to http://myservice.com/uservisits/create
and I don't care to receive any kind of return response. However, we want to use the same service for several of our domains, which means coming up against the cross-domain restrictions tied to Ajax.
How do you do this? There's a lot out there on JSONP and such, but I don't need to handle a response. I feel like I'm missing an obvious detail.
Upvotes: 10
Views: 1302
Reputation: 91527
The easiest way to send an http GET request is with an image beacon:
var json = encodeURIComponent(JSON.stringify(obj));
new Image().src = "http://myservice.com/uservisits/create?JSON=" + json;
And, you can even get a little bit of information back by handling the load
and error
events. Of course, if the response is not an image, the error
event will be called, and not load
. You can set your service to return a single pixel image to solve that.
Edit: You mentioned you may prefer to use an HTTP POST. It's not nearly as simple as an image beacon, but you can make a cross-domain post using a hidden iframe:
var frame = $("<iframe>").hide();
frame.load(function() {
var frameBody = frame.contents().find("body");
var form = $("<form>", {
action: "http://myservice.com/uservisits/create",
method: "POST"
});
form.appendTo(frameBody);
$("<input/>", {
name: "json",
value: json
}).appendTo(form);
form[0].submit();
});
frame.appendTo("body");
I think jQuery has something like this built in already. You might try digging through the jQuery.ajax
documentation. If not, you could probably find a plugin that does it.
Upvotes: 8
Reputation: 44939
The fact that you are not processing the response does not affect the same origin policy problem that you are facing. But, the fact that you will control all the consumers of the service opens up the possibility of using CORS. However, not all browsers support CORS. See the browser compatibility chart. If you need to support other browsers you still have to use JSONP.
Upvotes: 2
Reputation: 5303
The fact that you dont want any data back is actually irrelevant you still face the same cross domain problems. There are two ways you can go...
1) You can use jsonp (which actually makes a get request) to send the data across although this feels a little messy as you should try to use http verbs for their intention (ie GET should retrieve data).
2) You can use ARR (application request routing in IIS) to basically rewrite the request. So you would setup a rule for each domain to have a rewrite rule e.g. www.mydomain.com/webcall routes to http://myservice.com/uservisits/create where mydomain.com is the domain where the ajax call is being initiated. If you do this then you can use ajax in the normal fashion because as far as the browser is concerned you are now making requests on the same domain
Upvotes: 1