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.
Cross-domain policy (or same-origin policy) prevents client JavaScript, loaded from one domain, from accessing or manipulating the properties of a document from another domain. In short, the domain being requested from the client script must match the domain of the current web browser page.
ajax({ url: 'proxy. php', type: 'POST', data: { address: 'http://www.google.com' }, success: function(response) { // response now contains full HTML of google.com } });
d. If you put only response in alert it will show you something like [Object] in the alert. Suppose, response contains a message "Ajax call made successfully" then to see the message you have to use response. d ("d") property of response. Follow this answer to receive notifications.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With