Using Rails to Pass Front-End JavaScript Data from an External API to the Controller

I need to retrieve coordinates from an external API, specifically the Google Maps API, and then send it to my controller. However, I am encountering a 500 internal server error when using jQuery/Ajax for this task. Researching the issue online suggests that it could be due to a cross-domain Ajax request. Below are the relevant code snippets in JavaScript and the controller:

JavaScript:

// Here is where the Google Maps API code resides. The points variable represents an object with an array of coordinates.
var points = polyline.GetPointsAtDistance(16000);

$.ajax({
    type: "POST",
    url: '/pages/calculate',
    data: {mydata: points},
    success: function(response) {
        // Add your response handling logic here
    }
});

Controller:

def calculate
    x = params[:mydata]
    # Perform operations using 'x'...
end

Is there a way to successfully transmit this JavaScript data to the controller? Would submitting the data through a hidden form be a viable alternative? Alternatively, if backend manipulation of Google Maps data is required, should a Google Maps gem be used to handle all data processing on the backend instead?

Answer №1

One way to retrieve data from an external API is by setting up an ActiveResource. This will allow you to easily access and manipulate the data for use in your controllers and views.

To learn more about ActiveResource, visit: [http://api.rubyonrails.org/v3.2.1/classes/ActiveResource/Base.html]

Alternatively, you can utilize a pre-built Gem for this purpose...

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Notification issues in Vue with Firebase Cloud Messaging while in foreground

I have been working on implementing FCM in my Vue PWA application. I have successfully configured background notifications, but I am facing issues with handling notifications when the app is open. Here is the code I am using. src/App.vue import firebase ...

Ways to display or conceal information depending on the dropdown choice

In my Angular project, I am dealing with a dropdown menu that is followed by some data displayed in a div element. component.html <select class="form-control" id="power" required> <option value="" disabled selected ...

Is it possible in ReactJS to return JSX from a callback function?

After spending some time working with react, I encountered a basic issue that has me stumped. In the Login component, I am submitting a form and if it returns an error, I want to render a snackbar message. handleSubmit = (event) => { event.preven ...

Puppet Master: Retrieve the inner content

Is there a way to retrieve the innerHTML or text of an element? Or even better, how can I click on an element with a specific innerHTML? The approach in regular JavaScript would be as follows: let found = false; $(selector).each(function() { if (found ...

What benefits does Node.js offer even if I don't need real-time capabilities?

As I weigh my options for backend development, Node.js with frameworks like express, meteor, or sails (known for social functionalities) has caught my attention. While real-time features are not a priority for my project, I'm considering using Node.js ...

What is the solution to resolving the warning about the router no longer defaulting the history prop to hash history?

I have implemented browser history in my code within routes.js export default ( <Router history={browserHistory}> <Route path="/" component={Main}> <Route path="home/:username" component={Home}> <IndexRoute co ...

Exploring Type Refinements with Flow

I keep encountering an issue indicating that 'The operand of an arithmetic operation must be a number.' despite having a runtime check at the beginning of the function to confirm that this.startedDateTime is indeed a number. I am puzzled as to wh ...

I am facing an issue where both curl and file_get_contents are not functioning properly after

When attempting to access a user's city information using coordinates, I have encountered an issue with the response not being displayed in my console. The process involves a javascript function that takes latitude and longitude data, sends it to a PH ...

React Native: Why is useState setter not causing a re-render?

As a beginner in react and javascript, I am facing an issue with showing an ActivityIndicator while logging in a user. The setIsLoading method doesn't seem to change the state and trigger a rerender. When the handleLogin method is called on a button c ...

Switching form field types with jquery

Hello there! I am currently attempting to use jQuery to change the type of <input> from submit to image so that an image is displayed instead of a button during the AJAX request. Here's what I have tried: $(document).ajaxStart(function() { ...

Trouble with sending data to child components via props

I've been trying to pass a prop to a child component in React, but when I check the props using console log, it doesn't show up at all. Even the key things is missing from the props. Any assistance with this would be greatly appreciated. export ...

Tips for picking out a particular item from a list of child elements

When I select the first parent's children array, it ends up selecting every other parent's children as well. This is due to index 0 remaining the same for all of them. How can I specify and highlight a specific child? Link: Check out the stackb ...

What is the correct method for verifying the presence of a field in JavaScript (or its frameworks)?

Is there a better way to rewrite this computed method in JavaScript to handle cases where a field may not be available? computed() { isVerified() { return this.name.info.is_valid; } } I can make it less verbose, but I want it to still functi ...

How can a JavaScript function be triggered by Flask without relying on any requests from the client-side?

I'm in the process of setting up a GUI server using Flask. The challenge I'm facing is integrating an API that triggers a function whenever there's a change in a specific Sqlite3 database. My goal is to dynamically update a table on the HTML ...

Guide on moving elements to a different list with the help of the Angular DragDrop CDK Service

I encountered a unique situation while working on my project where I needed to implement a drag and drop feature for multiple lists using Angular CDK's DragDrop service. While I was able to successfully move items within a single list, transferring an ...

Ensure that Ajax requests are successfully executed when a user navigates away from the page

I have developed an HTML/JavaScript application that requires an AJAX request to be made when the user refreshes or closes the page in order to close the application gracefully. To achieve this, I am using the pageunload event. I have implemented the func ...

Storing user data on the client side of a website is most effectively accomplished by

I am looking to incorporate the following features: I would like to personalize the user experience by greeting them with their login name on the webpage (e.g. 'Hello, Fred!'). I also want to display or hide certain content based on the user&apo ...

There are certain lines of JavaScript/Node.js code that are failing to execute

app.get is not being executed. I have also attempted to include app.listen(3000). My goal is to retrieve the parameter passed from the first web page. This code is designed to fetch parameters sent by another web page and then construct a MySQL query and ...

Retrieving additional parameters from an HTTP request

Imagine a scenario where I am sending a request to a Node Server in order to retrieve a JS file: <script src="/example.js" id="123456"> On the Node server side: app.get('/example.js', function(req, res, next) { console.log(req.params.id) ...

Dealing with a cross-domain web method that returns a 204 status code

I have implemented a Webmethod in ASP.NET and am attempting to access it through jQuery AJAX. When I request the Webmethod directly via browser, I receive a JSON response. However, when I make the call using jQuery AJAX, I am seeing "204 no content" in Fir ...