2

I've always done this way, with jsonp:

$.ajax({
    url         : 'http://domain.local/api/3/authentication/get-token',
    type        : 'POST',
    dataType    : 'jsonp',
    data        : 'username=user&secret=pass',
    success     : function(data) {
        console.log(data);
    }
});

It works perfectly with old jQuery versions (1.3, 1.4) but seems not to work with the latest ones (since 1.5.x, it makes a strange GET or OPTION request)

Any idea on how to fix that?

Thanks!

guillaumepotier
  • 7,369
  • 8
  • 45
  • 72
  • Not sure why it would work with an older JQ version, but cross-domain JSONP requests inserts a script tag and does not work with POST at all, at least as far as I know ? – adeneo Aug 03 '12 at 21:39
  • It works with 1.4.x, with POST method, and jsonp, but not later ones, I've just tested it – guillaumepotier Aug 03 '12 at 22:10

1 Answers1

0

It's been working for me with the new versions of jQuery. I think the problem is you're using a POST request, which isn't allowed with JSONP:

You can't POST using JSONP...it simply doesn't work that way, it creates a element to fetch data...which has to be a GET request. There's not much you can do besides posting to your own domain as a proxy which posts to the other...but user's not going to be able to do this directly and see a response though.

From How to use type: "POST" in jsonp ajax call

Your call should look like this:

$.ajax({
    url         : 'http://domain.local/api/3/authentication/get-token',
    type        : 'GET',
    dataType    : 'jsonp',
    data        : 'username=user&secret=pass',
    success     : function(data) {
        console.log(data);
    }
});

If the above doesn't work, try looking at the parameters sent using Firebug. jQuery should send a "callback" parameter with a value like "jQuery1710013558088336139917_1344030860953."

Also look at the response from the server. The server should be returning be returning data which looks like the following:

jQuery1710013558088336139917_1344030860953({"data":"goes here"})
Community
  • 1
  • 1
jeff
  • 8,300
  • 2
  • 31
  • 43
  • jQuery should automatically use GET when a datatype of JSONP is used, so setting the type to POST should'nt really cause an error, but given the right circumstances anything is possible i guess ? – adeneo Aug 03 '12 at 21:50
  • Should, however we'd have to go to the core to confirm that. Best to just make it get to begin with though since that's what it has to be. – Kevin B Aug 03 '12 at 21:53
  • Thanks for your answer. But it IS working perfectly with 1.4.x but not later versions, with POST method. Why changing that :( in my API I want to use POST / PUT / PATCH to be REST compliant, and not being able to make a doc testing them with $.ajax is really bothering me :( – guillaumepotier Aug 03 '12 at 22:09