Mohamed Emad Hegab
Mohamed Emad Hegab

Reputation: 2675

jQuery: Cross-domain POST on Rails

I'm trying to make a post request to another domain using the following code

  $.ajax({
    url: "http://domainName.com/api/v1/statistics/1",
    crossDomain: true,
    type: 'POST',
    dataType: 'jsonp'
  });

but it gives me the error (404) and it seems that it sees the request as get request no matter what

Upvotes: 1

Views: 819

Answers (2)

Niels
Niels

Reputation: 49919

You can not POST through JSONP. You can only use GET.

Also the domain name should contain: http:// to access the external document. I hope you know you have to create a function for using JSONP. The default callback function is called callback so your response should be something like:

callback({ "data" : "data"});

The callback function ?callback=? will autoomaticly be added to the URL. If you have a rewrite you have to use $_GET['callback'] to get the callback function.

From the jQuery docs:

"jsonp": Loads in a JSON block using JSONP. Adds an extra "?callback=?" to the end of your URL to specify the callback. Disables caching by appending a query string parameter, "_=[TIMESTAMP]", to the URL unless the cache option is set to true.

EDIT

Your request will look something like:

$.ajax({
    url: "http://domainName.com/api/v1/statistics/1",
    crossDomain: true,
    dataType: 'jsonp',
    jsonp : "mycallback",
    success : function(data){
        console.log(data.thiskey); // Will log OK
    }
});

Now the request URL to your API will look like this (jQuery will append the ?callback=mycallback):

http://domainName.com/api/v1/statistics/1?callback=mycallback

In your response you have to create a function call so it will call the jQuery Ajax function. This result needs to look something like this:

mycallback({ thiskey : "OK" }); // The data in this call can be retreived at the success function

In the success function you are able to retreive your data like:

success : function(data){
    console.log(data.thiskey); // Will log OK
}

Upvotes: 4

Richard Peck
Richard Peck

Reputation: 76784

CORS

Further to Niels' answer, you must appreciate that cross-domain data sending is depended on the CORS policy of the "target" domain

Basically, "foreign" ajax requests are by default denied by the middleware of the server, unless you use some sort of CORS middleware to create some endpoints to access

If you get your 404 error out of the way, you should look at using something like Rack-CORS to provide Cross-Domain Origin support for your app (allowing cross-domain asynchronous data transfer)

Upvotes: 1

Related Questions