Krimo
Krimo

Reputation: 954

$.get(url) same as appending image to the DOM?

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.

Upvotes: 1

Views: 711

Answers (2)

David Hedlund
David Hedlund

Reputation: 129792

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.

Upvotes: 0

Pekka
Pekka

Reputation: 449415

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.

Upvotes: 6

Related Questions