PoeHaH
PoeHaH

Reputation: 1936

cross domain with jsonp and jquery

I am doing a cross-domain request from site1.com to site2.com (both maintained by me)

This is the jquery code on site1.com :

$.ajax({
        type: 'POST',
        url: 'http://site2.com/test/carrousel.cfm',
        cache: false,
        async: true,
        crossDomain: true, 
        dataType: "jsonp",
        success: function (data, status) {
           alert(data);}
        },
        error: function (xhr, textStatus, errorThrown) {
           alert('error');
        }
    });

I can see the request coming in with status 200 in the debugger. The response body also contains the string that I'm sending from the server. That string is: "okay"

Strange enough, the error handler is always fired and I can't access the data. I'm sending the Access-Control-Allow-Headers and Access-Control-Allow-Origin headers via the server too (I came across some posts asking to do this)

I also get a script error saying 'OKAY' is undefined. 'OKAY' is the string I get as a reply from the server. How come this is happening? And How can I get this cross domain request to succeed?

I'm using JQUERY 1.10.2 & IE 10

As you can see I'm also using jsonp & the right parameters as defined in the jquery documentation to perform cross domain requests

Upvotes: 0

Views: 1019

Answers (2)

Ninioe
Ninioe

Reputation: 520

You should try Ajax-cross-origin a jQuery plugin.

http://www.ajax-cross-origin.com/

$.ajax({
    crossOrigin: true,
    url: url,
    success: function(data) {
        console.log(data);
    }
});

You will be able to use ajax cross domain with no limitation!

Upvotes: 1

apsillers
apsillers

Reputation: 115940

Here's a simple JSONP excahnge:

  1. The client makes a <script src="target.js?arg=foo"> tag

  2. The server gets the request for target.js.

  3. The PHP server-side body of target.js is clientFunction("$_GET['arg']")

  4. The client gets back a script: clientFunction("foo")

  5. The client executes the script, which causes the client-side function clientFunction to run, with the argument "foo".

The obvious takeaway here is: JSONP responses are scripts. If your client asks for a JSONP response, it is asking for a script. The content "okay" is therefore being treated as a script, but okay hasn't been declared as a valid identifier in your client scripting environment, so it causes an error. (In my example above, we assume that clientFunction has been declared client-side before the exchange takes place.)

If you have control over the server and can serve CORS headers like Access-Control-Allow-Origin, then you don't need JSONP. Just make a normal Ajax request.

Upvotes: 0

Related Questions