1

UPDATE: Let me specify a few things. This GET request (to another domain) should happen after a form submitted through AJAX successfully (it counts the number of conversions coming from a specific referrer). So the response is indeed irrelevant, what matters most is that the GET request is successful, and of course that I keep the code to a minimum.

Quick question, are these two lines pretty much the same thing ? (what I need is a get request to the url) :

$('body').append('<img height="1" width="1" style="border-style:none;" alt="" src="url"/>');

And

$.get(url);

My apologies if this sounds idiotic, but I need to be sure.

Thank you.

Krimo
  • 954
  • 8
  • 20

2 Answers2

6

are these two lines pretty much the same thing

In terms of making a GET request to the URL - yes. But in terms of using the data - no.

One creates an image element with url as the image source. If the response is not valid image data, rendering it will fail. The GET request will always be made, though.

The other makes an Ajax request to url. If it's an image resource, the response will contain image data - but you're going to have a hard time displaying it (you'd have to base64 encode it first and show as a data: URL, or insert it into a canvas element, both of which methods don't have 100% browser support.) Also, request to remote URLs won't work.

Pekka
  • 442,112
  • 142
  • 972
  • 1,088
  • Given the image's 1x1 dimension, I don't reckon it'll contain image data, but rather, that appending the image was a hack for causing something to happen serverside, disregarding the response entirely. While your answer is technically a correct answer to the question, I think Dogbert is adressing the critical aspects of what should have been OP's question. – David Hedlund Nov 22 '11 at 09:27
  • I am only concerned with sending a get request to the url, not retrieve any image data. – Krimo Nov 22 '11 at 09:28
0

As you've probably realized, the first code snippet inserts an image to the document body, while the second submits an AJAX request.

You've indicated that you're only interested in sending the request, and have no interest in the response. As such, Dogbert pointed out the main critical aspect in his (albeit deleted) answer:

  • The AJAX solution will only work when the request is confined to the same domain and port
  • The image solution will only ever be able to submit GET requests

On top of that, I would like to point out a few things:

  • The image solution is using the img tag for something other than what it was intended for. This may be a minor point, but it still makes me opt for AJAX when that is an option.
  • Sending an $.ajax request you'll have the option to specify dataType: 'jsonp' which will work around the same domain prerequisite.
  • With AJAX, you'll have a lot more control over your request, such as the ability to specify a POST, or to be notified when the request fails.
David Hedlund
  • 128,221
  • 31
  • 203
  • 222