SemperFly
SemperFly

Reputation: 1583

Send GET Request to HTTP Server; don't care about the response

I'm trying to contact a server using $.get(). I don't care about the response. My purpose is to log some data about a user's action (what they clicked, etc). When the user clicks something, $.get is called like so:

$.get(
        "http://www.some-server.com/log.txt?click=1", 

        function (data)
        {
        },

        "text"
);

The server handles that get request accordingly. I get the following error when the function executes:

XMLHttpRequest cannot load ... is not allowed by Access-Control-Allow-Origin.

If I change datatype to jsonp, I do not get that error but when the jquery callback tries to evaluate the log server's response as JSON, it tells me "whateverwasreturned" is not defined. I'm not able to change anything on the log server.

Upvotes: 3

Views: 2224

Answers (6)

sethvargo
sethvargo

Reputation: 26997

You can use the pure ajax call:

$.ajax({
  url: 'http://www.some-server.com/log.txt?click=1',
  dataType: 'jsonp',
  crossDomain: true,
  success: function(data) { /* do nothing */ }
});

Upvotes: 0

Oleg Grishko
Oleg Grishko

Reputation: 4281

You can keep using JSONP, but make your log.txt return an empty JSON object: {}.

Upvotes: 0

Kamil Lach
Kamil Lach

Reputation: 4629

Becouse of same origin policy you cannot send ajax query to other domain (then script executes) but as you discover you can use jsonp but only when server support it (server basicly waraps JSON) and there is method for that $.getJson(..) it's easier way to call $.ajax(..)

http://api.jquery.com/jQuery.getJSON/

example of server side (in php) that supports jsonp: http://www.geekality.net/2010/06/27/php-how-to-easily-provide-json-and-jsonp/

Upvotes: 0

Alex Schenkel
Alex Schenkel

Reputation: 832

If you're using jquery, just add a script tag to avoid the same-origin-policy problem:

$('body').append('<script src="http://www.some-server.com/log.txt?click=1"></script>');

Upvotes: 1

Marc B
Marc B

Reputation: 360612

Not sure if you'll be able to... if you were talking to your own server, then it'd be simple to tell JS to treat the response as plaintext and not try to decode it. But once you're doing JSONP, then jquery is really just building a <script src="http://otherserver.com"></script> block and inserting it, means which means the remote server must reponse with valid JS code.

One alternative would be to load an image containing your json p url. The image itself would be "broken", but would still trigger a GET request.

Upvotes: 0

Diodeus - James MacFarlane
Diodeus - James MacFarlane

Reputation: 114367

Use a "tracking pixel" technique instead:

<img src="http://www.some-server.com/log.txt?click=1" height="1" width="1">

Just insert the HTML into the DOM when needed.

Upvotes: 6

Related Questions