Rails - How to send front-end javascript data retrieved from an external API to the controller

1.2k views Asked by At

As the question states, I want to retrieve some coordinates from an external API (the google maps API) and send it to my controller. Currently I am using jQuery/Ajax but I am getting a 500 internal server error. I googled the error and it appears that I may be making a cross-domain ajax request. Here is the relevant javascript and controller code:

Javascript:

//google maps API code goes here. The points variable ultimately gives me an object with an array of coorindates. 
var points = polyline.GetPointsAtDistance(16000);

$.ajax({
    type: "POST",
    url: '/pages/calculate',
    mydata: points,
    success: function(response) {
    //do something with the response here
    }
});

Controller:

def calculate
    x = params[:mydata]
    #do something with x ...
end

Is it possible to send this javascript data to my controller? Can I somehow submit the data using a hidden form instead? Or, if I want to manipulate the google maps data on the backend, do I have to use a google maps gem and perform all my data manipulation on the backend?

1

There are 1 answers

2
Andrew On

If you are looking to get data from an external API, consider setting up an ActiveResource for that. Doing this will make the data available for you to both manipulate as needed and provide to controller/views.

Check here for more details: [http://api.rubyonrails.org/v3.2.1/classes/ActiveResource/Base.html]

Or you could just use an already built Gem...