rook
rook

Reputation: 67019

Sending a GET request to another domain using jQuery, http response not required

I need to send a GET request to another domain preferably using jQuery. This isn't a same origin policy bypass because I don't need to get a response. For instance using JavaScript I know I can do this:

document.write('<img src="http://somedomain.com/someapp.php?data='+data+'>')

Is there a better way using jQuery?

Upvotes: 1

Views: 1099

Answers (6)

Nick Craver
Nick Craver

Reputation: 630389

You can create the <img> element but do nothing with it...it'll cause an immediate fetch, resulting in a GET request:

$('<img src="http://somedomain.com/someapp.php?data='+data+'">');

Upvotes: 4

Dr.Molle
Dr.Molle

Reputation: 117324

There's no need to inject the <img> into the DOM.

Simply:

var request=$('<img/>').attr('src','http://somedomain.com/someapp.php?data='+data);

This will create a new img-Element, similar to new Image() . If there is a src-attribute provided, the image will be loaded(the request sended)

But I think it's not a better way, I's another way. It,s the jQuery-way to do Martin's Proposal.

However, it would be good if the requested ressource didn't produce large response, because the response will be loaded anyway.

Upvotes: 0

Martin
Martin

Reputation: 38289

I presume you don't need it in the DOM, so you could do this:

var img = new Image();
img.src = 'http://somedomain.com/someapp.php...' + ...;

Upvotes: 2

spender
spender

Reputation: 120440

You can attach script tags to the DOM using JS.

var scrElem=document.createElement("script");
scrElem.type="text/javascript"; //maybe not required
scrElem.src="http://bla";
document.getElementsByTagName("head")[0].appendChild(scrElem);

If you want to be really tidy about it, you could also give the script element an id attribute so you can remove it when it's done its job.

Alternatively, jQuery getScript wraps all this up nicely.

Upvotes: 0

Bang Dao
Bang Dao

Reputation: 5102

You can do like this:

 $('selector').append('<img width="0" height="0" src="http://somedomain.com/someapp.php?data=' + encodeURIComponent(data) + '>');

Upvotes: 0

0x1F602
0x1F602

Reputation: 865

Specifically, add it to the <head> element. I'm not sure if it works in IE.

Upvotes: 0

Related Questions